babylon.max.js 3.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var Color3 = (function () {
  23. /**
  24. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  25. */
  26. function Color3(r, g, b) {
  27. if (r === void 0) { r = 0; }
  28. if (g === void 0) { g = 0; }
  29. if (b === void 0) { b = 0; }
  30. this.r = r;
  31. this.g = g;
  32. this.b = b;
  33. }
  34. /**
  35. * Returns a string with the Color3 current values.
  36. */
  37. Color3.prototype.toString = function () {
  38. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  39. };
  40. /**
  41. * Returns the string "Color3".
  42. */
  43. Color3.prototype.getClassName = function () {
  44. return "Color3";
  45. };
  46. /**
  47. * Returns the Color3 hash code.
  48. */
  49. Color3.prototype.getHashCode = function () {
  50. var hash = this.r || 0;
  51. hash = (hash * 397) ^ (this.g || 0);
  52. hash = (hash * 397) ^ (this.b || 0);
  53. return hash;
  54. };
  55. // Operators
  56. /**
  57. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  58. * Returns the Color3.
  59. */
  60. Color3.prototype.toArray = function (array, index) {
  61. if (index === undefined) {
  62. index = 0;
  63. }
  64. array[index] = this.r;
  65. array[index + 1] = this.g;
  66. array[index + 2] = this.b;
  67. return this;
  68. };
  69. /**
  70. * Returns a new Color4 object from the current Color3 and the passed alpha.
  71. */
  72. Color3.prototype.toColor4 = function (alpha) {
  73. if (alpha === void 0) { alpha = 1; }
  74. return new Color4(this.r, this.g, this.b, alpha);
  75. };
  76. /**
  77. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  78. */
  79. Color3.prototype.asArray = function () {
  80. var result = [];
  81. this.toArray(result, 0);
  82. return result;
  83. };
  84. /**
  85. * Returns the luminance value (float).
  86. */
  87. Color3.prototype.toLuminance = function () {
  88. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  89. };
  90. /**
  91. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  92. * Returns this new object.
  93. */
  94. Color3.prototype.multiply = function (otherColor) {
  95. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  96. };
  97. /**
  98. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  99. * Returns the current Color3.
  100. */
  101. Color3.prototype.multiplyToRef = function (otherColor, result) {
  102. result.r = this.r * otherColor.r;
  103. result.g = this.g * otherColor.g;
  104. result.b = this.b * otherColor.b;
  105. return this;
  106. };
  107. /**
  108. * Boolean : True if the rgb values are equal to the passed ones.
  109. */
  110. Color3.prototype.equals = function (otherColor) {
  111. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  112. };
  113. /**
  114. * Boolean : True if the rgb values are equal to the passed ones.
  115. */
  116. Color3.prototype.equalsFloats = function (r, g, b) {
  117. return this.r === r && this.g === g && this.b === b;
  118. };
  119. /**
  120. * Multiplies in place each rgb value by scale.
  121. * Returns the updated Color3.
  122. */
  123. Color3.prototype.scale = function (scale) {
  124. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  125. };
  126. /**
  127. * Multiplies the rgb values by scale and stores the result into "result".
  128. * Returns the unmodified current Color3.
  129. */
  130. Color3.prototype.scaleToRef = function (scale, result) {
  131. result.r = this.r * scale;
  132. result.g = this.g * scale;
  133. result.b = this.b * scale;
  134. return this;
  135. };
  136. /**
  137. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  138. */
  139. Color3.prototype.add = function (otherColor) {
  140. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  141. };
  142. /**
  143. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  144. * Returns the unmodified current Color3.
  145. */
  146. Color3.prototype.addToRef = function (otherColor, result) {
  147. result.r = this.r + otherColor.r;
  148. result.g = this.g + otherColor.g;
  149. result.b = this.b + otherColor.b;
  150. return this;
  151. };
  152. /**
  153. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  154. */
  155. Color3.prototype.subtract = function (otherColor) {
  156. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  157. };
  158. /**
  159. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  160. * Returns the unmodified current Color3.
  161. */
  162. Color3.prototype.subtractToRef = function (otherColor, result) {
  163. result.r = this.r - otherColor.r;
  164. result.g = this.g - otherColor.g;
  165. result.b = this.b - otherColor.b;
  166. return this;
  167. };
  168. /**
  169. * Returns a new Color3 copied the current one.
  170. */
  171. Color3.prototype.clone = function () {
  172. return new Color3(this.r, this.g, this.b);
  173. };
  174. /**
  175. * Copies the rgb values from the source in the current Color3.
  176. * Returns the updated Color3.
  177. */
  178. Color3.prototype.copyFrom = function (source) {
  179. this.r = source.r;
  180. this.g = source.g;
  181. this.b = source.b;
  182. return this;
  183. };
  184. /**
  185. * Updates the Color3 rgb values from the passed floats.
  186. * Returns the Color3.
  187. */
  188. Color3.prototype.copyFromFloats = function (r, g, b) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. };
  194. /**
  195. * Updates the Color3 rgb values from the passed floats.
  196. * Returns the Color3.
  197. */
  198. Color3.prototype.set = function (r, g, b) {
  199. return this.copyFromFloats(r, g, b);
  200. };
  201. /**
  202. * Returns the Color3 hexadecimal code as a string.
  203. */
  204. Color3.prototype.toHexString = function () {
  205. var intR = (this.r * 255) | 0;
  206. var intG = (this.g * 255) | 0;
  207. var intB = (this.b * 255) | 0;
  208. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  209. };
  210. /**
  211. * Returns a new Color3 converted to linear space.
  212. */
  213. Color3.prototype.toLinearSpace = function () {
  214. var convertedColor = new Color3();
  215. this.toLinearSpaceToRef(convertedColor);
  216. return convertedColor;
  217. };
  218. /**
  219. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  220. * Returns the unmodified Color3.
  221. */
  222. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  223. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  224. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  225. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  226. return this;
  227. };
  228. /**
  229. * Returns a new Color3 converted to gamma space.
  230. */
  231. Color3.prototype.toGammaSpace = function () {
  232. var convertedColor = new Color3();
  233. this.toGammaSpaceToRef(convertedColor);
  234. return convertedColor;
  235. };
  236. /**
  237. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  238. * Returns the unmodified Color3.
  239. */
  240. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  241. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  242. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  243. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  244. return this;
  245. };
  246. // Statics
  247. /**
  248. * Creates a new Color3 from the string containing valid hexadecimal values.
  249. */
  250. Color3.FromHexString = function (hex) {
  251. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  252. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  253. return new Color3(0, 0, 0);
  254. }
  255. var r = parseInt(hex.substring(1, 3), 16);
  256. var g = parseInt(hex.substring(3, 5), 16);
  257. var b = parseInt(hex.substring(5, 7), 16);
  258. return Color3.FromInts(r, g, b);
  259. };
  260. /**
  261. * Creates a new Vector3 from the startind index of the passed array.
  262. */
  263. Color3.FromArray = function (array, offset) {
  264. if (offset === void 0) { offset = 0; }
  265. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  266. };
  267. /**
  268. * Creates a new Color3 from integer values ( < 256).
  269. */
  270. Color3.FromInts = function (r, g, b) {
  271. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  272. };
  273. /**
  274. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  275. */
  276. Color3.Lerp = function (start, end, amount) {
  277. var r = start.r + ((end.r - start.r) * amount);
  278. var g = start.g + ((end.g - start.g) * amount);
  279. var b = start.b + ((end.b - start.b) * amount);
  280. return new Color3(r, g, b);
  281. };
  282. Color3.Red = function () { return new Color3(1, 0, 0); };
  283. Color3.Green = function () { return new Color3(0, 1, 0); };
  284. Color3.Blue = function () { return new Color3(0, 0, 1); };
  285. Color3.Black = function () { return new Color3(0, 0, 0); };
  286. Color3.White = function () { return new Color3(1, 1, 1); };
  287. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  288. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  289. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  290. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  291. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  292. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  293. return Color3;
  294. }());
  295. BABYLON.Color3 = Color3;
  296. var Color4 = (function () {
  297. /**
  298. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  299. */
  300. function Color4(r, g, b, a) {
  301. if (r === void 0) { r = 0; }
  302. if (g === void 0) { g = 0; }
  303. if (b === void 0) { b = 0; }
  304. if (a === void 0) { a = 1; }
  305. this.r = r;
  306. this.g = g;
  307. this.b = b;
  308. this.a = a;
  309. }
  310. // Operators
  311. /**
  312. * Adds in place the passed Color4 values to the current Color4.
  313. * Returns the updated Color4.
  314. */
  315. Color4.prototype.addInPlace = function (right) {
  316. this.r += right.r;
  317. this.g += right.g;
  318. this.b += right.b;
  319. this.a += right.a;
  320. return this;
  321. };
  322. /**
  323. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  324. */
  325. Color4.prototype.asArray = function () {
  326. var result = [];
  327. this.toArray(result, 0);
  328. return result;
  329. };
  330. /**
  331. * Stores from the starting index in the passed array the Color4 successive values.
  332. * Returns the Color4.
  333. */
  334. Color4.prototype.toArray = function (array, index) {
  335. if (index === undefined) {
  336. index = 0;
  337. }
  338. array[index] = this.r;
  339. array[index + 1] = this.g;
  340. array[index + 2] = this.b;
  341. array[index + 3] = this.a;
  342. return this;
  343. };
  344. /**
  345. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  346. */
  347. Color4.prototype.add = function (right) {
  348. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  349. };
  350. /**
  351. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  352. */
  353. Color4.prototype.subtract = function (right) {
  354. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  355. };
  356. /**
  357. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  358. * Returns the Color4.
  359. */
  360. Color4.prototype.subtractToRef = function (right, result) {
  361. result.r = this.r - right.r;
  362. result.g = this.g - right.g;
  363. result.b = this.b - right.b;
  364. result.a = this.a - right.a;
  365. return this;
  366. };
  367. /**
  368. * Creates a new Color4 with the current Color4 values multiplied by scale.
  369. */
  370. Color4.prototype.scale = function (scale) {
  371. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  372. };
  373. /**
  374. * Multiplies the current Color4 values by scale and stores the result in "result".
  375. * Returns the Color4.
  376. */
  377. Color4.prototype.scaleToRef = function (scale, result) {
  378. result.r = this.r * scale;
  379. result.g = this.g * scale;
  380. result.b = this.b * scale;
  381. result.a = this.a * scale;
  382. return this;
  383. };
  384. /**
  385. * Multipy an RGBA Color4 value by another and return a new Color4 object
  386. * @param color The Color4 (RGBA) value to multiply by
  387. * @returns A new Color4.
  388. */
  389. Color4.prototype.multiply = function (color) {
  390. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  391. };
  392. /**
  393. * Multipy an RGBA Color4 value by another and push the result in a reference value
  394. * @param color The Color4 (RGBA) value to multiply by
  395. * @param result The Color4 (RGBA) to fill the result in
  396. * @returns the result Color4.
  397. */
  398. Color4.prototype.multiplyToRef = function (color, result) {
  399. result.r = this.r * color.r;
  400. result.g = this.g * color.g;
  401. result.b = this.b * color.b;
  402. result.a = this.a * color.a;
  403. return result;
  404. };
  405. /**
  406. * Returns a string with the Color4 values.
  407. */
  408. Color4.prototype.toString = function () {
  409. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  410. };
  411. /**
  412. * Returns the string "Color4"
  413. */
  414. Color4.prototype.getClassName = function () {
  415. return "Color4";
  416. };
  417. /**
  418. * Return the Color4 hash code as a number.
  419. */
  420. Color4.prototype.getHashCode = function () {
  421. var hash = this.r || 0;
  422. hash = (hash * 397) ^ (this.g || 0);
  423. hash = (hash * 397) ^ (this.b || 0);
  424. hash = (hash * 397) ^ (this.a || 0);
  425. return hash;
  426. };
  427. /**
  428. * Creates a new Color4 copied from the current one.
  429. */
  430. Color4.prototype.clone = function () {
  431. return new Color4(this.r, this.g, this.b, this.a);
  432. };
  433. /**
  434. * Copies the passed Color4 values into the current one.
  435. * Returns the updated Color4.
  436. */
  437. Color4.prototype.copyFrom = function (source) {
  438. this.r = source.r;
  439. this.g = source.g;
  440. this.b = source.b;
  441. this.a = source.a;
  442. return this;
  443. };
  444. /**
  445. * Copies the passed float values into the current one.
  446. * Returns the updated Color4.
  447. */
  448. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  449. this.r = r;
  450. this.g = g;
  451. this.b = b;
  452. this.a = a;
  453. return this;
  454. };
  455. /**
  456. * Copies the passed float values into the current one.
  457. * Returns the updated Color4.
  458. */
  459. Color4.prototype.set = function (r, g, b, a) {
  460. return this.copyFromFloats(r, g, b, a);
  461. };
  462. /**
  463. * Returns a string containing the hexadecimal Color4 code.
  464. */
  465. Color4.prototype.toHexString = function () {
  466. var intR = (this.r * 255) | 0;
  467. var intG = (this.g * 255) | 0;
  468. var intB = (this.b * 255) | 0;
  469. var intA = (this.a * 255) | 0;
  470. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  471. };
  472. /**
  473. * Returns a new Color4 converted to linear space.
  474. */
  475. Color4.prototype.toLinearSpace = function () {
  476. var convertedColor = new Color4();
  477. this.toLinearSpaceToRef(convertedColor);
  478. return convertedColor;
  479. };
  480. /**
  481. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  482. * Returns the unmodified Color4.
  483. */
  484. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  485. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  486. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  487. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  488. convertedColor.a = this.a;
  489. return this;
  490. };
  491. /**
  492. * Returns a new Color4 converted to gamma space.
  493. */
  494. Color4.prototype.toGammaSpace = function () {
  495. var convertedColor = new Color4();
  496. this.toGammaSpaceToRef(convertedColor);
  497. return convertedColor;
  498. };
  499. /**
  500. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  501. * Returns the unmodified Color4.
  502. */
  503. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  504. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  505. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  506. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  507. convertedColor.a = this.a;
  508. return this;
  509. };
  510. // Statics
  511. /**
  512. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  513. */
  514. Color4.FromHexString = function (hex) {
  515. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  516. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  517. return new Color4(0.0, 0.0, 0.0, 0.0);
  518. }
  519. var r = parseInt(hex.substring(1, 3), 16);
  520. var g = parseInt(hex.substring(3, 5), 16);
  521. var b = parseInt(hex.substring(5, 7), 16);
  522. var a = parseInt(hex.substring(7, 9), 16);
  523. return Color4.FromInts(r, g, b, a);
  524. };
  525. /**
  526. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  527. */
  528. Color4.Lerp = function (left, right, amount) {
  529. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  530. Color4.LerpToRef(left, right, amount, result);
  531. return result;
  532. };
  533. /**
  534. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  535. */
  536. Color4.LerpToRef = function (left, right, amount, result) {
  537. result.r = left.r + (right.r - left.r) * amount;
  538. result.g = left.g + (right.g - left.g) * amount;
  539. result.b = left.b + (right.b - left.b) * amount;
  540. result.a = left.a + (right.a - left.a) * amount;
  541. };
  542. /**
  543. * Creates a new Color4 from the starting index element of the passed array.
  544. */
  545. Color4.FromArray = function (array, offset) {
  546. if (offset === void 0) { offset = 0; }
  547. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  548. };
  549. /**
  550. * Creates a new Color4 from the passed integers ( < 256 ).
  551. */
  552. Color4.FromInts = function (r, g, b, a) {
  553. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  554. };
  555. Color4.CheckColors4 = function (colors, count) {
  556. // Check if color3 was used
  557. if (colors.length === count * 3) {
  558. var colors4 = [];
  559. for (var index = 0; index < colors.length; index += 3) {
  560. var newIndex = (index / 3) * 4;
  561. colors4[newIndex] = colors[index];
  562. colors4[newIndex + 1] = colors[index + 1];
  563. colors4[newIndex + 2] = colors[index + 2];
  564. colors4[newIndex + 3] = 1.0;
  565. }
  566. return colors4;
  567. }
  568. return colors;
  569. };
  570. return Color4;
  571. }());
  572. BABYLON.Color4 = Color4;
  573. var Vector2 = (function () {
  574. /**
  575. * Creates a new Vector2 from the passed x and y coordinates.
  576. */
  577. function Vector2(x, y) {
  578. this.x = x;
  579. this.y = y;
  580. }
  581. /**
  582. * Returns a string with the Vector2 coordinates.
  583. */
  584. Vector2.prototype.toString = function () {
  585. return "{X: " + this.x + " Y:" + this.y + "}";
  586. };
  587. /**
  588. * Returns the string "Vector2"
  589. */
  590. Vector2.prototype.getClassName = function () {
  591. return "Vector2";
  592. };
  593. /**
  594. * Returns the Vector2 hash code as a number.
  595. */
  596. Vector2.prototype.getHashCode = function () {
  597. var hash = this.x || 0;
  598. hash = (hash * 397) ^ (this.y || 0);
  599. return hash;
  600. };
  601. // Operators
  602. /**
  603. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  604. * Returns the Vector2.
  605. */
  606. Vector2.prototype.toArray = function (array, index) {
  607. if (index === void 0) { index = 0; }
  608. array[index] = this.x;
  609. array[index + 1] = this.y;
  610. return this;
  611. };
  612. /**
  613. * Returns a new array with 2 elements : the Vector2 coordinates.
  614. */
  615. Vector2.prototype.asArray = function () {
  616. var result = [];
  617. this.toArray(result, 0);
  618. return result;
  619. };
  620. /**
  621. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  622. * Returns the updated Vector2.
  623. */
  624. Vector2.prototype.copyFrom = function (source) {
  625. this.x = source.x;
  626. this.y = source.y;
  627. return this;
  628. };
  629. /**
  630. * Sets the Vector2 coordinates with the passed floats.
  631. * Returns the updated Vector2.
  632. */
  633. Vector2.prototype.copyFromFloats = function (x, y) {
  634. this.x = x;
  635. this.y = y;
  636. return this;
  637. };
  638. /**
  639. * Sets the Vector2 coordinates with the passed floats.
  640. * Returns the updated Vector2.
  641. */
  642. Vector2.prototype.set = function (x, y) {
  643. return this.copyFromFloats(x, y);
  644. };
  645. /**
  646. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  647. */
  648. Vector2.prototype.add = function (otherVector) {
  649. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  650. };
  651. /**
  652. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  653. * Returns the Vector2.
  654. */
  655. Vector2.prototype.addToRef = function (otherVector, result) {
  656. result.x = this.x + otherVector.x;
  657. result.y = this.y + otherVector.y;
  658. return this;
  659. };
  660. /**
  661. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.addInPlace = function (otherVector) {
  665. this.x += otherVector.x;
  666. this.y += otherVector.y;
  667. return this;
  668. };
  669. /**
  670. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  671. */
  672. Vector2.prototype.addVector3 = function (otherVector) {
  673. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  674. };
  675. /**
  676. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  677. */
  678. Vector2.prototype.subtract = function (otherVector) {
  679. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  680. };
  681. /**
  682. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  683. * Returns the Vector2.
  684. */
  685. Vector2.prototype.subtractToRef = function (otherVector, result) {
  686. result.x = this.x - otherVector.x;
  687. result.y = this.y - otherVector.y;
  688. return this;
  689. };
  690. /**
  691. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  692. * Returns the updated Vector2.
  693. */
  694. Vector2.prototype.subtractInPlace = function (otherVector) {
  695. this.x -= otherVector.x;
  696. this.y -= otherVector.y;
  697. return this;
  698. };
  699. /**
  700. * Multiplies in place the current Vector2 coordinates by the passed ones.
  701. * Returns the updated Vector2.
  702. */
  703. Vector2.prototype.multiplyInPlace = function (otherVector) {
  704. this.x *= otherVector.x;
  705. this.y *= otherVector.y;
  706. return this;
  707. };
  708. /**
  709. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  710. */
  711. Vector2.prototype.multiply = function (otherVector) {
  712. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  713. };
  714. /**
  715. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  716. * Returns the Vector2.
  717. */
  718. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  719. result.x = this.x * otherVector.x;
  720. result.y = this.y * otherVector.y;
  721. return this;
  722. };
  723. /**
  724. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  725. */
  726. Vector2.prototype.multiplyByFloats = function (x, y) {
  727. return new Vector2(this.x * x, this.y * y);
  728. };
  729. /**
  730. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  731. */
  732. Vector2.prototype.divide = function (otherVector) {
  733. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  734. };
  735. /**
  736. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  737. * Returns the Vector2.
  738. */
  739. Vector2.prototype.divideToRef = function (otherVector, result) {
  740. result.x = this.x / otherVector.x;
  741. result.y = this.y / otherVector.y;
  742. return this;
  743. };
  744. /**
  745. * Returns a new Vector2 with current Vector2 negated coordinates.
  746. */
  747. Vector2.prototype.negate = function () {
  748. return new Vector2(-this.x, -this.y);
  749. };
  750. /**
  751. * Multiply the Vector2 coordinates by scale.
  752. * Returns the updated Vector2.
  753. */
  754. Vector2.prototype.scaleInPlace = function (scale) {
  755. this.x *= scale;
  756. this.y *= scale;
  757. return this;
  758. };
  759. /**
  760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  761. */
  762. Vector2.prototype.scale = function (scale) {
  763. return new Vector2(this.x * scale, this.y * scale);
  764. };
  765. /**
  766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  767. */
  768. Vector2.prototype.equals = function (otherVector) {
  769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  770. };
  771. /**
  772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  773. */
  774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  777. };
  778. // Properties
  779. /**
  780. * Returns the vector length (float).
  781. */
  782. Vector2.prototype.length = function () {
  783. return Math.sqrt(this.x * this.x + this.y * this.y);
  784. };
  785. /**
  786. * Returns the vector squared length (float);
  787. */
  788. Vector2.prototype.lengthSquared = function () {
  789. return (this.x * this.x + this.y * this.y);
  790. };
  791. // Methods
  792. /**
  793. * Normalize the vector.
  794. * Returns the updated Vector2.
  795. */
  796. Vector2.prototype.normalize = function () {
  797. var len = this.length();
  798. if (len === 0)
  799. return this;
  800. var num = 1.0 / len;
  801. this.x *= num;
  802. this.y *= num;
  803. return this;
  804. };
  805. /**
  806. * Returns a new Vector2 copied from the Vector2.
  807. */
  808. Vector2.prototype.clone = function () {
  809. return new Vector2(this.x, this.y);
  810. };
  811. // Statics
  812. /**
  813. * Returns a new Vector2(0, 0)
  814. */
  815. Vector2.Zero = function () {
  816. return new Vector2(0, 0);
  817. };
  818. /**
  819. * Returns a new Vector2(1, 1)
  820. */
  821. Vector2.One = function () {
  822. return new Vector2(1, 1);
  823. };
  824. /**
  825. * Returns a new Vector2 set from the passed index element of the passed array.
  826. */
  827. Vector2.FromArray = function (array, offset) {
  828. if (offset === void 0) { offset = 0; }
  829. return new Vector2(array[offset], array[offset + 1]);
  830. };
  831. /**
  832. * Sets "result" from the passed index element of the passed array.
  833. */
  834. Vector2.FromArrayToRef = function (array, offset, result) {
  835. result.x = array[offset];
  836. result.y = array[offset + 1];
  837. };
  838. /**
  839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  840. */
  841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  842. var squared = amount * amount;
  843. var cubed = amount * squared;
  844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  850. return new Vector2(x, y);
  851. };
  852. /**
  853. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  856. */
  857. Vector2.Clamp = function (value, min, max) {
  858. var x = value.x;
  859. x = (x > max.x) ? max.x : x;
  860. x = (x < min.x) ? min.x : x;
  861. var y = value.y;
  862. y = (y > max.y) ? max.y : y;
  863. y = (y < min.y) ? min.y : y;
  864. return new Vector2(x, y);
  865. };
  866. /**
  867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  868. */
  869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  870. var squared = amount * amount;
  871. var cubed = amount * squared;
  872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  874. var part3 = (cubed - (2.0 * squared)) + amount;
  875. var part4 = cubed - squared;
  876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  882. */
  883. Vector2.Lerp = function (start, end, amount) {
  884. var x = start.x + ((end.x - start.x) * amount);
  885. var y = start.y + ((end.y - start.y) * amount);
  886. return new Vector2(x, y);
  887. };
  888. /**
  889. * Returns the dot product (float) of the vector "left" and the vector "right".
  890. */
  891. Vector2.Dot = function (left, right) {
  892. return left.x * right.x + left.y * right.y;
  893. };
  894. /**
  895. * Returns a new Vector2 equal to the normalized passed vector.
  896. */
  897. Vector2.Normalize = function (vector) {
  898. var newVector = vector.clone();
  899. newVector.normalize();
  900. return newVector;
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Minimize = function (left, right) {
  906. var x = (left.x < right.x) ? left.x : right.x;
  907. var y = (left.y < right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  912. */
  913. Vector2.Maximize = function (left, right) {
  914. var x = (left.x > right.x) ? left.x : right.x;
  915. var y = (left.y > right.y) ? left.y : right.y;
  916. return new Vector2(x, y);
  917. };
  918. /**
  919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  920. */
  921. Vector2.Transform = function (vector, transformation) {
  922. var r = Vector2.Zero();
  923. Vector2.TransformToRef(vector, transformation, r);
  924. return r;
  925. };
  926. /**
  927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  928. */
  929. Vector2.TransformToRef = function (vector, transformation, result) {
  930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  932. result.x = x;
  933. result.y = y;
  934. };
  935. /**
  936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  937. */
  938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  940. var sign = a < 0 ? -1 : 1;
  941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  944. };
  945. /**
  946. * Returns the distance (float) between the vectors "value1" and "value2".
  947. */
  948. Vector2.Distance = function (value1, value2) {
  949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  950. };
  951. /**
  952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  953. */
  954. Vector2.DistanceSquared = function (value1, value2) {
  955. var x = value1.x - value2.x;
  956. var y = value1.y - value2.y;
  957. return (x * x) + (y * y);
  958. };
  959. /**
  960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  961. */
  962. Vector2.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. /**
  968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  969. */
  970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  971. var l2 = Vector2.DistanceSquared(segA, segB);
  972. if (l2 === 0.0) {
  973. return Vector2.Distance(p, segA);
  974. }
  975. var v = segB.subtract(segA);
  976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  977. var proj = segA.add(v.multiplyByFloats(t, t));
  978. return Vector2.Distance(p, proj);
  979. };
  980. return Vector2;
  981. }());
  982. BABYLON.Vector2 = Vector2;
  983. var Vector3 = (function () {
  984. /**
  985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  986. * A Vector3 is the main object used in 3D geometry.
  987. * It can represent etiher the coordinates of a point the space, either a direction.
  988. */
  989. function Vector3(x, y, z) {
  990. this.x = x;
  991. this.y = y;
  992. this.z = z;
  993. }
  994. /**
  995. * Returns a string with the Vector3 coordinates.
  996. */
  997. Vector3.prototype.toString = function () {
  998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  999. };
  1000. /**
  1001. * Returns the string "Vector3"
  1002. */
  1003. Vector3.prototype.getClassName = function () {
  1004. return "Vector3";
  1005. };
  1006. /**
  1007. * Returns the Vector hash code.
  1008. */
  1009. Vector3.prototype.getHashCode = function () {
  1010. var hash = this.x || 0;
  1011. hash = (hash * 397) ^ (this.y || 0);
  1012. hash = (hash * 397) ^ (this.z || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Returns a new array with three elements : the coordinates the Vector3.
  1018. */
  1019. Vector3.prototype.asArray = function () {
  1020. var result = [];
  1021. this.toArray(result, 0);
  1022. return result;
  1023. };
  1024. /**
  1025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1026. * Returns the Vector3.
  1027. */
  1028. Vector3.prototype.toArray = function (array, index) {
  1029. if (index === void 0) { index = 0; }
  1030. array[index] = this.x;
  1031. array[index + 1] = this.y;
  1032. array[index + 2] = this.z;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1037. */
  1038. Vector3.prototype.toQuaternion = function () {
  1039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1044. var cosy = Math.cos(this.y * 0.5);
  1045. var siny = Math.sin(this.y * 0.5);
  1046. result.x = coszMinusx * siny;
  1047. result.y = -sinzMinusx * siny;
  1048. result.z = sinxPlusz * cosy;
  1049. result.w = cosxPlusz * cosy;
  1050. return result;
  1051. };
  1052. /**
  1053. * Adds the passed vector to the current Vector3.
  1054. * Returns the updated Vector3.
  1055. */
  1056. Vector3.prototype.addInPlace = function (otherVector) {
  1057. this.x += otherVector.x;
  1058. this.y += otherVector.y;
  1059. this.z += otherVector.z;
  1060. return this;
  1061. };
  1062. /**
  1063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1064. */
  1065. Vector3.prototype.add = function (otherVector) {
  1066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1067. };
  1068. /**
  1069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1070. * Returns the current Vector3.
  1071. */
  1072. Vector3.prototype.addToRef = function (otherVector, result) {
  1073. result.x = this.x + otherVector.x;
  1074. result.y = this.y + otherVector.y;
  1075. result.z = this.z + otherVector.z;
  1076. return this;
  1077. };
  1078. /**
  1079. * Subtract the passed vector from the current Vector3.
  1080. * Returns the updated Vector3.
  1081. */
  1082. Vector3.prototype.subtractInPlace = function (otherVector) {
  1083. this.x -= otherVector.x;
  1084. this.y -= otherVector.y;
  1085. this.z -= otherVector.z;
  1086. return this;
  1087. };
  1088. /**
  1089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1090. */
  1091. Vector3.prototype.subtract = function (otherVector) {
  1092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1093. };
  1094. /**
  1095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1096. * Returns the current Vector3.
  1097. */
  1098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1099. result.x = this.x - otherVector.x;
  1100. result.y = this.y - otherVector.y;
  1101. result.z = this.z - otherVector.z;
  1102. return this;
  1103. };
  1104. /**
  1105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1106. */
  1107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1108. return new Vector3(this.x - x, this.y - y, this.z - z);
  1109. };
  1110. /**
  1111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1112. * Returns the current Vector3.
  1113. */
  1114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1115. result.x = this.x - x;
  1116. result.y = this.y - y;
  1117. result.z = this.z - z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1122. */
  1123. Vector3.prototype.negate = function () {
  1124. return new Vector3(-this.x, -this.y, -this.z);
  1125. };
  1126. /**
  1127. * Multiplies the Vector3 coordinates by the float "scale".
  1128. * Returns the updated Vector3.
  1129. */
  1130. Vector3.prototype.scaleInPlace = function (scale) {
  1131. this.x *= scale;
  1132. this.y *= scale;
  1133. this.z *= scale;
  1134. return this;
  1135. };
  1136. /**
  1137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1138. */
  1139. Vector3.prototype.scale = function (scale) {
  1140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1141. };
  1142. /**
  1143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1144. * Returns the current Vector3.
  1145. */
  1146. Vector3.prototype.scaleToRef = function (scale, result) {
  1147. result.x = this.x * scale;
  1148. result.y = this.y * scale;
  1149. result.z = this.z * scale;
  1150. return this;
  1151. };
  1152. /**
  1153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1154. */
  1155. Vector3.prototype.equals = function (otherVector) {
  1156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1157. };
  1158. /**
  1159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1160. */
  1161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1163. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1164. };
  1165. /**
  1166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1167. */
  1168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1169. return this.x === x && this.y === y && this.z === z;
  1170. };
  1171. /**
  1172. * Muliplies the current Vector3 coordinates by the passed ones.
  1173. * Returns the updated Vector3.
  1174. */
  1175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1176. this.x *= otherVector.x;
  1177. this.y *= otherVector.y;
  1178. this.z *= otherVector.z;
  1179. return this;
  1180. };
  1181. /**
  1182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1183. */
  1184. Vector3.prototype.multiply = function (otherVector) {
  1185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1186. };
  1187. /**
  1188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1189. * Returns the current Vector3.
  1190. */
  1191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1192. result.x = this.x * otherVector.x;
  1193. result.y = this.y * otherVector.y;
  1194. result.z = this.z * otherVector.z;
  1195. return this;
  1196. };
  1197. /**
  1198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1199. */
  1200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1201. return new Vector3(this.x * x, this.y * y, this.z * z);
  1202. };
  1203. /**
  1204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1205. */
  1206. Vector3.prototype.divide = function (otherVector) {
  1207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1208. };
  1209. /**
  1210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1211. * Returns the current Vector3.
  1212. */
  1213. Vector3.prototype.divideToRef = function (otherVector, result) {
  1214. result.x = this.x / otherVector.x;
  1215. result.y = this.y / otherVector.y;
  1216. result.z = this.z / otherVector.z;
  1217. return this;
  1218. };
  1219. /**
  1220. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.MinimizeInPlace = function (other) {
  1224. if (other.x < this.x)
  1225. this.x = other.x;
  1226. if (other.y < this.y)
  1227. this.y = other.y;
  1228. if (other.z < this.z)
  1229. this.z = other.z;
  1230. return this;
  1231. };
  1232. /**
  1233. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1234. * Returns the updated Vector3.
  1235. */
  1236. Vector3.prototype.MaximizeInPlace = function (other) {
  1237. if (other.x > this.x)
  1238. this.x = other.x;
  1239. if (other.y > this.y)
  1240. this.y = other.y;
  1241. if (other.z > this.z)
  1242. this.z = other.z;
  1243. return this;
  1244. };
  1245. // Properties
  1246. /**
  1247. * Returns the length of the Vector3 (float).
  1248. */
  1249. Vector3.prototype.length = function () {
  1250. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1251. };
  1252. /**
  1253. * Returns the squared length of the Vector3 (float).
  1254. */
  1255. Vector3.prototype.lengthSquared = function () {
  1256. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1257. };
  1258. // Methods
  1259. /**
  1260. * Normalize the current Vector3.
  1261. * Returns the updated Vector3.
  1262. */
  1263. Vector3.prototype.normalize = function () {
  1264. var len = this.length();
  1265. if (len === 0 || len === 1.0)
  1266. return this;
  1267. var num = 1.0 / len;
  1268. this.x *= num;
  1269. this.y *= num;
  1270. this.z *= num;
  1271. return this;
  1272. };
  1273. /**
  1274. * Returns a new Vector3 copied from the current Vector3.
  1275. */
  1276. Vector3.prototype.clone = function () {
  1277. return new Vector3(this.x, this.y, this.z);
  1278. };
  1279. /**
  1280. * Copies the passed vector coordinates to the current Vector3 ones.
  1281. * Returns the updated Vector3.
  1282. */
  1283. Vector3.prototype.copyFrom = function (source) {
  1284. this.x = source.x;
  1285. this.y = source.y;
  1286. this.z = source.z;
  1287. return this;
  1288. };
  1289. /**
  1290. * Copies the passed floats to the current Vector3 coordinates.
  1291. * Returns the updated Vector3.
  1292. */
  1293. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. return this;
  1298. };
  1299. /**
  1300. * Copies the passed floats to the current Vector3 coordinates.
  1301. * Returns the updated Vector3.
  1302. */
  1303. Vector3.prototype.set = function (x, y, z) {
  1304. return this.copyFromFloats(x, y, z);
  1305. };
  1306. // Statics
  1307. /**
  1308. *
  1309. */
  1310. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1311. var d0 = Vector3.Dot(vector0, axis) - size;
  1312. var d1 = Vector3.Dot(vector1, axis) - size;
  1313. var s = d0 / (d0 - d1);
  1314. return s;
  1315. };
  1316. /**
  1317. * Returns a new Vector3 set from the index "offset" of the passed array.
  1318. */
  1319. Vector3.FromArray = function (array, offset) {
  1320. if (!offset) {
  1321. offset = 0;
  1322. }
  1323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1324. };
  1325. /**
  1326. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1327. * This function is deprecated. Use FromArray instead.
  1328. */
  1329. Vector3.FromFloatArray = function (array, offset) {
  1330. return Vector3.FromArray(array, offset);
  1331. };
  1332. /**
  1333. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1334. */
  1335. Vector3.FromArrayToRef = function (array, offset, result) {
  1336. result.x = array[offset];
  1337. result.y = array[offset + 1];
  1338. result.z = array[offset + 2];
  1339. };
  1340. /**
  1341. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1342. * This function is deprecated. Use FromArrayToRef instead.
  1343. */
  1344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1345. return Vector3.FromArrayToRef(array, offset, result);
  1346. };
  1347. /**
  1348. * Sets the passed vector "result" with the passed floats.
  1349. */
  1350. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1351. result.x = x;
  1352. result.y = y;
  1353. result.z = z;
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1357. */
  1358. Vector3.Zero = function () {
  1359. return new Vector3(0.0, 0.0, 0.0);
  1360. };
  1361. /**
  1362. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1363. */
  1364. Vector3.One = function () {
  1365. return new Vector3(1.0, 1.0, 1.0);
  1366. };
  1367. /**
  1368. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1369. */
  1370. Vector3.Up = function () {
  1371. return new Vector3(0.0, 1.0, 0.0);
  1372. };
  1373. /**
  1374. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1375. */
  1376. Vector3.Forward = function () {
  1377. return new Vector3(0.0, 0.0, 1.0);
  1378. };
  1379. /**
  1380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1381. */
  1382. Vector3.Right = function () {
  1383. return new Vector3(1.0, 0.0, 0.0);
  1384. };
  1385. /**
  1386. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1387. */
  1388. Vector3.Left = function () {
  1389. return new Vector3(-1.0, 0.0, 0.0);
  1390. };
  1391. /**
  1392. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1393. * This method computes tranformed coordinates only, not transformed direction vectors.
  1394. */
  1395. Vector3.TransformCoordinates = function (vector, transformation) {
  1396. var result = Vector3.Zero();
  1397. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1398. return result;
  1399. };
  1400. /**
  1401. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1402. * This method computes tranformed coordinates only, not transformed direction vectors.
  1403. */
  1404. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1408. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1409. result.x = x / w;
  1410. result.y = y / w;
  1411. result.z = z / w;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1418. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1419. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1420. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1421. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1422. result.x = rx / rw;
  1423. result.y = ry / rw;
  1424. result.z = rz / rw;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1428. * This methods computes transformed normalized direction vectors only.
  1429. */
  1430. Vector3.TransformNormal = function (vector, transformation) {
  1431. var result = Vector3.Zero();
  1432. Vector3.TransformNormalToRef(vector, transformation, result);
  1433. return result;
  1434. };
  1435. /**
  1436. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1437. * This methods computes transformed normalized direction vectors only.
  1438. */
  1439. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1443. result.x = x;
  1444. result.y = y;
  1445. result.z = z;
  1446. };
  1447. /**
  1448. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1449. * This methods computes transformed normalized direction vectors only.
  1450. */
  1451. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1452. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1453. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1454. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1455. };
  1456. /**
  1457. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1458. */
  1459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1460. var squared = amount * amount;
  1461. var cubed = amount * squared;
  1462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1471. return new Vector3(x, y, z);
  1472. };
  1473. /**
  1474. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1477. */
  1478. Vector3.Clamp = function (value, min, max) {
  1479. var x = value.x;
  1480. x = (x > max.x) ? max.x : x;
  1481. x = (x < min.x) ? min.x : x;
  1482. var y = value.y;
  1483. y = (y > max.y) ? max.y : y;
  1484. y = (y < min.y) ? min.y : y;
  1485. var z = value.z;
  1486. z = (z > max.z) ? max.z : z;
  1487. z = (z < min.z) ? min.z : z;
  1488. return new Vector3(x, y, z);
  1489. };
  1490. /**
  1491. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1492. */
  1493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1494. var squared = amount * amount;
  1495. var cubed = amount * squared;
  1496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1498. var part3 = (cubed - (2.0 * squared)) + amount;
  1499. var part4 = cubed - squared;
  1500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1503. return new Vector3(x, y, z);
  1504. };
  1505. /**
  1506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1507. */
  1508. Vector3.Lerp = function (start, end, amount) {
  1509. var result = new Vector3(0, 0, 0);
  1510. Vector3.LerpToRef(start, end, amount, result);
  1511. return result;
  1512. };
  1513. /**
  1514. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1515. */
  1516. Vector3.LerpToRef = function (start, end, amount, result) {
  1517. result.x = start.x + ((end.x - start.x) * amount);
  1518. result.y = start.y + ((end.y - start.y) * amount);
  1519. result.z = start.z + ((end.z - start.z) * amount);
  1520. };
  1521. /**
  1522. * Returns the dot product (float) between the vectors "left" and "right".
  1523. */
  1524. Vector3.Dot = function (left, right) {
  1525. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1526. };
  1527. /**
  1528. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1529. * The cross product is then orthogonal to both "left" and "right".
  1530. */
  1531. Vector3.Cross = function (left, right) {
  1532. var result = Vector3.Zero();
  1533. Vector3.CrossToRef(left, right, result);
  1534. return result;
  1535. };
  1536. /**
  1537. * Sets the passed vector "result" with the cross product of "left" and "right".
  1538. * The cross product is then orthogonal to both "left" and "right".
  1539. */
  1540. Vector3.CrossToRef = function (left, right, result) {
  1541. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1542. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1543. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1544. result.copyFrom(MathTmp.Vector3[0]);
  1545. };
  1546. /**
  1547. * Returns a new Vector3 as the normalization of the passed vector.
  1548. */
  1549. Vector3.Normalize = function (vector) {
  1550. var result = Vector3.Zero();
  1551. Vector3.NormalizeToRef(vector, result);
  1552. return result;
  1553. };
  1554. /**
  1555. * Sets the passed vector "result" with the normalization of the passed first vector.
  1556. */
  1557. Vector3.NormalizeToRef = function (vector, result) {
  1558. result.copyFrom(vector);
  1559. result.normalize();
  1560. };
  1561. Vector3.Project = function (vector, world, transform, viewport) {
  1562. var cw = viewport.width;
  1563. var ch = viewport.height;
  1564. var cx = viewport.x;
  1565. var cy = viewport.y;
  1566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1567. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1568. var matrix = MathTmp.Matrix[0];
  1569. world.multiplyToRef(transform, matrix);
  1570. matrix.multiplyToRef(viewportMatrix, matrix);
  1571. return Vector3.TransformCoordinates(vector, matrix);
  1572. };
  1573. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1574. var matrix = MathTmp.Matrix[0];
  1575. world.multiplyToRef(transform, matrix);
  1576. matrix.invert();
  1577. source.x = source.x / viewportWidth * 2 - 1;
  1578. source.y = -(source.y / viewportHeight * 2 - 1);
  1579. var vector = Vector3.TransformCoordinates(source, matrix);
  1580. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1581. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1582. vector = vector.scale(1.0 / num);
  1583. }
  1584. return vector;
  1585. };
  1586. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1587. var matrix = MathTmp.Matrix[0];
  1588. world.multiplyToRef(view, matrix);
  1589. matrix.multiplyToRef(projection, matrix);
  1590. matrix.invert();
  1591. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1592. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1593. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1594. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Minimize = function (left, right) {
  1600. var min = left.clone();
  1601. min.MinimizeInPlace(right);
  1602. return min;
  1603. };
  1604. Vector3.Maximize = function (left, right) {
  1605. var max = left.clone();
  1606. max.MaximizeInPlace(right);
  1607. return max;
  1608. };
  1609. /**
  1610. * Returns the distance (float) between the vectors "value1" and "value2".
  1611. */
  1612. Vector3.Distance = function (value1, value2) {
  1613. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1614. };
  1615. /**
  1616. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1617. */
  1618. Vector3.DistanceSquared = function (value1, value2) {
  1619. var x = value1.x - value2.x;
  1620. var y = value1.y - value2.y;
  1621. var z = value1.z - value2.z;
  1622. return (x * x) + (y * y) + (z * z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 located at the center between "value1" and "value2".
  1626. */
  1627. Vector3.Center = function (value1, value2) {
  1628. var center = value1.add(value2);
  1629. center.scaleInPlace(0.5);
  1630. return center;
  1631. };
  1632. /**
  1633. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1634. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1635. * to something in order to rotate it from its local system to the given target system.
  1636. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1637. * Returns a new Vector3.
  1638. */
  1639. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1640. var rotation = Vector3.Zero();
  1641. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1642. return rotation;
  1643. };
  1644. /**
  1645. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1646. */
  1647. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1648. var quat = MathTmp.Quaternion[0];
  1649. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1650. quat.toEulerAnglesToRef(ref);
  1651. };
  1652. return Vector3;
  1653. }());
  1654. BABYLON.Vector3 = Vector3;
  1655. //Vector4 class created for EulerAngle class conversion to Quaternion
  1656. var Vector4 = (function () {
  1657. /**
  1658. * Creates a Vector4 object from the passed floats.
  1659. */
  1660. function Vector4(x, y, z, w) {
  1661. this.x = x;
  1662. this.y = y;
  1663. this.z = z;
  1664. this.w = w;
  1665. }
  1666. /**
  1667. * Returns the string with the Vector4 coordinates.
  1668. */
  1669. Vector4.prototype.toString = function () {
  1670. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1671. };
  1672. /**
  1673. * Returns the string "Vector4".
  1674. */
  1675. Vector4.prototype.getClassName = function () {
  1676. return "Vector4";
  1677. };
  1678. /**
  1679. * Returns the Vector4 hash code.
  1680. */
  1681. Vector4.prototype.getHashCode = function () {
  1682. var hash = this.x || 0;
  1683. hash = (hash * 397) ^ (this.y || 0);
  1684. hash = (hash * 397) ^ (this.z || 0);
  1685. hash = (hash * 397) ^ (this.w || 0);
  1686. return hash;
  1687. };
  1688. // Operators
  1689. /**
  1690. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1691. */
  1692. Vector4.prototype.asArray = function () {
  1693. var result = [];
  1694. this.toArray(result, 0);
  1695. return result;
  1696. };
  1697. /**
  1698. * Populates the passed array from the passed index with the Vector4 coordinates.
  1699. * Returns the Vector4.
  1700. */
  1701. Vector4.prototype.toArray = function (array, index) {
  1702. if (index === undefined) {
  1703. index = 0;
  1704. }
  1705. array[index] = this.x;
  1706. array[index + 1] = this.y;
  1707. array[index + 2] = this.z;
  1708. array[index + 3] = this.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Adds the passed vector to the current Vector4.
  1713. * Returns the updated Vector4.
  1714. */
  1715. Vector4.prototype.addInPlace = function (otherVector) {
  1716. this.x += otherVector.x;
  1717. this.y += otherVector.y;
  1718. this.z += otherVector.z;
  1719. this.w += otherVector.w;
  1720. return this;
  1721. };
  1722. /**
  1723. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1724. */
  1725. Vector4.prototype.add = function (otherVector) {
  1726. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1727. };
  1728. /**
  1729. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1730. * Returns the current Vector4.
  1731. */
  1732. Vector4.prototype.addToRef = function (otherVector, result) {
  1733. result.x = this.x + otherVector.x;
  1734. result.y = this.y + otherVector.y;
  1735. result.z = this.z + otherVector.z;
  1736. result.w = this.w + otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Subtract in place the passed vector from the current Vector4.
  1741. * Returns the updated Vector4.
  1742. */
  1743. Vector4.prototype.subtractInPlace = function (otherVector) {
  1744. this.x -= otherVector.x;
  1745. this.y -= otherVector.y;
  1746. this.z -= otherVector.z;
  1747. this.w -= otherVector.w;
  1748. return this;
  1749. };
  1750. /**
  1751. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1752. */
  1753. Vector4.prototype.subtract = function (otherVector) {
  1754. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1755. };
  1756. /**
  1757. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1758. * Returns the current Vector4.
  1759. */
  1760. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1761. result.x = this.x - otherVector.x;
  1762. result.y = this.y - otherVector.y;
  1763. result.z = this.z - otherVector.z;
  1764. result.w = this.w - otherVector.w;
  1765. return this;
  1766. };
  1767. /**
  1768. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1769. */
  1770. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1771. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1772. };
  1773. /**
  1774. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1775. * Returns the current Vector4.
  1776. */
  1777. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1778. result.x = this.x - x;
  1779. result.y = this.y - y;
  1780. result.z = this.z - z;
  1781. result.w = this.w - w;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1786. */
  1787. Vector4.prototype.negate = function () {
  1788. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1789. };
  1790. /**
  1791. * Multiplies the current Vector4 coordinates by scale (float).
  1792. * Returns the updated Vector4.
  1793. */
  1794. Vector4.prototype.scaleInPlace = function (scale) {
  1795. this.x *= scale;
  1796. this.y *= scale;
  1797. this.z *= scale;
  1798. this.w *= scale;
  1799. return this;
  1800. };
  1801. /**
  1802. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1803. */
  1804. Vector4.prototype.scale = function (scale) {
  1805. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1806. };
  1807. /**
  1808. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1809. * Returns the current Vector4.
  1810. */
  1811. Vector4.prototype.scaleToRef = function (scale, result) {
  1812. result.x = this.x * scale;
  1813. result.y = this.y * scale;
  1814. result.z = this.z * scale;
  1815. result.w = this.w * scale;
  1816. return this;
  1817. };
  1818. /**
  1819. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1820. */
  1821. Vector4.prototype.equals = function (otherVector) {
  1822. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1823. };
  1824. /**
  1825. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1826. */
  1827. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1828. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1829. return otherVector
  1830. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1831. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1832. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1833. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1834. };
  1835. /**
  1836. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1837. */
  1838. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1839. return this.x === x && this.y === y && this.z === z && this.w === w;
  1840. };
  1841. /**
  1842. * Multiplies in place the current Vector4 by the passed one.
  1843. * Returns the updated Vector4.
  1844. */
  1845. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1846. this.x *= otherVector.x;
  1847. this.y *= otherVector.y;
  1848. this.z *= otherVector.z;
  1849. this.w *= otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1854. */
  1855. Vector4.prototype.multiply = function (otherVector) {
  1856. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1857. };
  1858. /**
  1859. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1863. result.x = this.x * otherVector.x;
  1864. result.y = this.y * otherVector.y;
  1865. result.z = this.z * otherVector.z;
  1866. result.w = this.w * otherVector.w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1871. */
  1872. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1873. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1874. };
  1875. /**
  1876. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1877. */
  1878. Vector4.prototype.divide = function (otherVector) {
  1879. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1880. };
  1881. /**
  1882. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1883. * Returns the current Vector4.
  1884. */
  1885. Vector4.prototype.divideToRef = function (otherVector, result) {
  1886. result.x = this.x / otherVector.x;
  1887. result.y = this.y / otherVector.y;
  1888. result.z = this.z / otherVector.z;
  1889. result.w = this.w / otherVector.w;
  1890. return this;
  1891. };
  1892. /**
  1893. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1894. */
  1895. Vector4.prototype.MinimizeInPlace = function (other) {
  1896. if (other.x < this.x)
  1897. this.x = other.x;
  1898. if (other.y < this.y)
  1899. this.y = other.y;
  1900. if (other.z < this.z)
  1901. this.z = other.z;
  1902. if (other.w < this.w)
  1903. this.w = other.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1908. */
  1909. Vector4.prototype.MaximizeInPlace = function (other) {
  1910. if (other.x > this.x)
  1911. this.x = other.x;
  1912. if (other.y > this.y)
  1913. this.y = other.y;
  1914. if (other.z > this.z)
  1915. this.z = other.z;
  1916. if (other.w > this.w)
  1917. this.w = other.w;
  1918. return this;
  1919. };
  1920. // Properties
  1921. /**
  1922. * Returns the Vector4 length (float).
  1923. */
  1924. Vector4.prototype.length = function () {
  1925. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1926. };
  1927. /**
  1928. * Returns the Vector4 squared length (float).
  1929. */
  1930. Vector4.prototype.lengthSquared = function () {
  1931. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1932. };
  1933. // Methods
  1934. /**
  1935. * Normalizes in place the Vector4.
  1936. * Returns the updated Vector4.
  1937. */
  1938. Vector4.prototype.normalize = function () {
  1939. var len = this.length();
  1940. if (len === 0)
  1941. return this;
  1942. var num = 1.0 / len;
  1943. this.x *= num;
  1944. this.y *= num;
  1945. this.z *= num;
  1946. this.w *= num;
  1947. return this;
  1948. };
  1949. /**
  1950. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1951. */
  1952. Vector4.prototype.toVector3 = function () {
  1953. return new Vector3(this.x, this.y, this.z);
  1954. };
  1955. /**
  1956. * Returns a new Vector4 copied from the current one.
  1957. */
  1958. Vector4.prototype.clone = function () {
  1959. return new Vector4(this.x, this.y, this.z, this.w);
  1960. };
  1961. /**
  1962. * Updates the current Vector4 with the passed one coordinates.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFrom = function (source) {
  1966. this.x = source.x;
  1967. this.y = source.y;
  1968. this.z = source.z;
  1969. this.w = source.w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1977. this.x = x;
  1978. this.y = y;
  1979. this.z = z;
  1980. this.w = w;
  1981. return this;
  1982. };
  1983. /**
  1984. * Updates the current Vector4 coordinates with the passed floats.
  1985. * Returns the updated Vector4.
  1986. */
  1987. Vector4.prototype.set = function (x, y, z, w) {
  1988. return this.copyFromFloats(x, y, z, w);
  1989. };
  1990. // Statics
  1991. /**
  1992. * Returns a new Vector4 set from the starting index of the passed array.
  1993. */
  1994. Vector4.FromArray = function (array, offset) {
  1995. if (!offset) {
  1996. offset = 0;
  1997. }
  1998. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1999. };
  2000. /**
  2001. * Updates the passed vector "result" from the starting index of the passed array.
  2002. */
  2003. Vector4.FromArrayToRef = function (array, offset, result) {
  2004. result.x = array[offset];
  2005. result.y = array[offset + 1];
  2006. result.z = array[offset + 2];
  2007. result.w = array[offset + 3];
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2011. */
  2012. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2013. Vector4.FromArrayToRef(array, offset, result);
  2014. };
  2015. /**
  2016. * Updates the passed vector "result" coordinates from the passed floats.
  2017. */
  2018. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2019. result.x = x;
  2020. result.y = y;
  2021. result.z = z;
  2022. result.w = w;
  2023. };
  2024. /**
  2025. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2026. */
  2027. Vector4.Zero = function () {
  2028. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2032. */
  2033. Vector4.One = function () {
  2034. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2035. };
  2036. /**
  2037. * Returns a new normalized Vector4 from the passed one.
  2038. */
  2039. Vector4.Normalize = function (vector) {
  2040. var result = Vector4.Zero();
  2041. Vector4.NormalizeToRef(vector, result);
  2042. return result;
  2043. };
  2044. /**
  2045. * Updates the passed vector "result" from the normalization of the passed one.
  2046. */
  2047. Vector4.NormalizeToRef = function (vector, result) {
  2048. result.copyFrom(vector);
  2049. result.normalize();
  2050. };
  2051. Vector4.Minimize = function (left, right) {
  2052. var min = left.clone();
  2053. min.MinimizeInPlace(right);
  2054. return min;
  2055. };
  2056. Vector4.Maximize = function (left, right) {
  2057. var max = left.clone();
  2058. max.MaximizeInPlace(right);
  2059. return max;
  2060. };
  2061. /**
  2062. * Returns the distance (float) between the vectors "value1" and "value2".
  2063. */
  2064. Vector4.Distance = function (value1, value2) {
  2065. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2066. };
  2067. /**
  2068. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.DistanceSquared = function (value1, value2) {
  2071. var x = value1.x - value2.x;
  2072. var y = value1.y - value2.y;
  2073. var z = value1.z - value2.z;
  2074. var w = value1.w - value2.w;
  2075. return (x * x) + (y * y) + (z * z) + (w * w);
  2076. };
  2077. /**
  2078. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2079. */
  2080. Vector4.Center = function (value1, value2) {
  2081. var center = value1.add(value2);
  2082. center.scaleInPlace(0.5);
  2083. return center;
  2084. };
  2085. /**
  2086. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2087. * This methods computes transformed normalized direction vectors only.
  2088. */
  2089. Vector4.TransformNormal = function (vector, transformation) {
  2090. var result = Vector4.Zero();
  2091. Vector4.TransformNormalToRef(vector, transformation, result);
  2092. return result;
  2093. };
  2094. /**
  2095. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2096. * This methods computes transformed normalized direction vectors only.
  2097. */
  2098. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2099. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2100. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2101. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2102. result.x = x;
  2103. result.y = y;
  2104. result.z = z;
  2105. result.w = vector.w;
  2106. };
  2107. /**
  2108. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2109. * This methods computes transformed normalized direction vectors only.
  2110. */
  2111. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2112. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2113. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2114. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2115. result.w = w;
  2116. };
  2117. return Vector4;
  2118. }());
  2119. BABYLON.Vector4 = Vector4;
  2120. var Size = (function () {
  2121. /**
  2122. * Creates a Size object from the passed width and height (floats).
  2123. */
  2124. function Size(width, height) {
  2125. this.width = width;
  2126. this.height = height;
  2127. }
  2128. // Returns a string with the Size width and height.
  2129. Size.prototype.toString = function () {
  2130. return "{W: " + this.width + ", H: " + this.height + "}";
  2131. };
  2132. /**
  2133. * Returns the string "Size"
  2134. */
  2135. Size.prototype.getClassName = function () {
  2136. return "Size";
  2137. };
  2138. /**
  2139. * Returns the Size hash code.
  2140. */
  2141. Size.prototype.getHashCode = function () {
  2142. var hash = this.width || 0;
  2143. hash = (hash * 397) ^ (this.height || 0);
  2144. return hash;
  2145. };
  2146. /**
  2147. * Updates the current size from the passed one.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.copyFrom = function (src) {
  2151. this.width = src.width;
  2152. this.height = src.height;
  2153. };
  2154. /**
  2155. * Updates in place the current Size from the passed floats.
  2156. * Returns the updated Size.
  2157. */
  2158. Size.prototype.copyFromFloats = function (width, height) {
  2159. this.width = width;
  2160. this.height = height;
  2161. return this;
  2162. };
  2163. /**
  2164. * Updates in place the current Size from the passed floats.
  2165. * Returns the updated Size.
  2166. */
  2167. Size.prototype.set = function (width, height) {
  2168. return this.copyFromFloats(width, height);
  2169. };
  2170. /**
  2171. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2172. */
  2173. Size.prototype.multiplyByFloats = function (w, h) {
  2174. return new Size(this.width * w, this.height * h);
  2175. };
  2176. /**
  2177. * Returns a new Size copied from the passed one.
  2178. */
  2179. Size.prototype.clone = function () {
  2180. return new Size(this.width, this.height);
  2181. };
  2182. /**
  2183. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2184. */
  2185. Size.prototype.equals = function (other) {
  2186. if (!other) {
  2187. return false;
  2188. }
  2189. return (this.width === other.width) && (this.height === other.height);
  2190. };
  2191. Object.defineProperty(Size.prototype, "surface", {
  2192. /**
  2193. * Returns the surface of the Size : width * height (float).
  2194. */
  2195. get: function () {
  2196. return this.width * this.height;
  2197. },
  2198. enumerable: true,
  2199. configurable: true
  2200. });
  2201. /**
  2202. * Returns a new Size set to (0.0, 0.0)
  2203. */
  2204. Size.Zero = function () {
  2205. return new Size(0.0, 0.0);
  2206. };
  2207. /**
  2208. * Returns a new Size set as the addition result of the current Size and the passed one.
  2209. */
  2210. Size.prototype.add = function (otherSize) {
  2211. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2212. return r;
  2213. };
  2214. /**
  2215. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2216. */
  2217. Size.prototype.subtract = function (otherSize) {
  2218. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2223. */
  2224. Size.Lerp = function (start, end, amount) {
  2225. var w = start.width + ((end.width - start.width) * amount);
  2226. var h = start.height + ((end.height - start.height) * amount);
  2227. return new Size(w, h);
  2228. };
  2229. return Size;
  2230. }());
  2231. BABYLON.Size = Size;
  2232. var Quaternion = (function () {
  2233. /**
  2234. * Creates a new Quaternion from the passed floats.
  2235. */
  2236. function Quaternion(x, y, z, w) {
  2237. if (x === void 0) { x = 0.0; }
  2238. if (y === void 0) { y = 0.0; }
  2239. if (z === void 0) { z = 0.0; }
  2240. if (w === void 0) { w = 1.0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. this.z = z;
  2244. this.w = w;
  2245. }
  2246. /**
  2247. * Returns a string with the Quaternion coordinates.
  2248. */
  2249. Quaternion.prototype.toString = function () {
  2250. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2251. };
  2252. /**
  2253. * Returns the string "Quaternion".
  2254. */
  2255. Quaternion.prototype.getClassName = function () {
  2256. return "Quaternion";
  2257. };
  2258. /**
  2259. * Returns the Quaternion hash code.
  2260. */
  2261. Quaternion.prototype.getHashCode = function () {
  2262. var hash = this.x || 0;
  2263. hash = (hash * 397) ^ (this.y || 0);
  2264. hash = (hash * 397) ^ (this.z || 0);
  2265. hash = (hash * 397) ^ (this.w || 0);
  2266. return hash;
  2267. };
  2268. /**
  2269. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2270. */
  2271. Quaternion.prototype.asArray = function () {
  2272. return [this.x, this.y, this.z, this.w];
  2273. };
  2274. /**
  2275. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2276. */
  2277. Quaternion.prototype.equals = function (otherQuaternion) {
  2278. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2279. };
  2280. /**
  2281. * Returns a new Quaternion copied from the current one.
  2282. */
  2283. Quaternion.prototype.clone = function () {
  2284. return new Quaternion(this.x, this.y, this.z, this.w);
  2285. };
  2286. /**
  2287. * Updates the current Quaternion from the passed one coordinates.
  2288. * Returns the updated Quaterion.
  2289. */
  2290. Quaternion.prototype.copyFrom = function (other) {
  2291. this.x = other.x;
  2292. this.y = other.y;
  2293. this.z = other.z;
  2294. this.w = other.w;
  2295. return this;
  2296. };
  2297. /**
  2298. * Updates the current Quaternion from the passed float coordinates.
  2299. * Returns the updated Quaterion.
  2300. */
  2301. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2302. this.x = x;
  2303. this.y = y;
  2304. this.z = z;
  2305. this.w = w;
  2306. return this;
  2307. };
  2308. /**
  2309. * Updates the current Quaternion from the passed float coordinates.
  2310. * Returns the updated Quaterion.
  2311. */
  2312. Quaternion.prototype.set = function (x, y, z, w) {
  2313. return this.copyFromFloats(x, y, z, w);
  2314. };
  2315. /**
  2316. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2317. */
  2318. Quaternion.prototype.add = function (other) {
  2319. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2320. };
  2321. /**
  2322. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2323. */
  2324. Quaternion.prototype.subtract = function (other) {
  2325. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2326. };
  2327. /**
  2328. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2329. */
  2330. Quaternion.prototype.scale = function (value) {
  2331. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2332. };
  2333. /**
  2334. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2335. */
  2336. Quaternion.prototype.multiply = function (q1) {
  2337. var result = new Quaternion(0, 0, 0, 1.0);
  2338. this.multiplyToRef(q1, result);
  2339. return result;
  2340. };
  2341. /**
  2342. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2343. * Returns the current Quaternion.
  2344. */
  2345. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2346. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2347. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2348. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2349. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2350. result.copyFromFloats(x, y, z, w);
  2351. return this;
  2352. };
  2353. /**
  2354. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2355. * Returns the updated Quaternion.
  2356. */
  2357. Quaternion.prototype.multiplyInPlace = function (q1) {
  2358. this.multiplyToRef(q1, this);
  2359. return this;
  2360. };
  2361. /**
  2362. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2363. * Returns the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugateToRef = function (ref) {
  2366. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2367. return this;
  2368. };
  2369. /**
  2370. * Conjugates in place the current Quaternion.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.conjugateInPlace = function () {
  2374. this.x *= -1;
  2375. this.y *= -1;
  2376. this.z *= -1;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2381. */
  2382. Quaternion.prototype.conjugate = function () {
  2383. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2384. return result;
  2385. };
  2386. /**
  2387. * Returns the Quaternion length (float).
  2388. */
  2389. Quaternion.prototype.length = function () {
  2390. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2391. };
  2392. /**
  2393. * Normalize in place the current Quaternion.
  2394. * Returns the updated Quaternion.
  2395. */
  2396. Quaternion.prototype.normalize = function () {
  2397. var length = 1.0 / this.length();
  2398. this.x *= length;
  2399. this.y *= length;
  2400. this.z *= length;
  2401. this.w *= length;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAngles = function (order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var result = Vector3.Zero();
  2410. this.toEulerAnglesToRef(result, order);
  2411. return result;
  2412. };
  2413. /**
  2414. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2415. * Returns the current Quaternion.
  2416. */
  2417. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2418. if (order === void 0) { order = "YZX"; }
  2419. var qz = this.z;
  2420. var qx = this.x;
  2421. var qy = this.y;
  2422. var qw = this.w;
  2423. var sqw = qw * qw;
  2424. var sqz = qz * qz;
  2425. var sqx = qx * qx;
  2426. var sqy = qy * qy;
  2427. var zAxisY = qy * qz - qx * qw;
  2428. var limit = .4999999;
  2429. if (zAxisY < -limit) {
  2430. result.y = 2 * Math.atan2(qy, qw);
  2431. result.x = Math.PI / 2;
  2432. result.z = 0;
  2433. }
  2434. else if (zAxisY > limit) {
  2435. result.y = 2 * Math.atan2(qy, qw);
  2436. result.x = -Math.PI / 2;
  2437. result.z = 0;
  2438. }
  2439. else {
  2440. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2441. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2442. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2443. }
  2444. return this;
  2445. };
  2446. /**
  2447. * Updates the passed rotation matrix with the current Quaternion values.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.toRotationMatrix = function (result) {
  2451. var xx = this.x * this.x;
  2452. var yy = this.y * this.y;
  2453. var zz = this.z * this.z;
  2454. var xy = this.x * this.y;
  2455. var zw = this.z * this.w;
  2456. var zx = this.z * this.x;
  2457. var yw = this.y * this.w;
  2458. var yz = this.y * this.z;
  2459. var xw = this.x * this.w;
  2460. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2461. result.m[1] = 2.0 * (xy + zw);
  2462. result.m[2] = 2.0 * (zx - yw);
  2463. result.m[3] = 0;
  2464. result.m[4] = 2.0 * (xy - zw);
  2465. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2466. result.m[6] = 2.0 * (yz + xw);
  2467. result.m[7] = 0;
  2468. result.m[8] = 2.0 * (zx + yw);
  2469. result.m[9] = 2.0 * (yz - xw);
  2470. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2471. result.m[11] = 0;
  2472. result.m[12] = 0;
  2473. result.m[13] = 0;
  2474. result.m[14] = 0;
  2475. result.m[15] = 1.0;
  2476. result._markAsUpdated();
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed rotation matrix values.
  2481. * Returns the updated Quaternion.
  2482. */
  2483. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2484. Quaternion.FromRotationMatrixToRef(matrix, this);
  2485. return this;
  2486. };
  2487. // Statics
  2488. /**
  2489. * Returns a new Quaternion set from the passed rotation matrix values.
  2490. */
  2491. Quaternion.FromRotationMatrix = function (matrix) {
  2492. var result = new Quaternion();
  2493. Quaternion.FromRotationMatrixToRef(matrix, result);
  2494. return result;
  2495. };
  2496. /**
  2497. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2498. */
  2499. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2500. var data = matrix.m;
  2501. var m11 = data[0], m12 = data[4], m13 = data[8];
  2502. var m21 = data[1], m22 = data[5], m23 = data[9];
  2503. var m31 = data[2], m32 = data[6], m33 = data[10];
  2504. var trace = m11 + m22 + m33;
  2505. var s;
  2506. if (trace > 0) {
  2507. s = 0.5 / Math.sqrt(trace + 1.0);
  2508. result.w = 0.25 / s;
  2509. result.x = (m32 - m23) * s;
  2510. result.y = (m13 - m31) * s;
  2511. result.z = (m21 - m12) * s;
  2512. }
  2513. else if (m11 > m22 && m11 > m33) {
  2514. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2515. result.w = (m32 - m23) / s;
  2516. result.x = 0.25 * s;
  2517. result.y = (m12 + m21) / s;
  2518. result.z = (m13 + m31) / s;
  2519. }
  2520. else if (m22 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2522. result.w = (m13 - m31) / s;
  2523. result.x = (m12 + m21) / s;
  2524. result.y = 0.25 * s;
  2525. result.z = (m23 + m32) / s;
  2526. }
  2527. else {
  2528. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2529. result.w = (m21 - m12) / s;
  2530. result.x = (m13 + m31) / s;
  2531. result.y = (m23 + m32) / s;
  2532. result.z = 0.25 * s;
  2533. }
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2537. */
  2538. Quaternion.Zero = function () {
  2539. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion as the inverted current Quaternion.
  2543. */
  2544. Quaternion.Inverse = function (q) {
  2545. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2546. };
  2547. /**
  2548. * Returns the identity Quaternion.
  2549. */
  2550. Quaternion.Identity = function () {
  2551. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2552. };
  2553. Quaternion.IsIdentity = function (quaternion) {
  2554. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2558. */
  2559. Quaternion.RotationAxis = function (axis, angle) {
  2560. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2561. };
  2562. /**
  2563. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2564. */
  2565. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2566. var sin = Math.sin(angle / 2);
  2567. axis.normalize();
  2568. result.w = Math.cos(angle / 2);
  2569. result.x = axis.x * sin;
  2570. result.y = axis.y * sin;
  2571. result.z = axis.z * sin;
  2572. return result;
  2573. };
  2574. /**
  2575. * Retuns a new Quaternion set from the starting index of the passed array.
  2576. */
  2577. Quaternion.FromArray = function (array, offset) {
  2578. if (!offset) {
  2579. offset = 0;
  2580. }
  2581. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2585. */
  2586. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2587. var q = new Quaternion();
  2588. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2589. return q;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2593. */
  2594. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2595. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2596. var halfRoll = roll * 0.5;
  2597. var halfPitch = pitch * 0.5;
  2598. var halfYaw = yaw * 0.5;
  2599. var sinRoll = Math.sin(halfRoll);
  2600. var cosRoll = Math.cos(halfRoll);
  2601. var sinPitch = Math.sin(halfPitch);
  2602. var cosPitch = Math.cos(halfPitch);
  2603. var sinYaw = Math.sin(halfYaw);
  2604. var cosYaw = Math.cos(halfYaw);
  2605. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2606. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2607. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2608. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2609. };
  2610. /**
  2611. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2612. */
  2613. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2614. var result = new Quaternion();
  2615. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2620. */
  2621. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2622. // Produces a quaternion from Euler angles in the z-x-z orientation
  2623. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2624. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2625. var halfBeta = beta * 0.5;
  2626. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2627. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2628. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2629. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2637. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2639. return quat;
  2640. };
  2641. /**
  2642. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2643. * cf to Vector3.RotationFromAxis() documentation.
  2644. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2645. */
  2646. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2647. var rotMat = MathTmp.Matrix[0];
  2648. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2649. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2650. };
  2651. Quaternion.Slerp = function (left, right, amount) {
  2652. var result = Quaternion.Identity();
  2653. Quaternion.SlerpToRef(left, right, amount, result);
  2654. return result;
  2655. };
  2656. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2657. var num2;
  2658. var num3;
  2659. var num = amount;
  2660. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2661. var flag = false;
  2662. if (num4 < 0) {
  2663. flag = true;
  2664. num4 = -num4;
  2665. }
  2666. if (num4 > 0.999999) {
  2667. num3 = 1 - num;
  2668. num2 = flag ? -num : num;
  2669. }
  2670. else {
  2671. var num5 = Math.acos(num4);
  2672. var num6 = (1.0 / Math.sin(num5));
  2673. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2674. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2675. }
  2676. result.x = (num3 * left.x) + (num2 * right.x);
  2677. result.y = (num3 * left.y) + (num2 * right.y);
  2678. result.z = (num3 * left.z) + (num2 * right.z);
  2679. result.w = (num3 * left.w) + (num2 * right.w);
  2680. };
  2681. /**
  2682. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2683. */
  2684. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2685. var squared = amount * amount;
  2686. var cubed = amount * squared;
  2687. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2688. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2689. var part3 = (cubed - (2.0 * squared)) + amount;
  2690. var part4 = cubed - squared;
  2691. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2692. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2693. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2694. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2695. return new Quaternion(x, y, z, w);
  2696. };
  2697. return Quaternion;
  2698. }());
  2699. BABYLON.Quaternion = Quaternion;
  2700. var Matrix = (function () {
  2701. function Matrix() {
  2702. this._isIdentity = false;
  2703. this._isIdentityDirty = true;
  2704. this.m = new Float32Array(16);
  2705. this._markAsUpdated();
  2706. }
  2707. Matrix.prototype._markAsUpdated = function () {
  2708. this.updateFlag = Matrix._updateFlagSeed++;
  2709. this._isIdentityDirty = true;
  2710. };
  2711. // Properties
  2712. /**
  2713. * Boolean : True is the matrix is the identity matrix
  2714. */
  2715. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2716. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2717. if (this._isIdentityDirty) {
  2718. this._isIdentityDirty = false;
  2719. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2720. this._isIdentity = false;
  2721. }
  2722. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2726. this._isIdentity = false;
  2727. }
  2728. else {
  2729. this._isIdentity = true;
  2730. }
  2731. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2732. this._isIdentity = false;
  2733. }
  2734. }
  2735. return this._isIdentity;
  2736. };
  2737. /**
  2738. * Returns the matrix determinant (float).
  2739. */
  2740. Matrix.prototype.determinant = function () {
  2741. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2742. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2743. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2744. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2745. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2746. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2747. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2748. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2749. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2750. };
  2751. // Methods
  2752. /**
  2753. * Returns the matrix underlying array.
  2754. */
  2755. Matrix.prototype.toArray = function () {
  2756. return this.m;
  2757. };
  2758. /**
  2759. * Returns the matrix underlying array.
  2760. */
  2761. Matrix.prototype.asArray = function () {
  2762. return this.toArray();
  2763. };
  2764. /**
  2765. * Inverts in place the Matrix.
  2766. * Returns the Matrix inverted.
  2767. */
  2768. Matrix.prototype.invert = function () {
  2769. this.invertToRef(this);
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets all the matrix elements to zero.
  2774. * Returns the Matrix.
  2775. */
  2776. Matrix.prototype.reset = function () {
  2777. for (var index = 0; index < 16; index++) {
  2778. this.m[index] = 0.0;
  2779. }
  2780. this._markAsUpdated();
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2785. */
  2786. Matrix.prototype.add = function (other) {
  2787. var result = new Matrix();
  2788. this.addToRef(other, result);
  2789. return result;
  2790. };
  2791. /**
  2792. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2793. * Returns the Matrix.
  2794. */
  2795. Matrix.prototype.addToRef = function (other, result) {
  2796. for (var index = 0; index < 16; index++) {
  2797. result.m[index] = this.m[index] + other.m[index];
  2798. }
  2799. result._markAsUpdated();
  2800. return this;
  2801. };
  2802. /**
  2803. * Adds in place the passed matrix to the current Matrix.
  2804. * Returns the updated Matrix.
  2805. */
  2806. Matrix.prototype.addToSelf = function (other) {
  2807. for (var index = 0; index < 16; index++) {
  2808. this.m[index] += other.m[index];
  2809. }
  2810. this._markAsUpdated();
  2811. return this;
  2812. };
  2813. /**
  2814. * Sets the passed matrix with the current inverted Matrix.
  2815. * Returns the unmodified current Matrix.
  2816. */
  2817. Matrix.prototype.invertToRef = function (other) {
  2818. var l1 = this.m[0];
  2819. var l2 = this.m[1];
  2820. var l3 = this.m[2];
  2821. var l4 = this.m[3];
  2822. var l5 = this.m[4];
  2823. var l6 = this.m[5];
  2824. var l7 = this.m[6];
  2825. var l8 = this.m[7];
  2826. var l9 = this.m[8];
  2827. var l10 = this.m[9];
  2828. var l11 = this.m[10];
  2829. var l12 = this.m[11];
  2830. var l13 = this.m[12];
  2831. var l14 = this.m[13];
  2832. var l15 = this.m[14];
  2833. var l16 = this.m[15];
  2834. var l17 = (l11 * l16) - (l12 * l15);
  2835. var l18 = (l10 * l16) - (l12 * l14);
  2836. var l19 = (l10 * l15) - (l11 * l14);
  2837. var l20 = (l9 * l16) - (l12 * l13);
  2838. var l21 = (l9 * l15) - (l11 * l13);
  2839. var l22 = (l9 * l14) - (l10 * l13);
  2840. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2841. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2842. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2843. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2844. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2845. var l28 = (l7 * l16) - (l8 * l15);
  2846. var l29 = (l6 * l16) - (l8 * l14);
  2847. var l30 = (l6 * l15) - (l7 * l14);
  2848. var l31 = (l5 * l16) - (l8 * l13);
  2849. var l32 = (l5 * l15) - (l7 * l13);
  2850. var l33 = (l5 * l14) - (l6 * l13);
  2851. var l34 = (l7 * l12) - (l8 * l11);
  2852. var l35 = (l6 * l12) - (l8 * l10);
  2853. var l36 = (l6 * l11) - (l7 * l10);
  2854. var l37 = (l5 * l12) - (l8 * l9);
  2855. var l38 = (l5 * l11) - (l7 * l9);
  2856. var l39 = (l5 * l10) - (l6 * l9);
  2857. other.m[0] = l23 * l27;
  2858. other.m[4] = l24 * l27;
  2859. other.m[8] = l25 * l27;
  2860. other.m[12] = l26 * l27;
  2861. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2862. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2863. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2864. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2865. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2866. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2867. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2868. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2869. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2870. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2871. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2872. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2873. other._markAsUpdated();
  2874. return this;
  2875. };
  2876. /**
  2877. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2878. * Returns the updated Matrix.
  2879. */
  2880. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2881. this.m[12] = x;
  2882. this.m[13] = y;
  2883. this.m[14] = z;
  2884. this._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Inserts the translation vector in the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.setTranslation = function (vector3) {
  2892. this.m[12] = vector3.x;
  2893. this.m[13] = vector3.y;
  2894. this.m[14] = vector3.z;
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3 as the extracted translation from the Matrix.
  2900. */
  2901. Matrix.prototype.getTranslation = function () {
  2902. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2903. };
  2904. /**
  2905. * Fill a Vector3 with the extracted translation from the Matrix.
  2906. */
  2907. Matrix.prototype.getTranslationToRef = function (result) {
  2908. result.x = this.m[12];
  2909. result.y = this.m[13];
  2910. result.z = this.m[14];
  2911. return this;
  2912. };
  2913. /**
  2914. * Remove rotation and scaling part from the Matrix.
  2915. * Returns the updated Matrix.
  2916. */
  2917. Matrix.prototype.removeRotationAndScaling = function () {
  2918. this.setRowFromFloats(0, 1, 0, 0, 0);
  2919. this.setRowFromFloats(1, 0, 1, 0, 0);
  2920. this.setRowFromFloats(2, 0, 0, 1, 0);
  2921. return this;
  2922. };
  2923. /**
  2924. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2925. */
  2926. Matrix.prototype.multiply = function (other) {
  2927. var result = new Matrix();
  2928. this.multiplyToRef(other, result);
  2929. return result;
  2930. };
  2931. /**
  2932. * Updates the current Matrix from the passed one values.
  2933. * Returns the updated Matrix.
  2934. */
  2935. Matrix.prototype.copyFrom = function (other) {
  2936. for (var index = 0; index < 16; index++) {
  2937. this.m[index] = other.m[index];
  2938. }
  2939. this._markAsUpdated();
  2940. return this;
  2941. };
  2942. /**
  2943. * Populates the passed array from the starting index with the Matrix values.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.copyToArray = function (array, offset) {
  2947. if (offset === void 0) { offset = 0; }
  2948. for (var index = 0; index < 16; index++) {
  2949. array[offset + index] = this.m[index];
  2950. }
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToRef = function (other, result) {
  2957. this.multiplyToArray(other, result.m, 0);
  2958. result._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2963. */
  2964. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2965. var tm0 = this.m[0];
  2966. var tm1 = this.m[1];
  2967. var tm2 = this.m[2];
  2968. var tm3 = this.m[3];
  2969. var tm4 = this.m[4];
  2970. var tm5 = this.m[5];
  2971. var tm6 = this.m[6];
  2972. var tm7 = this.m[7];
  2973. var tm8 = this.m[8];
  2974. var tm9 = this.m[9];
  2975. var tm10 = this.m[10];
  2976. var tm11 = this.m[11];
  2977. var tm12 = this.m[12];
  2978. var tm13 = this.m[13];
  2979. var tm14 = this.m[14];
  2980. var tm15 = this.m[15];
  2981. var om0 = other.m[0];
  2982. var om1 = other.m[1];
  2983. var om2 = other.m[2];
  2984. var om3 = other.m[3];
  2985. var om4 = other.m[4];
  2986. var om5 = other.m[5];
  2987. var om6 = other.m[6];
  2988. var om7 = other.m[7];
  2989. var om8 = other.m[8];
  2990. var om9 = other.m[9];
  2991. var om10 = other.m[10];
  2992. var om11 = other.m[11];
  2993. var om12 = other.m[12];
  2994. var om13 = other.m[13];
  2995. var om14 = other.m[14];
  2996. var om15 = other.m[15];
  2997. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2998. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2999. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3000. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3001. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3002. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3003. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3004. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3005. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3006. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3007. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3008. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3009. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3010. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3011. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3012. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3013. return this;
  3014. };
  3015. /**
  3016. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3017. */
  3018. Matrix.prototype.equals = function (value) {
  3019. return value &&
  3020. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3021. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3022. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3023. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3024. };
  3025. /**
  3026. * Returns a new Matrix from the current Matrix.
  3027. */
  3028. Matrix.prototype.clone = function () {
  3029. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3030. };
  3031. /**
  3032. * Returns the string "Matrix"
  3033. */
  3034. Matrix.prototype.getClassName = function () {
  3035. return "Matrix";
  3036. };
  3037. /**
  3038. * Returns the Matrix hash code.
  3039. */
  3040. Matrix.prototype.getHashCode = function () {
  3041. var hash = this.m[0] || 0;
  3042. for (var i = 1; i < 16; i++) {
  3043. hash = (hash * 397) ^ (this.m[i] || 0);
  3044. }
  3045. return hash;
  3046. };
  3047. /**
  3048. * Decomposes the current Matrix into :
  3049. * - a scale vector3 passed as a reference to update,
  3050. * - a rotation quaternion passed as a reference to update,
  3051. * - a translation vector3 passed as a reference to update.
  3052. * Returns the boolean `true`.
  3053. */
  3054. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3055. translation.x = this.m[12];
  3056. translation.y = this.m[13];
  3057. translation.z = this.m[14];
  3058. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3059. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3060. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3061. if (this.determinant() <= 0) {
  3062. scale.y *= -1;
  3063. }
  3064. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3065. rotation.x = 0;
  3066. rotation.y = 0;
  3067. rotation.z = 0;
  3068. rotation.w = 1;
  3069. return false;
  3070. }
  3071. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3072. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3073. return true;
  3074. };
  3075. /**
  3076. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3077. */
  3078. Matrix.prototype.getRotationMatrix = function () {
  3079. var result = Matrix.Identity();
  3080. this.getRotationMatrixToRef(result);
  3081. return result;
  3082. };
  3083. /**
  3084. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3085. * Returns the current Matrix.
  3086. */
  3087. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3088. var m = this.m;
  3089. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3090. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3091. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3092. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3093. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3094. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3095. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3096. return this;
  3097. };
  3098. // Statics
  3099. /**
  3100. * Returns a new Matrix set from the starting index of the passed array.
  3101. */
  3102. Matrix.FromArray = function (array, offset) {
  3103. var result = new Matrix();
  3104. if (!offset) {
  3105. offset = 0;
  3106. }
  3107. Matrix.FromArrayToRef(array, offset, result);
  3108. return result;
  3109. };
  3110. /**
  3111. * Sets the passed "result" matrix from the starting index of the passed array.
  3112. */
  3113. Matrix.FromArrayToRef = function (array, offset, result) {
  3114. for (var index = 0; index < 16; index++) {
  3115. result.m[index] = array[index + offset];
  3116. }
  3117. result._markAsUpdated();
  3118. };
  3119. /**
  3120. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3121. */
  3122. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3123. for (var index = 0; index < 16; index++) {
  3124. result.m[index] = array[index + offset] * scale;
  3125. }
  3126. result._markAsUpdated();
  3127. };
  3128. /**
  3129. * Sets the passed matrix "result" with the 16 passed floats.
  3130. */
  3131. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3132. result.m[0] = initialM11;
  3133. result.m[1] = initialM12;
  3134. result.m[2] = initialM13;
  3135. result.m[3] = initialM14;
  3136. result.m[4] = initialM21;
  3137. result.m[5] = initialM22;
  3138. result.m[6] = initialM23;
  3139. result.m[7] = initialM24;
  3140. result.m[8] = initialM31;
  3141. result.m[9] = initialM32;
  3142. result.m[10] = initialM33;
  3143. result.m[11] = initialM34;
  3144. result.m[12] = initialM41;
  3145. result.m[13] = initialM42;
  3146. result.m[14] = initialM43;
  3147. result.m[15] = initialM44;
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Returns the index-th row of the current matrix as a new Vector4.
  3152. */
  3153. Matrix.prototype.getRow = function (index) {
  3154. if (index < 0 || index > 3) {
  3155. return null;
  3156. }
  3157. var i = index * 4;
  3158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3159. };
  3160. /**
  3161. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.setRow = function (index, row) {
  3165. if (index < 0 || index > 3) {
  3166. return this;
  3167. }
  3168. var i = index * 4;
  3169. this.m[i + 0] = row.x;
  3170. this.m[i + 1] = row.y;
  3171. this.m[i + 2] = row.z;
  3172. this.m[i + 3] = row.w;
  3173. this._markAsUpdated();
  3174. return this;
  3175. };
  3176. /**
  3177. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3178. * Returns the updated Matrix.
  3179. */
  3180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3181. if (index < 0 || index > 3) {
  3182. return this;
  3183. }
  3184. var i = index * 4;
  3185. this.m[i + 0] = x;
  3186. this.m[i + 1] = y;
  3187. this.m[i + 2] = z;
  3188. this.m[i + 3] = w;
  3189. this._markAsUpdated();
  3190. return this;
  3191. };
  3192. /**
  3193. * Returns a new Matrix set from the 16 passed floats.
  3194. */
  3195. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3196. var result = new Matrix();
  3197. result.m[0] = initialM11;
  3198. result.m[1] = initialM12;
  3199. result.m[2] = initialM13;
  3200. result.m[3] = initialM14;
  3201. result.m[4] = initialM21;
  3202. result.m[5] = initialM22;
  3203. result.m[6] = initialM23;
  3204. result.m[7] = initialM24;
  3205. result.m[8] = initialM31;
  3206. result.m[9] = initialM32;
  3207. result.m[10] = initialM33;
  3208. result.m[11] = initialM34;
  3209. result.m[12] = initialM41;
  3210. result.m[13] = initialM42;
  3211. result.m[14] = initialM43;
  3212. result.m[15] = initialM44;
  3213. return result;
  3214. };
  3215. /**
  3216. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.Compose = function (scale, rotation, translation) {
  3219. var result = Matrix.Identity();
  3220. Matrix.ComposeToRef(scale, rotation, translation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3225. */
  3226. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3227. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3228. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3229. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3230. result.setTranslation(translation);
  3231. };
  3232. /**
  3233. * Returns a new indentity Matrix.
  3234. */
  3235. Matrix.Identity = function () {
  3236. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3237. };
  3238. /**
  3239. * Sets the passed "result" as an identity matrix.
  3240. */
  3241. Matrix.IdentityToRef = function (result) {
  3242. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3243. };
  3244. /**
  3245. * Returns a new zero Matrix.
  3246. */
  3247. Matrix.Zero = function () {
  3248. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3249. };
  3250. /**
  3251. * Returns a new rotation matrix for "angle" radians around the X axis.
  3252. */
  3253. Matrix.RotationX = function (angle) {
  3254. var result = new Matrix();
  3255. Matrix.RotationXToRef(angle, result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Returns a new Matrix as the passed inverted one.
  3260. */
  3261. Matrix.Invert = function (source) {
  3262. var result = new Matrix();
  3263. source.invertToRef(result);
  3264. return result;
  3265. };
  3266. /**
  3267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3268. */
  3269. Matrix.RotationXToRef = function (angle, result) {
  3270. var s = Math.sin(angle);
  3271. var c = Math.cos(angle);
  3272. result.m[0] = 1.0;
  3273. result.m[15] = 1.0;
  3274. result.m[5] = c;
  3275. result.m[10] = c;
  3276. result.m[9] = -s;
  3277. result.m[6] = s;
  3278. result.m[1] = 0.0;
  3279. result.m[2] = 0.0;
  3280. result.m[3] = 0.0;
  3281. result.m[4] = 0.0;
  3282. result.m[7] = 0.0;
  3283. result.m[8] = 0.0;
  3284. result.m[11] = 0.0;
  3285. result.m[12] = 0.0;
  3286. result.m[13] = 0.0;
  3287. result.m[14] = 0.0;
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationY = function (angle) {
  3294. var result = new Matrix();
  3295. Matrix.RotationYToRef(angle, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3300. */
  3301. Matrix.RotationYToRef = function (angle, result) {
  3302. var s = Math.sin(angle);
  3303. var c = Math.cos(angle);
  3304. result.m[5] = 1.0;
  3305. result.m[15] = 1.0;
  3306. result.m[0] = c;
  3307. result.m[2] = -s;
  3308. result.m[8] = s;
  3309. result.m[10] = c;
  3310. result.m[1] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[6] = 0.0;
  3314. result.m[7] = 0.0;
  3315. result.m[9] = 0.0;
  3316. result.m[11] = 0.0;
  3317. result.m[12] = 0.0;
  3318. result.m[13] = 0.0;
  3319. result.m[14] = 0.0;
  3320. result._markAsUpdated();
  3321. };
  3322. /**
  3323. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZ = function (angle) {
  3326. var result = new Matrix();
  3327. Matrix.RotationZToRef(angle, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3332. */
  3333. Matrix.RotationZToRef = function (angle, result) {
  3334. var s = Math.sin(angle);
  3335. var c = Math.cos(angle);
  3336. result.m[10] = 1.0;
  3337. result.m[15] = 1.0;
  3338. result.m[0] = c;
  3339. result.m[1] = s;
  3340. result.m[4] = -s;
  3341. result.m[5] = c;
  3342. result.m[2] = 0.0;
  3343. result.m[3] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[8] = 0.0;
  3347. result.m[9] = 0.0;
  3348. result.m[11] = 0.0;
  3349. result.m[12] = 0.0;
  3350. result.m[13] = 0.0;
  3351. result.m[14] = 0.0;
  3352. result._markAsUpdated();
  3353. };
  3354. /**
  3355. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxis = function (axis, angle) {
  3358. var result = Matrix.Zero();
  3359. Matrix.RotationAxisToRef(axis, angle, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3364. */
  3365. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3366. var s = Math.sin(-angle);
  3367. var c = Math.cos(-angle);
  3368. var c1 = 1 - c;
  3369. axis.normalize();
  3370. result.m[0] = (axis.x * axis.x) * c1 + c;
  3371. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3372. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3373. result.m[3] = 0.0;
  3374. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3375. result.m[5] = (axis.y * axis.y) * c1 + c;
  3376. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3377. result.m[7] = 0.0;
  3378. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3379. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3380. result.m[10] = (axis.z * axis.z) * c1 + c;
  3381. result.m[11] = 0.0;
  3382. result.m[15] = 1.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3389. var result = new Matrix();
  3390. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3395. */
  3396. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3397. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3398. this._tempQuaternion.toRotationMatrix(result);
  3399. };
  3400. /**
  3401. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.Scaling = function (x, y, z) {
  3404. var result = Matrix.Zero();
  3405. Matrix.ScalingToRef(x, y, z, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3410. */
  3411. Matrix.ScalingToRef = function (x, y, z, result) {
  3412. result.m[0] = x;
  3413. result.m[1] = 0.0;
  3414. result.m[2] = 0.0;
  3415. result.m[3] = 0.0;
  3416. result.m[4] = 0.0;
  3417. result.m[5] = y;
  3418. result.m[6] = 0.0;
  3419. result.m[7] = 0.0;
  3420. result.m[8] = 0.0;
  3421. result.m[9] = 0.0;
  3422. result.m[10] = z;
  3423. result.m[11] = 0.0;
  3424. result.m[12] = 0.0;
  3425. result.m[13] = 0.0;
  3426. result.m[14] = 0.0;
  3427. result.m[15] = 1.0;
  3428. result._markAsUpdated();
  3429. };
  3430. /**
  3431. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.Translation = function (x, y, z) {
  3434. var result = Matrix.Identity();
  3435. Matrix.TranslationToRef(x, y, z, result);
  3436. return result;
  3437. };
  3438. /**
  3439. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3440. */
  3441. Matrix.TranslationToRef = function (x, y, z, result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3446. */
  3447. Matrix.Lerp = function (startValue, endValue, gradient) {
  3448. var result = Matrix.Zero();
  3449. for (var index = 0; index < 16; index++) {
  3450. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3451. }
  3452. result._markAsUpdated();
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix whose values are computed by :
  3457. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3458. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3459. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3460. */
  3461. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3462. var startScale = new Vector3(0, 0, 0);
  3463. var startRotation = new Quaternion();
  3464. var startTranslation = new Vector3(0, 0, 0);
  3465. startValue.decompose(startScale, startRotation, startTranslation);
  3466. var endScale = new Vector3(0, 0, 0);
  3467. var endRotation = new Quaternion();
  3468. var endTranslation = new Vector3(0, 0, 0);
  3469. endValue.decompose(endScale, endRotation, endTranslation);
  3470. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3471. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3472. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3473. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3474. };
  3475. /**
  3476. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3477. * This methods works for a Left-Handed system.
  3478. */
  3479. Matrix.LookAtLH = function (eye, target, up) {
  3480. var result = Matrix.Zero();
  3481. Matrix.LookAtLHToRef(eye, target, up, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3486. * This methods works for a Left-Handed system.
  3487. */
  3488. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3489. // Z axis
  3490. target.subtractToRef(eye, this._zAxis);
  3491. this._zAxis.normalize();
  3492. // X axis
  3493. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3494. if (this._xAxis.lengthSquared() === 0) {
  3495. this._xAxis.x = 1.0;
  3496. }
  3497. else {
  3498. this._xAxis.normalize();
  3499. }
  3500. // Y axis
  3501. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3502. this._yAxis.normalize();
  3503. // Eye angles
  3504. var ex = -Vector3.Dot(this._xAxis, eye);
  3505. var ey = -Vector3.Dot(this._yAxis, eye);
  3506. var ez = -Vector3.Dot(this._zAxis, eye);
  3507. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3508. };
  3509. /**
  3510. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3511. * This methods works for a Right-Handed system.
  3512. */
  3513. Matrix.LookAtRH = function (eye, target, up) {
  3514. var result = Matrix.Zero();
  3515. Matrix.LookAtRHToRef(eye, target, up, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3520. * This methods works for a Left-Handed system.
  3521. */
  3522. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3523. // Z axis
  3524. eye.subtractToRef(target, this._zAxis);
  3525. this._zAxis.normalize();
  3526. // X axis
  3527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3528. if (this._xAxis.lengthSquared() === 0) {
  3529. this._xAxis.x = 1.0;
  3530. }
  3531. else {
  3532. this._xAxis.normalize();
  3533. }
  3534. // Y axis
  3535. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3536. this._yAxis.normalize();
  3537. // Eye angles
  3538. var ex = -Vector3.Dot(this._xAxis, eye);
  3539. var ey = -Vector3.Dot(this._yAxis, eye);
  3540. var ez = -Vector3.Dot(this._zAxis, eye);
  3541. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3542. };
  3543. /**
  3544. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3545. */
  3546. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3547. var matrix = Matrix.Zero();
  3548. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3549. return matrix;
  3550. };
  3551. /**
  3552. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3553. */
  3554. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3555. var n = znear;
  3556. var f = zfar;
  3557. var a = 2.0 / width;
  3558. var b = 2.0 / height;
  3559. var c = 2.0 / (f - n);
  3560. var d = -(f + n) / (f - n);
  3561. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3562. };
  3563. /**
  3564. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3565. */
  3566. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3567. var matrix = Matrix.Zero();
  3568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3569. return matrix;
  3570. };
  3571. /**
  3572. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3573. */
  3574. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3575. var n = znear;
  3576. var f = zfar;
  3577. var a = 2.0 / (right - left);
  3578. var b = 2.0 / (top - bottom);
  3579. var c = 2.0 / (f - n);
  3580. var d = -(f + n) / (f - n);
  3581. var i0 = (left + right) / (left - right);
  3582. var i1 = (top + bottom) / (bottom - top);
  3583. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3587. */
  3588. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3589. var matrix = Matrix.Zero();
  3590. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3591. return matrix;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3595. */
  3596. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3597. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3598. result.m[10] *= -1.0;
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3602. */
  3603. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3604. var matrix = Matrix.Zero();
  3605. var n = znear;
  3606. var f = zfar;
  3607. var a = 2.0 * n / width;
  3608. var b = 2.0 * n / height;
  3609. var c = (f + n) / (f - n);
  3610. var d = -2.0 * f * n / (f - n);
  3611. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3616. */
  3617. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3618. var matrix = Matrix.Zero();
  3619. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3620. return matrix;
  3621. };
  3622. /**
  3623. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3624. */
  3625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3627. var n = znear;
  3628. var f = zfar;
  3629. var t = 1.0 / (Math.tan(fov * 0.5));
  3630. var a = isVerticalFovFixed ? (t / aspect) : t;
  3631. var b = isVerticalFovFixed ? t : (t * aspect);
  3632. var c = (f + n) / (f - n);
  3633. var d = -2.0 * f * n / (f - n);
  3634. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3635. };
  3636. /**
  3637. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3638. */
  3639. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3640. var matrix = Matrix.Zero();
  3641. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3642. return matrix;
  3643. };
  3644. /**
  3645. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3646. */
  3647. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3648. //alternatively this could be expressed as:
  3649. // m = PerspectiveFovLHToRef
  3650. // m[10] *= -1.0;
  3651. // m[11] *= -1.0;
  3652. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3653. var n = znear;
  3654. var f = zfar;
  3655. var t = 1.0 / (Math.tan(fov * 0.5));
  3656. var a = isVerticalFovFixed ? (t / aspect) : t;
  3657. var b = isVerticalFovFixed ? t : (t * aspect);
  3658. var c = -(f + n) / (f - n);
  3659. var d = -2 * f * n / (f - n);
  3660. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3661. };
  3662. /**
  3663. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3664. */
  3665. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3666. if (rightHanded === void 0) { rightHanded = false; }
  3667. var rightHandedFactor = rightHanded ? -1 : 1;
  3668. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3669. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3670. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3671. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3672. var xScale = 2.0 / (leftTan + rightTan);
  3673. var yScale = 2.0 / (upTan + downTan);
  3674. result.m[0] = xScale;
  3675. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3676. result.m[5] = yScale;
  3677. result.m[6] = result.m[7] = 0.0;
  3678. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3679. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3680. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3681. result.m[10] = -zfar / (znear - zfar);
  3682. result.m[11] = 1.0 * rightHandedFactor;
  3683. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3684. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3685. // result.m[14] = (znear * zfar) / (znear - zfar);
  3686. result._markAsUpdated();
  3687. };
  3688. /**
  3689. * Returns the final transformation matrix : world * view * projection * viewport
  3690. */
  3691. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3692. var cw = viewport.width;
  3693. var ch = viewport.height;
  3694. var cx = viewport.x;
  3695. var cy = viewport.y;
  3696. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3697. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3698. };
  3699. /**
  3700. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3701. */
  3702. Matrix.GetAsMatrix2x2 = function (matrix) {
  3703. return new Float32Array([
  3704. matrix.m[0], matrix.m[1],
  3705. matrix.m[4], matrix.m[5]
  3706. ]);
  3707. };
  3708. /**
  3709. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3710. */
  3711. Matrix.GetAsMatrix3x3 = function (matrix) {
  3712. return new Float32Array([
  3713. matrix.m[0], matrix.m[1], matrix.m[2],
  3714. matrix.m[4], matrix.m[5], matrix.m[6],
  3715. matrix.m[8], matrix.m[9], matrix.m[10]
  3716. ]);
  3717. };
  3718. /**
  3719. * Compute the transpose of the passed Matrix.
  3720. * Returns a new Matrix.
  3721. */
  3722. Matrix.Transpose = function (matrix) {
  3723. var result = new Matrix();
  3724. result.m[0] = matrix.m[0];
  3725. result.m[1] = matrix.m[4];
  3726. result.m[2] = matrix.m[8];
  3727. result.m[3] = matrix.m[12];
  3728. result.m[4] = matrix.m[1];
  3729. result.m[5] = matrix.m[5];
  3730. result.m[6] = matrix.m[9];
  3731. result.m[7] = matrix.m[13];
  3732. result.m[8] = matrix.m[2];
  3733. result.m[9] = matrix.m[6];
  3734. result.m[10] = matrix.m[10];
  3735. result.m[11] = matrix.m[14];
  3736. result.m[12] = matrix.m[3];
  3737. result.m[13] = matrix.m[7];
  3738. result.m[14] = matrix.m[11];
  3739. result.m[15] = matrix.m[15];
  3740. return result;
  3741. };
  3742. /**
  3743. * Returns a new Matrix as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.Reflection = function (plane) {
  3746. var matrix = new Matrix();
  3747. Matrix.ReflectionToRef(plane, matrix);
  3748. return matrix;
  3749. };
  3750. /**
  3751. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3752. */
  3753. Matrix.ReflectionToRef = function (plane, result) {
  3754. plane.normalize();
  3755. var x = plane.normal.x;
  3756. var y = plane.normal.y;
  3757. var z = plane.normal.z;
  3758. var temp = -2 * x;
  3759. var temp2 = -2 * y;
  3760. var temp3 = -2 * z;
  3761. result.m[0] = (temp * x) + 1;
  3762. result.m[1] = temp2 * x;
  3763. result.m[2] = temp3 * x;
  3764. result.m[3] = 0.0;
  3765. result.m[4] = temp * y;
  3766. result.m[5] = (temp2 * y) + 1;
  3767. result.m[6] = temp3 * y;
  3768. result.m[7] = 0.0;
  3769. result.m[8] = temp * z;
  3770. result.m[9] = temp2 * z;
  3771. result.m[10] = (temp3 * z) + 1;
  3772. result.m[11] = 0.0;
  3773. result.m[12] = temp * plane.d;
  3774. result.m[13] = temp2 * plane.d;
  3775. result.m[14] = temp3 * plane.d;
  3776. result.m[15] = 1.0;
  3777. result._markAsUpdated();
  3778. };
  3779. /**
  3780. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3781. */
  3782. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3783. result.m[0] = xaxis.x;
  3784. result.m[1] = xaxis.y;
  3785. result.m[2] = xaxis.z;
  3786. result.m[3] = 0.0;
  3787. result.m[4] = yaxis.x;
  3788. result.m[5] = yaxis.y;
  3789. result.m[6] = yaxis.z;
  3790. result.m[7] = 0.0;
  3791. result.m[8] = zaxis.x;
  3792. result.m[9] = zaxis.y;
  3793. result.m[10] = zaxis.z;
  3794. result.m[11] = 0.0;
  3795. result.m[12] = 0.0;
  3796. result.m[13] = 0.0;
  3797. result.m[14] = 0.0;
  3798. result.m[15] = 1.0;
  3799. result._markAsUpdated();
  3800. };
  3801. /**
  3802. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3803. */
  3804. Matrix.FromQuaternionToRef = function (quat, result) {
  3805. var xx = quat.x * quat.x;
  3806. var yy = quat.y * quat.y;
  3807. var zz = quat.z * quat.z;
  3808. var xy = quat.x * quat.y;
  3809. var zw = quat.z * quat.w;
  3810. var zx = quat.z * quat.x;
  3811. var yw = quat.y * quat.w;
  3812. var yz = quat.y * quat.z;
  3813. var xw = quat.x * quat.w;
  3814. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3815. result.m[1] = 2.0 * (xy + zw);
  3816. result.m[2] = 2.0 * (zx - yw);
  3817. result.m[3] = 0.0;
  3818. result.m[4] = 2.0 * (xy - zw);
  3819. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3820. result.m[6] = 2.0 * (yz + xw);
  3821. result.m[7] = 0.0;
  3822. result.m[8] = 2.0 * (zx + yw);
  3823. result.m[9] = 2.0 * (yz - xw);
  3824. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. return Matrix;
  3833. }());
  3834. Matrix._tempQuaternion = new Quaternion();
  3835. Matrix._xAxis = Vector3.Zero();
  3836. Matrix._yAxis = Vector3.Zero();
  3837. Matrix._zAxis = Vector3.Zero();
  3838. Matrix._updateFlagSeed = 0;
  3839. BABYLON.Matrix = Matrix;
  3840. var Plane = (function () {
  3841. /**
  3842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3843. */
  3844. function Plane(a, b, c, d) {
  3845. this.normal = new Vector3(a, b, c);
  3846. this.d = d;
  3847. }
  3848. /**
  3849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3850. */
  3851. Plane.prototype.asArray = function () {
  3852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3853. };
  3854. // Methods
  3855. /**
  3856. * Returns a new plane copied from the current Plane.
  3857. */
  3858. Plane.prototype.clone = function () {
  3859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3860. };
  3861. /**
  3862. * Returns the string "Plane".
  3863. */
  3864. Plane.prototype.getClassName = function () {
  3865. return "Plane";
  3866. };
  3867. /**
  3868. * Returns the Plane hash code.
  3869. */
  3870. Plane.prototype.getHashCode = function () {
  3871. var hash = this.normal.getHashCode();
  3872. hash = (hash * 397) ^ (this.d || 0);
  3873. return hash;
  3874. };
  3875. /**
  3876. * Normalize the current Plane in place.
  3877. * Returns the updated Plane.
  3878. */
  3879. Plane.prototype.normalize = function () {
  3880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3881. var magnitude = 0.0;
  3882. if (norm !== 0) {
  3883. magnitude = 1.0 / norm;
  3884. }
  3885. this.normal.x *= magnitude;
  3886. this.normal.y *= magnitude;
  3887. this.normal.z *= magnitude;
  3888. this.d *= magnitude;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3893. */
  3894. Plane.prototype.transform = function (transformation) {
  3895. var transposedMatrix = Matrix.Transpose(transformation);
  3896. var x = this.normal.x;
  3897. var y = this.normal.y;
  3898. var z = this.normal.z;
  3899. var d = this.d;
  3900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3904. return new Plane(normalX, normalY, normalZ, finalD);
  3905. };
  3906. /**
  3907. * Returns the dot product (float) of the point coordinates and the plane normal.
  3908. */
  3909. Plane.prototype.dotCoordinate = function (point) {
  3910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3911. };
  3912. /**
  3913. * Updates the current Plane from the plane defined by the three passed points.
  3914. * Returns the updated Plane.
  3915. */
  3916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3917. var x1 = point2.x - point1.x;
  3918. var y1 = point2.y - point1.y;
  3919. var z1 = point2.z - point1.z;
  3920. var x2 = point3.x - point1.x;
  3921. var y2 = point3.y - point1.y;
  3922. var z2 = point3.z - point1.z;
  3923. var yz = (y1 * z2) - (z1 * y2);
  3924. var xz = (z1 * x2) - (x1 * z2);
  3925. var xy = (x1 * y2) - (y1 * x2);
  3926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3927. var invPyth;
  3928. if (pyth !== 0) {
  3929. invPyth = 1.0 / pyth;
  3930. }
  3931. else {
  3932. invPyth = 0.0;
  3933. }
  3934. this.normal.x = yz * invPyth;
  3935. this.normal.y = xz * invPyth;
  3936. this.normal.z = xy * invPyth;
  3937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3942. */
  3943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3944. var dot = Vector3.Dot(this.normal, direction);
  3945. return (dot <= epsilon);
  3946. };
  3947. /**
  3948. * Returns the signed distance (float) from the passed point to the Plane.
  3949. */
  3950. Plane.prototype.signedDistanceTo = function (point) {
  3951. return Vector3.Dot(point, this.normal) + this.d;
  3952. };
  3953. // Statics
  3954. /**
  3955. * Returns a new Plane from the passed array.
  3956. */
  3957. Plane.FromArray = function (array) {
  3958. return new Plane(array[0], array[1], array[2], array[3]);
  3959. };
  3960. /**
  3961. * Returns a new Plane defined by the three passed points.
  3962. */
  3963. Plane.FromPoints = function (point1, point2, point3) {
  3964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3965. result.copyFromPoints(point1, point2, point3);
  3966. return result;
  3967. };
  3968. /**
  3969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3970. * Note : the vector "normal" is updated because normalized.
  3971. */
  3972. Plane.FromPositionAndNormal = function (origin, normal) {
  3973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3974. normal.normalize();
  3975. result.normal = normal;
  3976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3977. return result;
  3978. };
  3979. /**
  3980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3981. */
  3982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3984. return Vector3.Dot(point, normal) + d;
  3985. };
  3986. return Plane;
  3987. }());
  3988. BABYLON.Plane = Plane;
  3989. var Viewport = (function () {
  3990. /**
  3991. * Creates a Viewport object located at (x, y) and sized (width, height).
  3992. */
  3993. function Viewport(x, y, width, height) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.width = width;
  3997. this.height = height;
  3998. }
  3999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4000. if (renderWidthOrEngine._gl) {
  4001. var engine = renderWidthOrEngine;
  4002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4003. }
  4004. var renderWidth = renderWidthOrEngine;
  4005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4006. };
  4007. /**
  4008. * Returns a new Viewport copied from the current one.
  4009. */
  4010. Viewport.prototype.clone = function () {
  4011. return new Viewport(this.x, this.y, this.width, this.height);
  4012. };
  4013. return Viewport;
  4014. }());
  4015. BABYLON.Viewport = Viewport;
  4016. var Frustum = (function () {
  4017. function Frustum() {
  4018. }
  4019. /**
  4020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4021. */
  4022. Frustum.GetPlanes = function (transform) {
  4023. var frustumPlanes = [];
  4024. for (var index = 0; index < 6; index++) {
  4025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4026. }
  4027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4028. return frustumPlanes;
  4029. };
  4030. /**
  4031. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4032. */
  4033. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4034. // Near
  4035. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4036. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4037. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4038. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4039. frustumPlanes[0].normalize();
  4040. // Far
  4041. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4042. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4043. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4044. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4045. frustumPlanes[1].normalize();
  4046. // Left
  4047. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4048. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4049. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4050. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4051. frustumPlanes[2].normalize();
  4052. // Right
  4053. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4054. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4055. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4056. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4057. frustumPlanes[3].normalize();
  4058. // Top
  4059. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4060. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4061. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4062. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4063. frustumPlanes[4].normalize();
  4064. // Bottom
  4065. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4066. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4067. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4068. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4069. frustumPlanes[5].normalize();
  4070. };
  4071. return Frustum;
  4072. }());
  4073. BABYLON.Frustum = Frustum;
  4074. var Space;
  4075. (function (Space) {
  4076. Space[Space["LOCAL"] = 0] = "LOCAL";
  4077. Space[Space["WORLD"] = 1] = "WORLD";
  4078. Space[Space["BONE"] = 2] = "BONE";
  4079. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4080. var Axis = (function () {
  4081. function Axis() {
  4082. }
  4083. return Axis;
  4084. }());
  4085. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4086. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4087. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4088. BABYLON.Axis = Axis;
  4089. ;
  4090. var BezierCurve = (function () {
  4091. function BezierCurve() {
  4092. }
  4093. /**
  4094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4095. */
  4096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4097. // Extract X (which is equal to time here)
  4098. var f0 = 1 - 3 * x2 + 3 * x1;
  4099. var f1 = 3 * x2 - 6 * x1;
  4100. var f2 = 3 * x1;
  4101. var refinedT = t;
  4102. for (var i = 0; i < 5; i++) {
  4103. var refinedT2 = refinedT * refinedT;
  4104. var refinedT3 = refinedT2 * refinedT;
  4105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4107. refinedT -= (x - t) * slope;
  4108. refinedT = Math.min(1, Math.max(0, refinedT));
  4109. }
  4110. // Resolve cubic bezier for the given x
  4111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4113. Math.pow(refinedT, 3);
  4114. };
  4115. return BezierCurve;
  4116. }());
  4117. BABYLON.BezierCurve = BezierCurve;
  4118. var Orientation;
  4119. (function (Orientation) {
  4120. Orientation[Orientation["CW"] = 0] = "CW";
  4121. Orientation[Orientation["CCW"] = 1] = "CCW";
  4122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4123. var Angle = (function () {
  4124. /**
  4125. * Creates an Angle object of "radians" radians (float).
  4126. */
  4127. function Angle(radians) {
  4128. var _this = this;
  4129. /**
  4130. * Returns the Angle value in degrees (float).
  4131. */
  4132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4133. /**
  4134. * Returns the Angle value in radians (float).
  4135. */
  4136. this.radians = function () { return _this._radians; };
  4137. this._radians = radians;
  4138. if (this._radians < 0.0)
  4139. this._radians += (2.0 * Math.PI);
  4140. }
  4141. /**
  4142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4143. */
  4144. Angle.BetweenTwoPoints = function (a, b) {
  4145. var delta = b.subtract(a);
  4146. var theta = Math.atan2(delta.y, delta.x);
  4147. return new Angle(theta);
  4148. };
  4149. /**
  4150. * Returns a new Angle object from the passed float in radians.
  4151. */
  4152. Angle.FromRadians = function (radians) {
  4153. return new Angle(radians);
  4154. };
  4155. /**
  4156. * Returns a new Angle object from the passed float in degrees.
  4157. */
  4158. Angle.FromDegrees = function (degrees) {
  4159. return new Angle(degrees * Math.PI / 180.0);
  4160. };
  4161. return Angle;
  4162. }());
  4163. BABYLON.Angle = Angle;
  4164. var Arc2 = (function () {
  4165. /**
  4166. * Creates an Arc object from the three passed points : start, middle and end.
  4167. */
  4168. function Arc2(startPoint, midPoint, endPoint) {
  4169. this.startPoint = startPoint;
  4170. this.midPoint = midPoint;
  4171. this.endPoint = endPoint;
  4172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4176. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4179. var a1 = this.startAngle.degrees();
  4180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4182. // angles correction
  4183. if (a2 - a1 > +180.0)
  4184. a2 -= 360.0;
  4185. if (a2 - a1 < -180.0)
  4186. a2 += 360.0;
  4187. if (a3 - a2 > +180.0)
  4188. a3 -= 360.0;
  4189. if (a3 - a2 < -180.0)
  4190. a3 += 360.0;
  4191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4193. }
  4194. return Arc2;
  4195. }());
  4196. BABYLON.Arc2 = Arc2;
  4197. var Path2 = (function () {
  4198. /**
  4199. * Creates a Path2 object from the starting 2D coordinates x and y.
  4200. */
  4201. function Path2(x, y) {
  4202. this._points = new Array();
  4203. this._length = 0.0;
  4204. this.closed = false;
  4205. this._points.push(new Vector2(x, y));
  4206. }
  4207. /**
  4208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4209. * Returns the updated Path2.
  4210. */
  4211. Path2.prototype.addLineTo = function (x, y) {
  4212. if (closed) {
  4213. //Tools.Error("cannot add lines to closed paths");
  4214. return this;
  4215. }
  4216. var newPoint = new Vector2(x, y);
  4217. var previousPoint = this._points[this._points.length - 1];
  4218. this._points.push(newPoint);
  4219. this._length += newPoint.subtract(previousPoint).length();
  4220. return this;
  4221. };
  4222. /**
  4223. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4224. * Returns the updated Path2.
  4225. */
  4226. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4227. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4228. if (closed) {
  4229. //Tools.Error("cannot add arcs to closed paths");
  4230. return this;
  4231. }
  4232. var startPoint = this._points[this._points.length - 1];
  4233. var midPoint = new Vector2(midX, midY);
  4234. var endPoint = new Vector2(endX, endY);
  4235. var arc = new Arc2(startPoint, midPoint, endPoint);
  4236. var increment = arc.angle.radians() / numberOfSegments;
  4237. if (arc.orientation === Orientation.CW)
  4238. increment *= -1;
  4239. var currentAngle = arc.startAngle.radians() + increment;
  4240. for (var i = 0; i < numberOfSegments; i++) {
  4241. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4242. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4243. this.addLineTo(x, y);
  4244. currentAngle += increment;
  4245. }
  4246. return this;
  4247. };
  4248. /**
  4249. * Closes the Path2.
  4250. * Returns the Path2.
  4251. */
  4252. Path2.prototype.close = function () {
  4253. this.closed = true;
  4254. return this;
  4255. };
  4256. /**
  4257. * Returns the Path2 total length (float).
  4258. */
  4259. Path2.prototype.length = function () {
  4260. var result = this._length;
  4261. if (!this.closed) {
  4262. var lastPoint = this._points[this._points.length - 1];
  4263. var firstPoint = this._points[0];
  4264. result += (firstPoint.subtract(lastPoint).length());
  4265. }
  4266. return result;
  4267. };
  4268. /**
  4269. * Returns the Path2 internal array of points.
  4270. */
  4271. Path2.prototype.getPoints = function () {
  4272. return this._points;
  4273. };
  4274. /**
  4275. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4276. */
  4277. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4278. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4279. //Tools.Error("normalized length position should be between 0 and 1.");
  4280. return Vector2.Zero();
  4281. }
  4282. var lengthPosition = normalizedLengthPosition * this.length();
  4283. var previousOffset = 0;
  4284. for (var i = 0; i < this._points.length; i++) {
  4285. var j = (i + 1) % this._points.length;
  4286. var a = this._points[i];
  4287. var b = this._points[j];
  4288. var bToA = b.subtract(a);
  4289. var nextOffset = (bToA.length() + previousOffset);
  4290. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4291. var dir = bToA.normalize();
  4292. var localOffset = lengthPosition - previousOffset;
  4293. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4294. }
  4295. previousOffset = nextOffset;
  4296. }
  4297. //Tools.Error("internal error");
  4298. return Vector2.Zero();
  4299. };
  4300. /**
  4301. * Returns a new Path2 starting at the coordinates (x, y).
  4302. */
  4303. Path2.StartingAt = function (x, y) {
  4304. return new Path2(x, y);
  4305. };
  4306. return Path2;
  4307. }());
  4308. BABYLON.Path2 = Path2;
  4309. var Path3D = (function () {
  4310. /**
  4311. * new Path3D(path, normal, raw)
  4312. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4313. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4314. * path : an array of Vector3, the curve axis of the Path3D
  4315. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4316. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4317. */
  4318. function Path3D(path, firstNormal, raw) {
  4319. this.path = path;
  4320. this._curve = new Array();
  4321. this._distances = new Array();
  4322. this._tangents = new Array();
  4323. this._normals = new Array();
  4324. this._binormals = new Array();
  4325. for (var p = 0; p < path.length; p++) {
  4326. this._curve[p] = path[p].clone(); // hard copy
  4327. }
  4328. this._raw = raw || false;
  4329. this._compute(firstNormal);
  4330. }
  4331. /**
  4332. * Returns the Path3D array of successive Vector3 designing its curve.
  4333. */
  4334. Path3D.prototype.getCurve = function () {
  4335. return this._curve;
  4336. };
  4337. /**
  4338. * Returns an array populated with tangent vectors on each Path3D curve point.
  4339. */
  4340. Path3D.prototype.getTangents = function () {
  4341. return this._tangents;
  4342. };
  4343. /**
  4344. * Returns an array populated with normal vectors on each Path3D curve point.
  4345. */
  4346. Path3D.prototype.getNormals = function () {
  4347. return this._normals;
  4348. };
  4349. /**
  4350. * Returns an array populated with binormal vectors on each Path3D curve point.
  4351. */
  4352. Path3D.prototype.getBinormals = function () {
  4353. return this._binormals;
  4354. };
  4355. /**
  4356. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4357. */
  4358. Path3D.prototype.getDistances = function () {
  4359. return this._distances;
  4360. };
  4361. /**
  4362. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4363. * Returns the same object updated.
  4364. */
  4365. Path3D.prototype.update = function (path, firstNormal) {
  4366. for (var p = 0; p < path.length; p++) {
  4367. this._curve[p].x = path[p].x;
  4368. this._curve[p].y = path[p].y;
  4369. this._curve[p].z = path[p].z;
  4370. }
  4371. this._compute(firstNormal);
  4372. return this;
  4373. };
  4374. // private function compute() : computes tangents, normals and binormals
  4375. Path3D.prototype._compute = function (firstNormal) {
  4376. var l = this._curve.length;
  4377. // first and last tangents
  4378. this._tangents[0] = this._getFirstNonNullVector(0);
  4379. if (!this._raw) {
  4380. this._tangents[0].normalize();
  4381. }
  4382. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4383. if (!this._raw) {
  4384. this._tangents[l - 1].normalize();
  4385. }
  4386. // normals and binormals at first point : arbitrary vector with _normalVector()
  4387. var tg0 = this._tangents[0];
  4388. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4389. this._normals[0] = pp0;
  4390. if (!this._raw) {
  4391. this._normals[0].normalize();
  4392. }
  4393. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4394. if (!this._raw) {
  4395. this._binormals[0].normalize();
  4396. }
  4397. this._distances[0] = 0.0;
  4398. // normals and binormals : next points
  4399. var prev; // previous vector (segment)
  4400. var cur; // current vector (segment)
  4401. var curTang; // current tangent
  4402. // previous normal
  4403. var prevBinor; // previous binormal
  4404. for (var i = 1; i < l; i++) {
  4405. // tangents
  4406. prev = this._getLastNonNullVector(i);
  4407. if (i < l - 1) {
  4408. cur = this._getFirstNonNullVector(i);
  4409. this._tangents[i] = prev.add(cur);
  4410. this._tangents[i].normalize();
  4411. }
  4412. this._distances[i] = this._distances[i - 1] + prev.length();
  4413. // normals and binormals
  4414. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4415. curTang = this._tangents[i];
  4416. prevBinor = this._binormals[i - 1];
  4417. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4418. if (!this._raw) {
  4419. this._normals[i].normalize();
  4420. }
  4421. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4422. if (!this._raw) {
  4423. this._binormals[i].normalize();
  4424. }
  4425. }
  4426. };
  4427. // private function getFirstNonNullVector(index)
  4428. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4429. Path3D.prototype._getFirstNonNullVector = function (index) {
  4430. var i = 1;
  4431. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4432. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4433. i++;
  4434. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4435. }
  4436. return nNVector;
  4437. };
  4438. // private function getLastNonNullVector(index)
  4439. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4440. Path3D.prototype._getLastNonNullVector = function (index) {
  4441. var i = 1;
  4442. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4443. while (nLVector.length() === 0 && index > i + 1) {
  4444. i++;
  4445. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4446. }
  4447. return nLVector;
  4448. };
  4449. // private function normalVector(v0, vt, va) :
  4450. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4451. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4452. Path3D.prototype._normalVector = function (v0, vt, va) {
  4453. var normal0;
  4454. var tgl = vt.length();
  4455. if (tgl === 0.0) {
  4456. tgl = 1.0;
  4457. }
  4458. if (va === undefined || va === null) {
  4459. var point;
  4460. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4461. point = new Vector3(0.0, -1.0, 0.0);
  4462. }
  4463. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4464. point = new Vector3(1.0, 0.0, 0.0);
  4465. }
  4466. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4467. point = new Vector3(0.0, 0.0, 1.0);
  4468. }
  4469. normal0 = Vector3.Cross(vt, point);
  4470. }
  4471. else {
  4472. normal0 = Vector3.Cross(vt, va);
  4473. Vector3.CrossToRef(normal0, vt, normal0);
  4474. }
  4475. normal0.normalize();
  4476. return normal0;
  4477. };
  4478. return Path3D;
  4479. }());
  4480. BABYLON.Path3D = Path3D;
  4481. var Curve3 = (function () {
  4482. /**
  4483. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4484. * A Curve3 is designed from a series of successive Vector3.
  4485. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4486. */
  4487. function Curve3(points) {
  4488. this._length = 0.0;
  4489. this._points = points;
  4490. this._length = this._computeLength(points);
  4491. }
  4492. /**
  4493. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4494. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4495. * @param v1 (Vector3) the control point
  4496. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4500. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4501. var bez = new Array();
  4502. var equation = function (t, val0, val1, val2) {
  4503. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4504. return res;
  4505. };
  4506. for (var i = 0; i <= nbPoints; i++) {
  4507. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4508. }
  4509. return new Curve3(bez);
  4510. };
  4511. /**
  4512. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4513. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4514. * @param v1 (Vector3) the first control point
  4515. * @param v2 (Vector3) the second control point
  4516. * @param v3 (Vector3) the end point of the Cubic Bezier
  4517. * @param nbPoints (integer) the wanted number of points in the curve
  4518. */
  4519. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4520. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4521. var bez = new Array();
  4522. var equation = function (t, val0, val1, val2, val3) {
  4523. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4524. return res;
  4525. };
  4526. for (var i = 0; i <= nbPoints; i++) {
  4527. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4528. }
  4529. return new Curve3(bez);
  4530. };
  4531. /**
  4532. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4533. * @param p1 (Vector3) the origin point of the Hermite Spline
  4534. * @param t1 (Vector3) the tangent vector at the origin point
  4535. * @param p2 (Vector3) the end point of the Hermite Spline
  4536. * @param t2 (Vector3) the tangent vector at the end point
  4537. * @param nbPoints (integer) the wanted number of points in the curve
  4538. */
  4539. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4540. var hermite = new Array();
  4541. var step = 1.0 / nbPoints;
  4542. for (var i = 0; i <= nbPoints; i++) {
  4543. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4544. }
  4545. return new Curve3(hermite);
  4546. };
  4547. /**
  4548. * Returns a Curve3 object along a CatmullRom Spline curve :
  4549. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4550. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4551. */
  4552. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4553. var totalPoints = new Array();
  4554. totalPoints.push(points[0].clone());
  4555. Array.prototype.push.apply(totalPoints, points);
  4556. totalPoints.push(points[points.length - 1].clone());
  4557. var catmullRom = new Array();
  4558. var step = 1.0 / nbPoints;
  4559. for (var i = 0; i < totalPoints.length - 3; i++) {
  4560. var amount = 0.0;
  4561. for (var c = 0; c < nbPoints; c++) {
  4562. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4563. amount += step;
  4564. }
  4565. }
  4566. i--;
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. return new Curve3(catmullRom);
  4569. };
  4570. /**
  4571. * Returns the Curve3 stored array of successive Vector3
  4572. */
  4573. Curve3.prototype.getPoints = function () {
  4574. return this._points;
  4575. };
  4576. /**
  4577. * Returns the computed length (float) of the curve.
  4578. */
  4579. Curve3.prototype.length = function () {
  4580. return this._length;
  4581. };
  4582. /**
  4583. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4584. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4585. * curveA and curveB keep unchanged.
  4586. */
  4587. Curve3.prototype.continue = function (curve) {
  4588. var lastPoint = this._points[this._points.length - 1];
  4589. var continuedPoints = this._points.slice();
  4590. var curvePoints = curve.getPoints();
  4591. for (var i = 1; i < curvePoints.length; i++) {
  4592. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4593. }
  4594. var continuedCurve = new Curve3(continuedPoints);
  4595. return continuedCurve;
  4596. };
  4597. Curve3.prototype._computeLength = function (path) {
  4598. var l = 0;
  4599. for (var i = 1; i < path.length; i++) {
  4600. l += (path[i].subtract(path[i - 1])).length();
  4601. }
  4602. return l;
  4603. };
  4604. return Curve3;
  4605. }());
  4606. BABYLON.Curve3 = Curve3;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. return Tmp;
  4644. }());
  4645. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4646. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4647. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4648. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4649. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4650. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4651. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero(),
  4653. Matrix.Zero(), Matrix.Zero(),
  4654. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. return MathTmp;
  4661. }());
  4662. MathTmp.Vector3 = [Vector3.Zero()];
  4663. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4664. MathTmp.Quaternion = [Quaternion.Zero()];
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. var BABYLON;
  4668. (function (BABYLON) {
  4669. var Scalar = (function () {
  4670. function Scalar() {
  4671. }
  4672. /**
  4673. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4674. */
  4675. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4676. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4677. var num = a - b;
  4678. return -epsilon <= num && num <= epsilon;
  4679. };
  4680. /**
  4681. * Returns a string : the upper case translation of the number i to hexadecimal.
  4682. */
  4683. Scalar.ToHex = function (i) {
  4684. var str = i.toString(16);
  4685. if (i <= 15) {
  4686. return ("0" + str).toUpperCase();
  4687. }
  4688. return str.toUpperCase();
  4689. };
  4690. /**
  4691. * Returns -1 if value is negative and +1 is value is positive.
  4692. * Returns the value itself if it's equal to zero.
  4693. */
  4694. Scalar.Sign = function (value) {
  4695. value = +value; // convert to a number
  4696. if (value === 0 || isNaN(value))
  4697. return value;
  4698. return value > 0 ? 1 : -1;
  4699. };
  4700. /**
  4701. * Returns the value itself if it's between min and max.
  4702. * Returns min if the value is lower than min.
  4703. * Returns max if the value is greater than max.
  4704. */
  4705. Scalar.Clamp = function (value, min, max) {
  4706. if (min === void 0) { min = 0; }
  4707. if (max === void 0) { max = 1; }
  4708. return Math.min(max, Math.max(min, value));
  4709. };
  4710. /**
  4711. * Returns the log2 of value.
  4712. */
  4713. Scalar.Log2 = function (value) {
  4714. return Math.log(value) * Math.LOG2E;
  4715. };
  4716. /**
  4717. * Loops the value, so that it is never larger than length and never smaller than 0.
  4718. *
  4719. * This is similar to the modulo operator but it works with floating point numbers.
  4720. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4721. * With t = 5 and length = 2.5, the result would be 0.0.
  4722. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4723. */
  4724. Scalar.Repeat = function (value, length) {
  4725. return value - Math.floor(value / length) * length;
  4726. };
  4727. /**
  4728. * Normalize the value between 0.0 and 1.0 using min and max values
  4729. */
  4730. Scalar.Normalize = function (value, min, max) {
  4731. return (value - min) / (max - min);
  4732. };
  4733. /**
  4734. * Denormalize the value from 0.0 and 1.0 using min and max values
  4735. */
  4736. Scalar.Denormalize = function (normalized, min, max) {
  4737. return (normalized * (max - min) + min);
  4738. };
  4739. /**
  4740. * Calculates the shortest difference between two given angles given in degrees.
  4741. */
  4742. Scalar.DeltaAngle = function (current, target) {
  4743. var num = Scalar.Repeat(target - current, 360.0);
  4744. if (num > 180.0) {
  4745. num -= 360.0;
  4746. }
  4747. return num;
  4748. };
  4749. /**
  4750. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4751. *
  4752. * The returned value will move back and forth between 0 and length
  4753. */
  4754. Scalar.PingPong = function (tx, length) {
  4755. var t = Scalar.Repeat(tx, length * 2.0);
  4756. return length - Math.abs(t - length);
  4757. };
  4758. /**
  4759. * Interpolates between min and max with smoothing at the limits.
  4760. *
  4761. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4762. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4763. */
  4764. Scalar.SmoothStep = function (from, to, tx) {
  4765. var t = Scalar.Clamp(tx);
  4766. t = -2.0 * t * t * t + 3.0 * t * t;
  4767. return to * t + from * (1.0 - t);
  4768. };
  4769. /**
  4770. * Moves a value current towards target.
  4771. *
  4772. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4773. * Negative values of maxDelta pushes the value away from target.
  4774. */
  4775. Scalar.MoveTowards = function (current, target, maxDelta) {
  4776. var result = 0;
  4777. if (Math.abs(target - current) <= maxDelta) {
  4778. result = target;
  4779. }
  4780. else {
  4781. result = current + Scalar.Sign(target - current) * maxDelta;
  4782. }
  4783. return result;
  4784. };
  4785. /**
  4786. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4787. *
  4788. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4789. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4790. */
  4791. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4792. var num = Scalar.DeltaAngle(current, target);
  4793. var result = 0;
  4794. if (-maxDelta < num && num < maxDelta) {
  4795. result = target;
  4796. }
  4797. else {
  4798. target = current + num;
  4799. result = Scalar.MoveTowards(current, target, maxDelta);
  4800. }
  4801. return result;
  4802. };
  4803. /**
  4804. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4805. */
  4806. Scalar.Lerp = function (start, end, amount) {
  4807. return start + ((end - start) * amount);
  4808. };
  4809. /**
  4810. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4811. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4812. */
  4813. Scalar.LerpAngle = function (start, end, amount) {
  4814. var num = Scalar.Repeat(end - start, 360.0);
  4815. if (num > 180.0) {
  4816. num -= 360.0;
  4817. }
  4818. return start + num * Scalar.Clamp(amount);
  4819. };
  4820. /**
  4821. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4822. */
  4823. Scalar.InverseLerp = function (a, b, value) {
  4824. var result = 0;
  4825. if (a != b) {
  4826. result = Scalar.Clamp((value - a) / (b - a));
  4827. }
  4828. else {
  4829. result = 0.0;
  4830. }
  4831. return result;
  4832. };
  4833. /**
  4834. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4835. */
  4836. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4837. var squared = amount * amount;
  4838. var cubed = amount * squared;
  4839. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4840. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4841. var part3 = (cubed - (2.0 * squared)) + amount;
  4842. var part4 = cubed - squared;
  4843. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4844. };
  4845. /**
  4846. * Returns a random float number between and min and max values
  4847. */
  4848. Scalar.RandomRange = function (min, max) {
  4849. if (min === max)
  4850. return min;
  4851. return ((Math.random() * (max - min)) + min);
  4852. };
  4853. /**
  4854. * This function returns percentage of a number in a given range.
  4855. *
  4856. * RangeToPercent(40,20,60) will return 0.5 (50%)
  4857. * RangeToPercent(34,0,100) will return 0.34 (34%)
  4858. */
  4859. Scalar.RangeToPercent = function (number, min, max) {
  4860. return ((number - min) / (max - min));
  4861. };
  4862. /**
  4863. * This function returns number that corresponds to the percentage in a given range.
  4864. *
  4865. * PercentToRange(0.34,0,100) will return 34.
  4866. */
  4867. Scalar.PercentToRange = function (percent, min, max) {
  4868. return ((max - min) * percent + min);
  4869. };
  4870. return Scalar;
  4871. }());
  4872. BABYLON.Scalar = Scalar;
  4873. })(BABYLON || (BABYLON = {}));
  4874. //# sourceMappingURL=babylon.math.scalar.js.map
  4875. //# sourceMappingURL=babylon.mixins.js.map
  4876. var BABYLON;
  4877. (function (BABYLON) {
  4878. var __decoratorInitialStore = {};
  4879. var __mergedStore = {};
  4880. var _copySource = function (creationFunction, source, instanciate) {
  4881. var destination = creationFunction();
  4882. // Tags
  4883. if (BABYLON.Tags) {
  4884. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4885. }
  4886. var classStore = getMergedStore(destination);
  4887. // Properties
  4888. for (var property in classStore) {
  4889. var propertyDescriptor = classStore[property];
  4890. var sourceProperty = source[property];
  4891. var propertyType = propertyDescriptor.type;
  4892. if (sourceProperty !== undefined && sourceProperty !== null) {
  4893. switch (propertyType) {
  4894. case 0: // Value
  4895. case 6:
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1: // Texture
  4899. case 2: // Color3
  4900. case 3: // FresnelParameters
  4901. case 4: // Vector2
  4902. case 5: // Vector3
  4903. case 7:
  4904. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  4905. break;
  4906. }
  4907. }
  4908. }
  4909. return destination;
  4910. };
  4911. function getDirectStore(target) {
  4912. var classKey = target.getClassName();
  4913. if (!__decoratorInitialStore[classKey]) {
  4914. __decoratorInitialStore[classKey] = {};
  4915. }
  4916. return __decoratorInitialStore[classKey];
  4917. }
  4918. /**
  4919. * Return the list of properties flagged as serializable
  4920. * @param target: host object
  4921. */
  4922. function getMergedStore(target) {
  4923. var classKey = target.getClassName();
  4924. if (__mergedStore[classKey]) {
  4925. return __mergedStore[classKey];
  4926. }
  4927. __mergedStore[classKey] = {};
  4928. var store = __mergedStore[classKey];
  4929. var currentTarget = target;
  4930. var currentKey = classKey;
  4931. while (currentKey) {
  4932. var initialStore = __decoratorInitialStore[currentKey];
  4933. for (var property in initialStore) {
  4934. store[property] = initialStore[property];
  4935. }
  4936. var parent_1 = void 0;
  4937. var done = false;
  4938. do {
  4939. parent_1 = Object.getPrototypeOf(currentTarget);
  4940. if (!parent_1.getClassName) {
  4941. done = true;
  4942. break;
  4943. }
  4944. if (parent_1.getClassName() !== currentKey) {
  4945. break;
  4946. }
  4947. currentTarget = parent_1;
  4948. } while (parent_1);
  4949. if (done) {
  4950. break;
  4951. }
  4952. currentKey = parent_1.getClassName();
  4953. currentTarget = parent_1;
  4954. }
  4955. return store;
  4956. }
  4957. function generateSerializableMember(type, sourceName) {
  4958. return function (target, propertyKey) {
  4959. var classStore = getDirectStore(target);
  4960. if (!classStore[propertyKey]) {
  4961. classStore[propertyKey] = { type: type, sourceName: sourceName };
  4962. }
  4963. };
  4964. }
  4965. function generateExpandMember(setCallback, targetKey) {
  4966. return function (target, propertyKey) {
  4967. var key = targetKey || ("_" + propertyKey);
  4968. Object.defineProperty(target, propertyKey, {
  4969. get: function () {
  4970. return this[key];
  4971. },
  4972. set: function (value) {
  4973. if (this[key] === value) {
  4974. return;
  4975. }
  4976. this[key] = value;
  4977. target[setCallback].apply(this);
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. };
  4983. }
  4984. function expandToProperty(callback, targetKey) {
  4985. return generateExpandMember(callback, targetKey);
  4986. }
  4987. BABYLON.expandToProperty = expandToProperty;
  4988. function serialize(sourceName) {
  4989. return generateSerializableMember(0, sourceName); // value member
  4990. }
  4991. BABYLON.serialize = serialize;
  4992. function serializeAsTexture(sourceName) {
  4993. return generateSerializableMember(1, sourceName); // texture member
  4994. }
  4995. BABYLON.serializeAsTexture = serializeAsTexture;
  4996. function serializeAsColor3(sourceName) {
  4997. return generateSerializableMember(2, sourceName); // color3 member
  4998. }
  4999. BABYLON.serializeAsColor3 = serializeAsColor3;
  5000. function serializeAsFresnelParameters(sourceName) {
  5001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5002. }
  5003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5004. function serializeAsVector2(sourceName) {
  5005. return generateSerializableMember(4, sourceName); // vector2 member
  5006. }
  5007. BABYLON.serializeAsVector2 = serializeAsVector2;
  5008. function serializeAsVector3(sourceName) {
  5009. return generateSerializableMember(5, sourceName); // vector3 member
  5010. }
  5011. BABYLON.serializeAsVector3 = serializeAsVector3;
  5012. function serializeAsMeshReference(sourceName) {
  5013. return generateSerializableMember(6, sourceName); // mesh reference member
  5014. }
  5015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5016. function serializeAsColorCurves(sourceName) {
  5017. return generateSerializableMember(7, sourceName); // color curves
  5018. }
  5019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5020. function serializeAsColor4(sourceName) {
  5021. return generateSerializableMember(8, sourceName); // color 4
  5022. }
  5023. BABYLON.serializeAsColor4 = serializeAsColor4;
  5024. function serializeAsImageProcessingConfiguration(sourceName) {
  5025. return generateSerializableMember(9, sourceName); // image processing
  5026. }
  5027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5028. var SerializationHelper = (function () {
  5029. function SerializationHelper() {
  5030. }
  5031. SerializationHelper.Serialize = function (entity, serializationObject) {
  5032. if (!serializationObject) {
  5033. serializationObject = {};
  5034. }
  5035. // Tags
  5036. if (BABYLON.Tags) {
  5037. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5038. }
  5039. var serializedProperties = getMergedStore(entity);
  5040. // Properties
  5041. for (var property in serializedProperties) {
  5042. var propertyDescriptor = serializedProperties[property];
  5043. var targetPropertyName = propertyDescriptor.sourceName || property;
  5044. var propertyType = propertyDescriptor.type;
  5045. var sourceProperty = entity[property];
  5046. if (sourceProperty !== undefined && sourceProperty !== null) {
  5047. switch (propertyType) {
  5048. case 0:
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:
  5076. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. return serializationObject;
  5082. };
  5083. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5084. var destination = creationFunction();
  5085. // Tags
  5086. if (BABYLON.Tags) {
  5087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5088. }
  5089. var classStore = getMergedStore(destination);
  5090. // Properties
  5091. for (var property in classStore) {
  5092. var propertyDescriptor = classStore[property];
  5093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5094. var propertyType = propertyDescriptor.type;
  5095. if (sourceProperty !== undefined && sourceProperty !== null) {
  5096. switch (propertyType) {
  5097. case 0:
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:
  5125. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. return destination;
  5131. };
  5132. SerializationHelper.Clone = function (creationFunction, source) {
  5133. return _copySource(creationFunction, source, false);
  5134. };
  5135. SerializationHelper.Instanciate = function (creationFunction, source) {
  5136. return _copySource(creationFunction, source, true);
  5137. };
  5138. return SerializationHelper;
  5139. }());
  5140. BABYLON.SerializationHelper = SerializationHelper;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.decorators.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. /**
  5146. * A class serves as a medium between the observable and its observers
  5147. */
  5148. var EventState = (function () {
  5149. /**
  5150. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5151. */
  5152. function EventState(mask, skipNextObservers) {
  5153. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5154. this.initalize(mask, skipNextObservers);
  5155. }
  5156. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5157. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5158. this.mask = mask;
  5159. this.skipNextObservers = skipNextObservers;
  5160. return this;
  5161. };
  5162. return EventState;
  5163. }());
  5164. BABYLON.EventState = EventState;
  5165. /**
  5166. * Represent an Observer registered to a given Observable object.
  5167. */
  5168. var Observer = (function () {
  5169. function Observer(callback, mask) {
  5170. this.callback = callback;
  5171. this.mask = mask;
  5172. }
  5173. return Observer;
  5174. }());
  5175. BABYLON.Observer = Observer;
  5176. /**
  5177. * The Observable class is a simple implementation of the Observable pattern.
  5178. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5179. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5180. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5181. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5182. */
  5183. var Observable = (function () {
  5184. function Observable() {
  5185. this._observers = new Array();
  5186. this._eventState = new EventState(0);
  5187. }
  5188. /**
  5189. * Create a new Observer with the specified callback
  5190. * @param callback the callback that will be executed for that Observer
  5191. * @param mask the mask used to filter observers
  5192. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5193. */
  5194. Observable.prototype.add = function (callback, mask, insertFirst) {
  5195. if (mask === void 0) { mask = -1; }
  5196. if (insertFirst === void 0) { insertFirst = false; }
  5197. if (!callback) {
  5198. return null;
  5199. }
  5200. var observer = new Observer(callback, mask);
  5201. if (insertFirst) {
  5202. this._observers.unshift(observer);
  5203. }
  5204. else {
  5205. this._observers.push(observer);
  5206. }
  5207. return observer;
  5208. };
  5209. /**
  5210. * Remove an Observer from the Observable object
  5211. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5212. */
  5213. Observable.prototype.remove = function (observer) {
  5214. var index = this._observers.indexOf(observer);
  5215. if (index !== -1) {
  5216. this._observers.splice(index, 1);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. /**
  5222. * Remove a callback from the Observable object
  5223. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5224. */
  5225. Observable.prototype.removeCallback = function (callback) {
  5226. for (var index = 0; index < this._observers.length; index++) {
  5227. if (this._observers[index].callback === callback) {
  5228. this._observers.splice(index, 1);
  5229. return true;
  5230. }
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Notify all Observers by calling their respective callback with the given data
  5236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5237. * @param eventData
  5238. * @param mask
  5239. */
  5240. Observable.prototype.notifyObservers = function (eventData, mask) {
  5241. if (mask === void 0) { mask = -1; }
  5242. var state = this._eventState;
  5243. state.mask = mask;
  5244. state.skipNextObservers = false;
  5245. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5246. var obs = _a[_i];
  5247. if (obs.mask & mask) {
  5248. obs.callback(eventData, state);
  5249. }
  5250. if (state.skipNextObservers) {
  5251. return false;
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. /**
  5257. * return true is the Observable has at least one Observer registered
  5258. */
  5259. Observable.prototype.hasObservers = function () {
  5260. return this._observers.length > 0;
  5261. };
  5262. /**
  5263. * Clear the list of observers
  5264. */
  5265. Observable.prototype.clear = function () {
  5266. this._observers = new Array();
  5267. };
  5268. /**
  5269. * Clone the current observable
  5270. */
  5271. Observable.prototype.clone = function () {
  5272. var result = new Observable();
  5273. result._observers = this._observers.slice(0);
  5274. return result;
  5275. };
  5276. /**
  5277. * Does this observable handles observer registered with a given mask
  5278. * @param {number} trigger - the mask to be tested
  5279. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5280. **/
  5281. Observable.prototype.hasSpecificMask = function (mask) {
  5282. if (mask === void 0) { mask = -1; }
  5283. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5284. var obs = _a[_i];
  5285. if (obs.mask & mask && obs.mask === mask) {
  5286. return true;
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. return Observable;
  5292. }());
  5293. BABYLON.Observable = Observable;
  5294. })(BABYLON || (BABYLON = {}));
  5295. //# sourceMappingURL=babylon.observable.js.map
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var SmartArray = (function () {
  5299. function SmartArray(capacity) {
  5300. this.length = 0;
  5301. this._duplicateId = 0;
  5302. this.data = new Array(capacity);
  5303. this._id = SmartArray._GlobalId++;
  5304. }
  5305. SmartArray.prototype.push = function (value) {
  5306. this.data[this.length++] = value;
  5307. if (this.length > this.data.length) {
  5308. this.data.length *= 2;
  5309. }
  5310. if (!value.__smartArrayFlags) {
  5311. value.__smartArrayFlags = {};
  5312. }
  5313. value.__smartArrayFlags[this._id] = this._duplicateId;
  5314. };
  5315. SmartArray.prototype.forEach = function (func) {
  5316. for (var index = 0; index < this.length; index++) {
  5317. func(this.data[index]);
  5318. }
  5319. };
  5320. SmartArray.prototype.pushNoDuplicate = function (value) {
  5321. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5322. return false;
  5323. }
  5324. this.push(value);
  5325. return true;
  5326. };
  5327. SmartArray.prototype.sort = function (compareFn) {
  5328. this.data.sort(compareFn);
  5329. };
  5330. SmartArray.prototype.reset = function () {
  5331. this.length = 0;
  5332. this._duplicateId++;
  5333. };
  5334. SmartArray.prototype.dispose = function () {
  5335. this.reset();
  5336. this.data.length = 0;
  5337. };
  5338. SmartArray.prototype.concat = function (array) {
  5339. if (array.length === 0) {
  5340. return;
  5341. }
  5342. if (this.length + array.length > this.data.length) {
  5343. this.data.length = (this.length + array.length) * 2;
  5344. }
  5345. for (var index = 0; index < array.length; index++) {
  5346. this.data[this.length++] = (array.data || array)[index];
  5347. }
  5348. };
  5349. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5350. if (array.length === 0) {
  5351. return;
  5352. }
  5353. if (this.length + array.length > this.data.length) {
  5354. this.data.length = (this.length + array.length) * 2;
  5355. }
  5356. for (var index = 0; index < array.length; index++) {
  5357. var item = (array.data || array)[index];
  5358. this.pushNoDuplicate(item);
  5359. }
  5360. };
  5361. SmartArray.prototype.indexOf = function (value) {
  5362. var position = this.data.indexOf(value);
  5363. if (position >= this.length) {
  5364. return -1;
  5365. }
  5366. return position;
  5367. };
  5368. SmartArray.prototype.contains = function (value) {
  5369. return this.data.indexOf(value) !== -1;
  5370. };
  5371. return SmartArray;
  5372. }());
  5373. // Statics
  5374. SmartArray._GlobalId = 0;
  5375. BABYLON.SmartArray = SmartArray;
  5376. })(BABYLON || (BABYLON = {}));
  5377. //# sourceMappingURL=babylon.smartArray.js.map
  5378. var BABYLON;
  5379. (function (BABYLON) {
  5380. // Screenshots
  5381. var screenshotCanvas;
  5382. var cloneValue = function (source, destinationObject) {
  5383. if (!source)
  5384. return null;
  5385. if (source instanceof BABYLON.Mesh) {
  5386. return null;
  5387. }
  5388. if (source instanceof BABYLON.SubMesh) {
  5389. return source.clone(destinationObject);
  5390. }
  5391. else if (source.clone) {
  5392. return source.clone();
  5393. }
  5394. return null;
  5395. };
  5396. var Tools = (function () {
  5397. function Tools() {
  5398. }
  5399. ;
  5400. /**
  5401. * Interpolates between a and b via alpha
  5402. * @param a The lower value (returned when alpha = 0)
  5403. * @param b The upper value (returned when alpha = 1)
  5404. * @param alpha The interpolation-factor
  5405. * @return The mixed value
  5406. */
  5407. Tools.Mix = function (a, b, alpha) {
  5408. return a * (1 - alpha) + b * alpha;
  5409. };
  5410. Tools.Instantiate = function (className) {
  5411. var arr = className.split(".");
  5412. var fn = (window || this);
  5413. for (var i = 0, len = arr.length; i < len; i++) {
  5414. fn = fn[arr[i]];
  5415. }
  5416. if (typeof fn !== "function") {
  5417. return null;
  5418. }
  5419. return fn;
  5420. };
  5421. Tools.SetImmediate = function (action) {
  5422. if (window.setImmediate) {
  5423. window.setImmediate(action);
  5424. }
  5425. else {
  5426. setTimeout(action, 1);
  5427. }
  5428. };
  5429. Tools.IsExponentOfTwo = function (value) {
  5430. var count = 1;
  5431. do {
  5432. count *= 2;
  5433. } while (count < value);
  5434. return count === value;
  5435. };
  5436. /**
  5437. * Find the next highest power of two.
  5438. * @param x Number to start search from.
  5439. * @return Next highest power of two.
  5440. */
  5441. Tools.CeilingPOT = function (x) {
  5442. x--;
  5443. x |= x >> 1;
  5444. x |= x >> 2;
  5445. x |= x >> 4;
  5446. x |= x >> 8;
  5447. x |= x >> 16;
  5448. x++;
  5449. return x;
  5450. };
  5451. /**
  5452. * Find the next lowest power of two.
  5453. * @param x Number to start search from.
  5454. * @return Next lowest power of two.
  5455. */
  5456. Tools.FloorPOT = function (x) {
  5457. x = x | (x >> 1);
  5458. x = x | (x >> 2);
  5459. x = x | (x >> 4);
  5460. x = x | (x >> 8);
  5461. x = x | (x >> 16);
  5462. return x - (x >> 1);
  5463. };
  5464. /**
  5465. * Find the nearest power of two.
  5466. * @param x Number to start search from.
  5467. * @return Next nearest power of two.
  5468. */
  5469. Tools.NearestPOT = function (x) {
  5470. var c = Tools.CeilingPOT(x);
  5471. var f = Tools.FloorPOT(x);
  5472. return (c - x) > (x - f) ? f : c;
  5473. };
  5474. Tools.GetExponentOfTwo = function (value, max, mode) {
  5475. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5476. var pot;
  5477. switch (mode) {
  5478. case BABYLON.Engine.SCALEMODE_FLOOR:
  5479. pot = Tools.FloorPOT(value);
  5480. break;
  5481. case BABYLON.Engine.SCALEMODE_NEAREST:
  5482. pot = Tools.NearestPOT(value);
  5483. break;
  5484. case BABYLON.Engine.SCALEMODE_CEILING:
  5485. pot = Tools.CeilingPOT(value);
  5486. break;
  5487. }
  5488. return Math.min(pot, max);
  5489. };
  5490. Tools.GetFilename = function (path) {
  5491. var index = path.lastIndexOf("/");
  5492. if (index < 0)
  5493. return path;
  5494. return path.substring(index + 1);
  5495. };
  5496. Tools.GetDOMTextContent = function (element) {
  5497. var result = "";
  5498. var child = element.firstChild;
  5499. while (child) {
  5500. if (child.nodeType === 3) {
  5501. result += child.textContent;
  5502. }
  5503. child = child.nextSibling;
  5504. }
  5505. return result;
  5506. };
  5507. Tools.ToDegrees = function (angle) {
  5508. return angle * 180 / Math.PI;
  5509. };
  5510. Tools.ToRadians = function (angle) {
  5511. return angle * Math.PI / 180;
  5512. };
  5513. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5514. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5515. var output = "";
  5516. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5517. var i = 0;
  5518. var bytes = new Uint8Array(buffer);
  5519. while (i < bytes.length) {
  5520. chr1 = bytes[i++];
  5521. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5522. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5523. enc1 = chr1 >> 2;
  5524. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5525. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5526. enc4 = chr3 & 63;
  5527. if (isNaN(chr2)) {
  5528. enc3 = enc4 = 64;
  5529. }
  5530. else if (isNaN(chr3)) {
  5531. enc4 = 64;
  5532. }
  5533. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5534. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5535. }
  5536. return "data:image/png;base64," + output;
  5537. };
  5538. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5539. if (bias === void 0) { bias = null; }
  5540. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5541. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5542. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5543. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5544. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5545. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5546. }
  5547. if (bias) {
  5548. minimum.x -= minimum.x * bias.x + bias.y;
  5549. minimum.y -= minimum.y * bias.x + bias.y;
  5550. minimum.z -= minimum.z * bias.x + bias.y;
  5551. maximum.x += maximum.x * bias.x + bias.y;
  5552. maximum.y += maximum.y * bias.x + bias.y;
  5553. maximum.z += maximum.z * bias.x + bias.y;
  5554. }
  5555. return {
  5556. minimum: minimum,
  5557. maximum: maximum
  5558. };
  5559. };
  5560. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5561. if (bias === void 0) { bias = null; }
  5562. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5563. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5564. if (!stride) {
  5565. stride = 3;
  5566. }
  5567. for (var index = start; index < start + count; index++) {
  5568. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5569. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5570. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5571. }
  5572. if (bias) {
  5573. minimum.x -= minimum.x * bias.x + bias.y;
  5574. minimum.y -= minimum.y * bias.x + bias.y;
  5575. minimum.z -= minimum.z * bias.x + bias.y;
  5576. maximum.x += maximum.x * bias.x + bias.y;
  5577. maximum.y += maximum.y * bias.x + bias.y;
  5578. maximum.z += maximum.z * bias.x + bias.y;
  5579. }
  5580. return {
  5581. minimum: minimum,
  5582. maximum: maximum
  5583. };
  5584. };
  5585. Tools.Vector2ArrayFeeder = function (array) {
  5586. return function (index) {
  5587. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5588. var length = isFloatArray ? array.length / 2 : array.length;
  5589. if (index >= length) {
  5590. return null;
  5591. }
  5592. if (isFloatArray) {
  5593. var fa = array;
  5594. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5595. }
  5596. var a = array;
  5597. return a[index];
  5598. };
  5599. };
  5600. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5601. if (bias === void 0) { bias = null; }
  5602. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5603. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5604. var i = 0;
  5605. var cur = feeder(i++);
  5606. while (cur) {
  5607. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5608. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5609. cur = feeder(i++);
  5610. }
  5611. if (bias) {
  5612. minimum.x -= minimum.x * bias.x + bias.y;
  5613. minimum.y -= minimum.y * bias.x + bias.y;
  5614. maximum.x += maximum.x * bias.x + bias.y;
  5615. maximum.y += maximum.y * bias.x + bias.y;
  5616. }
  5617. return {
  5618. minimum: minimum,
  5619. maximum: maximum
  5620. };
  5621. };
  5622. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5623. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5624. return undefined;
  5625. return Array.isArray(obj) ? obj : [obj];
  5626. };
  5627. // Misc.
  5628. Tools.GetPointerPrefix = function () {
  5629. var eventPrefix = "pointer";
  5630. // Check if pointer events are supported
  5631. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5632. eventPrefix = "mouse";
  5633. }
  5634. return eventPrefix;
  5635. };
  5636. /**
  5637. * @param func - the function to be called
  5638. * @param requester - the object that will request the next frame. Falls back to window.
  5639. */
  5640. Tools.QueueNewFrame = function (func, requester) {
  5641. if (requester === void 0) { requester = window; }
  5642. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5643. /*if(requester.isPresenting) {
  5644. return;
  5645. } else*/ if (requester.requestAnimationFrame)
  5646. requester.requestAnimationFrame(func);
  5647. else if (requester.msRequestAnimationFrame)
  5648. requester.msRequestAnimationFrame(func);
  5649. else if (requester.webkitRequestAnimationFrame)
  5650. requester.webkitRequestAnimationFrame(func);
  5651. else if (requester.mozRequestAnimationFrame)
  5652. requester.mozRequestAnimationFrame(func);
  5653. else if (requester.oRequestAnimationFrame)
  5654. requester.oRequestAnimationFrame(func);
  5655. else {
  5656. window.setTimeout(func, 16);
  5657. }
  5658. };
  5659. Tools.RequestFullscreen = function (element) {
  5660. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5661. if (!requestFunction)
  5662. return;
  5663. requestFunction.call(element);
  5664. };
  5665. Tools.ExitFullscreen = function () {
  5666. if (document.exitFullscreen) {
  5667. document.exitFullscreen();
  5668. }
  5669. else if (document.mozCancelFullScreen) {
  5670. document.mozCancelFullScreen();
  5671. }
  5672. else if (document.webkitCancelFullScreen) {
  5673. document.webkitCancelFullScreen();
  5674. }
  5675. else if (document.msCancelFullScreen) {
  5676. document.msCancelFullScreen();
  5677. }
  5678. };
  5679. Tools.SetCorsBehavior = function (url, img) {
  5680. if (Tools.CorsBehavior) {
  5681. switch (typeof (Tools.CorsBehavior)) {
  5682. case "function":
  5683. var result = Tools.CorsBehavior(url);
  5684. if (result) {
  5685. img.crossOrigin = result;
  5686. }
  5687. break;
  5688. case "string":
  5689. default:
  5690. img.crossOrigin = Tools.CorsBehavior;
  5691. break;
  5692. }
  5693. }
  5694. };
  5695. // External files
  5696. Tools.CleanUrl = function (url) {
  5697. url = url.replace(/#/mg, "%23");
  5698. return url;
  5699. };
  5700. Tools.LoadImage = function (url, onload, onerror, database) {
  5701. if (url instanceof ArrayBuffer) {
  5702. url = Tools.EncodeArrayBufferTobase64(url);
  5703. }
  5704. url = Tools.CleanUrl(url);
  5705. var img = new Image();
  5706. if (url.substr(0, 5) !== "data:") {
  5707. Tools.SetCorsBehavior(url, img);
  5708. }
  5709. img.onload = function () {
  5710. onload(img);
  5711. };
  5712. img.onerror = function (err) {
  5713. Tools.Error("Error while trying to load image: " + url);
  5714. if (Tools.UseFallbackTexture) {
  5715. img.src = Tools.fallbackTexture;
  5716. onload(img);
  5717. }
  5718. else {
  5719. onerror();
  5720. }
  5721. };
  5722. var noIndexedDB = function () {
  5723. img.src = url;
  5724. };
  5725. var loadFromIndexedDB = function () {
  5726. database.loadImageFromDB(url, img);
  5727. };
  5728. //ANY database to do!
  5729. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5730. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5731. }
  5732. else {
  5733. if (url.indexOf("file:") !== 0) {
  5734. noIndexedDB();
  5735. }
  5736. else {
  5737. var textureName = url.substring(5).toLowerCase();
  5738. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5739. try {
  5740. var blobURL;
  5741. try {
  5742. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5743. }
  5744. catch (ex) {
  5745. // Chrome doesn't support oneTimeOnly parameter
  5746. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5747. }
  5748. img.src = blobURL;
  5749. }
  5750. catch (e) {
  5751. img.src = null;
  5752. }
  5753. }
  5754. else {
  5755. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5756. img.src = Tools.fallbackTexture;
  5757. }
  5758. }
  5759. }
  5760. return img;
  5761. };
  5762. //ANY
  5763. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5764. url = Tools.CleanUrl(url);
  5765. var noIndexedDB = function () {
  5766. var request = new XMLHttpRequest();
  5767. var loadUrl = Tools.BaseUrl + url;
  5768. request.open('GET', loadUrl, true);
  5769. if (useArrayBuffer) {
  5770. request.responseType = "arraybuffer";
  5771. }
  5772. request.onprogress = progressCallBack;
  5773. request.onreadystatechange = function () {
  5774. // In case of undefined state in some browsers.
  5775. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5776. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5777. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5778. callback(!useArrayBuffer ? request.responseText : request.response);
  5779. }
  5780. else {
  5781. if (onError) {
  5782. onError(request);
  5783. }
  5784. else {
  5785. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5786. }
  5787. }
  5788. }
  5789. };
  5790. request.send(null);
  5791. };
  5792. var loadFromIndexedDB = function () {
  5793. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5794. };
  5795. if (url.indexOf("file:") !== -1) {
  5796. var fileName = url.substring(5).toLowerCase();
  5797. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5798. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5799. }
  5800. else {
  5801. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5802. }
  5803. }
  5804. else {
  5805. // Caching all files
  5806. if (database && database.enableSceneOffline) {
  5807. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5808. }
  5809. else {
  5810. noIndexedDB();
  5811. }
  5812. }
  5813. };
  5814. /**
  5815. * Load a script (identified by an url). When the url returns, the
  5816. * content of this file is added into a new script element, attached to the DOM (body element)
  5817. */
  5818. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5819. var head = document.getElementsByTagName('head')[0];
  5820. var script = document.createElement('script');
  5821. script.type = 'text/javascript';
  5822. script.src = scriptUrl;
  5823. var self = this;
  5824. script.onload = function () {
  5825. if (onSuccess) {
  5826. onSuccess();
  5827. }
  5828. };
  5829. script.onerror = function () {
  5830. if (onError) {
  5831. onError();
  5832. }
  5833. };
  5834. head.appendChild(script);
  5835. };
  5836. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5837. var reader = new FileReader();
  5838. reader.onload = function (e) {
  5839. //target doesn't have result from ts 1.3
  5840. callback(e.target['result']);
  5841. };
  5842. reader.onprogress = progressCallback;
  5843. reader.readAsDataURL(fileToLoad);
  5844. };
  5845. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5846. var reader = new FileReader();
  5847. reader.onerror = function (e) {
  5848. Tools.Log("Error while reading file: " + fileToLoad.name);
  5849. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5850. };
  5851. reader.onload = function (e) {
  5852. //target doesn't have result from ts 1.3
  5853. callback(e.target['result']);
  5854. };
  5855. reader.onprogress = progressCallBack;
  5856. if (!useArrayBuffer) {
  5857. // Asynchronous read
  5858. reader.readAsText(fileToLoad);
  5859. }
  5860. else {
  5861. reader.readAsArrayBuffer(fileToLoad);
  5862. }
  5863. };
  5864. //returns a downloadable url to a file content.
  5865. Tools.FileAsURL = function (content) {
  5866. var fileBlob = new Blob([content]);
  5867. var url = window.URL || window.webkitURL;
  5868. var link = url.createObjectURL(fileBlob);
  5869. return link;
  5870. };
  5871. // Misc.
  5872. Tools.Format = function (value, decimals) {
  5873. if (decimals === void 0) { decimals = 2; }
  5874. return value.toFixed(decimals);
  5875. };
  5876. Tools.CheckExtends = function (v, min, max) {
  5877. if (v.x < min.x)
  5878. min.x = v.x;
  5879. if (v.y < min.y)
  5880. min.y = v.y;
  5881. if (v.z < min.z)
  5882. min.z = v.z;
  5883. if (v.x > max.x)
  5884. max.x = v.x;
  5885. if (v.y > max.y)
  5886. max.y = v.y;
  5887. if (v.z > max.z)
  5888. max.z = v.z;
  5889. };
  5890. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5891. for (var prop in source) {
  5892. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5893. continue;
  5894. }
  5895. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5896. continue;
  5897. }
  5898. var sourceValue = source[prop];
  5899. var typeOfSourceValue = typeof sourceValue;
  5900. if (typeOfSourceValue === "function") {
  5901. continue;
  5902. }
  5903. if (typeOfSourceValue === "object") {
  5904. if (sourceValue instanceof Array) {
  5905. destination[prop] = [];
  5906. if (sourceValue.length > 0) {
  5907. if (typeof sourceValue[0] == "object") {
  5908. for (var index = 0; index < sourceValue.length; index++) {
  5909. var clonedValue = cloneValue(sourceValue[index], destination);
  5910. if (destination[prop].indexOf(clonedValue) === -1) {
  5911. destination[prop].push(clonedValue);
  5912. }
  5913. }
  5914. }
  5915. else {
  5916. destination[prop] = sourceValue.slice(0);
  5917. }
  5918. }
  5919. }
  5920. else {
  5921. destination[prop] = cloneValue(sourceValue, destination);
  5922. }
  5923. }
  5924. else {
  5925. destination[prop] = sourceValue;
  5926. }
  5927. }
  5928. };
  5929. Tools.IsEmpty = function (obj) {
  5930. for (var i in obj) {
  5931. return false;
  5932. }
  5933. return true;
  5934. };
  5935. Tools.RegisterTopRootEvents = function (events) {
  5936. for (var index = 0; index < events.length; index++) {
  5937. var event = events[index];
  5938. window.addEventListener(event.name, event.handler, false);
  5939. try {
  5940. if (window.parent) {
  5941. window.parent.addEventListener(event.name, event.handler, false);
  5942. }
  5943. }
  5944. catch (e) {
  5945. // Silently fails...
  5946. }
  5947. }
  5948. };
  5949. Tools.UnregisterTopRootEvents = function (events) {
  5950. for (var index = 0; index < events.length; index++) {
  5951. var event = events[index];
  5952. window.removeEventListener(event.name, event.handler);
  5953. try {
  5954. if (window.parent) {
  5955. window.parent.removeEventListener(event.name, event.handler);
  5956. }
  5957. }
  5958. catch (e) {
  5959. // Silently fails...
  5960. }
  5961. }
  5962. };
  5963. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5964. if (mimeType === void 0) { mimeType = "image/png"; }
  5965. // Read the contents of the framebuffer
  5966. var numberOfChannelsByLine = width * 4;
  5967. var halfHeight = height / 2;
  5968. //Reading datas from WebGL
  5969. var data = engine.readPixels(0, 0, width, height);
  5970. //To flip image on Y axis.
  5971. for (var i = 0; i < halfHeight; i++) {
  5972. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5973. var currentCell = j + i * numberOfChannelsByLine;
  5974. var targetLine = height - i - 1;
  5975. var targetCell = j + targetLine * numberOfChannelsByLine;
  5976. var temp = data[currentCell];
  5977. data[currentCell] = data[targetCell];
  5978. data[targetCell] = temp;
  5979. }
  5980. }
  5981. // Create a 2D canvas to store the result
  5982. if (!screenshotCanvas) {
  5983. screenshotCanvas = document.createElement('canvas');
  5984. }
  5985. screenshotCanvas.width = width;
  5986. screenshotCanvas.height = height;
  5987. var context = screenshotCanvas.getContext('2d');
  5988. // Copy the pixels to a 2D canvas
  5989. var imageData = context.createImageData(width, height);
  5990. var castData = (imageData.data);
  5991. castData.set(data);
  5992. context.putImageData(imageData, 0, 0);
  5993. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5994. };
  5995. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5996. if (mimeType === void 0) { mimeType = "image/png"; }
  5997. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5998. if (successCallback) {
  5999. successCallback(base64Image);
  6000. }
  6001. else {
  6002. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6003. if (("download" in document.createElement("a"))) {
  6004. var a = window.document.createElement("a");
  6005. a.href = base64Image;
  6006. var date = new Date();
  6007. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6008. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6009. window.document.body.appendChild(a);
  6010. a.addEventListener("click", function () {
  6011. a.parentElement.removeChild(a);
  6012. });
  6013. a.click();
  6014. //Or opening a new tab with the image if it is not possible to automatically start download.
  6015. }
  6016. else {
  6017. var newWindow = window.open("");
  6018. var img = newWindow.document.createElement("img");
  6019. img.src = base64Image;
  6020. newWindow.document.body.appendChild(img);
  6021. }
  6022. }
  6023. };
  6024. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6025. if (mimeType === void 0) { mimeType = "image/png"; }
  6026. var width;
  6027. var height;
  6028. // If a precision value is specified
  6029. if (size.precision) {
  6030. width = Math.round(engine.getRenderWidth() * size.precision);
  6031. height = Math.round(width / engine.getAspectRatio(camera));
  6032. }
  6033. else if (size.width && size.height) {
  6034. width = size.width;
  6035. height = size.height;
  6036. }
  6037. else if (size.width && !size.height) {
  6038. width = size.width;
  6039. height = Math.round(width / engine.getAspectRatio(camera));
  6040. }
  6041. else if (size.height && !size.width) {
  6042. height = size.height;
  6043. width = Math.round(height * engine.getAspectRatio(camera));
  6044. }
  6045. else if (!isNaN(size)) {
  6046. height = size;
  6047. width = size;
  6048. }
  6049. else {
  6050. Tools.Error("Invalid 'size' parameter !");
  6051. return;
  6052. }
  6053. if (!screenshotCanvas) {
  6054. screenshotCanvas = document.createElement('canvas');
  6055. }
  6056. screenshotCanvas.width = width;
  6057. screenshotCanvas.height = height;
  6058. var renderContext = screenshotCanvas.getContext("2d");
  6059. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6060. var newWidth = width;
  6061. var newHeight = newWidth / ratio;
  6062. if (newHeight > height) {
  6063. newHeight = height;
  6064. newWidth = newHeight * ratio;
  6065. }
  6066. var offsetX = Math.max(0, width - newWidth) / 2;
  6067. var offsetY = Math.max(0, height - newHeight) / 2;
  6068. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6069. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6070. };
  6071. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6072. if (mimeType === void 0) { mimeType = "image/png"; }
  6073. if (samples === void 0) { samples = 1; }
  6074. var width;
  6075. var height;
  6076. //If a precision value is specified
  6077. if (size.precision) {
  6078. width = Math.round(engine.getRenderWidth() * size.precision);
  6079. height = Math.round(width / engine.getAspectRatio(camera));
  6080. size = { width: width, height: height };
  6081. }
  6082. else if (size.width && size.height) {
  6083. width = size.width;
  6084. height = size.height;
  6085. }
  6086. else if (size.width && !size.height) {
  6087. width = size.width;
  6088. height = Math.round(width / engine.getAspectRatio(camera));
  6089. size = { width: width, height: height };
  6090. }
  6091. else if (size.height && !size.width) {
  6092. height = size.height;
  6093. width = Math.round(height * engine.getAspectRatio(camera));
  6094. size = { width: width, height: height };
  6095. }
  6096. else if (!isNaN(size)) {
  6097. height = size;
  6098. width = size;
  6099. }
  6100. else {
  6101. Tools.Error("Invalid 'size' parameter !");
  6102. return;
  6103. }
  6104. var scene = camera.getScene();
  6105. var previousCamera = null;
  6106. if (scene.activeCamera !== camera) {
  6107. previousCamera = scene.activeCamera;
  6108. scene.activeCamera = camera;
  6109. }
  6110. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6111. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6112. texture.renderList = null;
  6113. texture.samples = samples;
  6114. texture.onAfterRenderObservable.add(function () {
  6115. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6116. });
  6117. scene.incrementRenderId();
  6118. scene.resetCachedMaterial();
  6119. texture.render(true);
  6120. texture.dispose();
  6121. if (previousCamera) {
  6122. scene.activeCamera = previousCamera;
  6123. }
  6124. camera.getProjectionMatrix(true); // Force cache refresh;
  6125. };
  6126. // XHR response validator for local file scenario
  6127. Tools.ValidateXHRData = function (xhr, dataType) {
  6128. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6129. if (dataType === void 0) { dataType = 7; }
  6130. try {
  6131. if (dataType & 1) {
  6132. if (xhr.responseText && xhr.responseText.length > 0) {
  6133. return true;
  6134. }
  6135. else if (dataType === 1) {
  6136. return false;
  6137. }
  6138. }
  6139. if (dataType & 2) {
  6140. // Check header width and height since there is no "TGA" magic number
  6141. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6142. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6143. return true;
  6144. }
  6145. else if (dataType === 2) {
  6146. return false;
  6147. }
  6148. }
  6149. if (dataType & 4) {
  6150. // Check for the "DDS" magic number
  6151. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6152. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6153. return true;
  6154. }
  6155. else {
  6156. return false;
  6157. }
  6158. }
  6159. }
  6160. catch (e) {
  6161. // Global protection
  6162. }
  6163. return false;
  6164. };
  6165. /**
  6166. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6167. * Be aware Math.random() could cause collisions, but:
  6168. * "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"
  6169. */
  6170. Tools.RandomId = function () {
  6171. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6172. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6173. return v.toString(16);
  6174. });
  6175. };
  6176. Object.defineProperty(Tools, "NoneLogLevel", {
  6177. get: function () {
  6178. return Tools._NoneLogLevel;
  6179. },
  6180. enumerable: true,
  6181. configurable: true
  6182. });
  6183. Object.defineProperty(Tools, "MessageLogLevel", {
  6184. get: function () {
  6185. return Tools._MessageLogLevel;
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. Object.defineProperty(Tools, "WarningLogLevel", {
  6191. get: function () {
  6192. return Tools._WarningLogLevel;
  6193. },
  6194. enumerable: true,
  6195. configurable: true
  6196. });
  6197. Object.defineProperty(Tools, "ErrorLogLevel", {
  6198. get: function () {
  6199. return Tools._ErrorLogLevel;
  6200. },
  6201. enumerable: true,
  6202. configurable: true
  6203. });
  6204. Object.defineProperty(Tools, "AllLogLevel", {
  6205. get: function () {
  6206. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6207. },
  6208. enumerable: true,
  6209. configurable: true
  6210. });
  6211. Tools._AddLogEntry = function (entry) {
  6212. Tools._LogCache = entry + Tools._LogCache;
  6213. if (Tools.OnNewCacheEntry) {
  6214. Tools.OnNewCacheEntry(entry);
  6215. }
  6216. };
  6217. Tools._FormatMessage = function (message) {
  6218. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6219. var date = new Date();
  6220. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6221. };
  6222. Tools._LogDisabled = function (message) {
  6223. // nothing to do
  6224. };
  6225. Tools._LogEnabled = function (message) {
  6226. var formattedMessage = Tools._FormatMessage(message);
  6227. console.log("BJS - " + formattedMessage);
  6228. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6229. Tools._AddLogEntry(entry);
  6230. };
  6231. Tools._WarnDisabled = function (message) {
  6232. // nothing to do
  6233. };
  6234. Tools._WarnEnabled = function (message) {
  6235. var formattedMessage = Tools._FormatMessage(message);
  6236. console.warn("BJS - " + formattedMessage);
  6237. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6238. Tools._AddLogEntry(entry);
  6239. };
  6240. Tools._ErrorDisabled = function (message) {
  6241. // nothing to do
  6242. };
  6243. Tools._ErrorEnabled = function (message) {
  6244. Tools.errorsCount++;
  6245. var formattedMessage = Tools._FormatMessage(message);
  6246. console.error("BJS - " + formattedMessage);
  6247. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6248. Tools._AddLogEntry(entry);
  6249. };
  6250. Object.defineProperty(Tools, "LogCache", {
  6251. get: function () {
  6252. return Tools._LogCache;
  6253. },
  6254. enumerable: true,
  6255. configurable: true
  6256. });
  6257. Tools.ClearLogCache = function () {
  6258. Tools._LogCache = "";
  6259. Tools.errorsCount = 0;
  6260. };
  6261. Object.defineProperty(Tools, "LogLevels", {
  6262. set: function (level) {
  6263. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6264. Tools.Log = Tools._LogEnabled;
  6265. }
  6266. else {
  6267. Tools.Log = Tools._LogDisabled;
  6268. }
  6269. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6270. Tools.Warn = Tools._WarnEnabled;
  6271. }
  6272. else {
  6273. Tools.Warn = Tools._WarnDisabled;
  6274. }
  6275. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6276. Tools.Error = Tools._ErrorEnabled;
  6277. }
  6278. else {
  6279. Tools.Error = Tools._ErrorDisabled;
  6280. }
  6281. },
  6282. enumerable: true,
  6283. configurable: true
  6284. });
  6285. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6286. get: function () {
  6287. return Tools._PerformanceNoneLogLevel;
  6288. },
  6289. enumerable: true,
  6290. configurable: true
  6291. });
  6292. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6293. get: function () {
  6294. return Tools._PerformanceUserMarkLogLevel;
  6295. },
  6296. enumerable: true,
  6297. configurable: true
  6298. });
  6299. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6300. get: function () {
  6301. return Tools._PerformanceConsoleLogLevel;
  6302. },
  6303. enumerable: true,
  6304. configurable: true
  6305. });
  6306. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6307. set: function (level) {
  6308. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6309. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6310. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6311. return;
  6312. }
  6313. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6314. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6315. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6316. return;
  6317. }
  6318. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6319. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6320. },
  6321. enumerable: true,
  6322. configurable: true
  6323. });
  6324. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6325. };
  6326. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6327. };
  6328. Tools._StartUserMark = function (counterName, condition) {
  6329. if (condition === void 0) { condition = true; }
  6330. if (!condition || !Tools._performance.mark) {
  6331. return;
  6332. }
  6333. Tools._performance.mark(counterName + "-Begin");
  6334. };
  6335. Tools._EndUserMark = function (counterName, condition) {
  6336. if (condition === void 0) { condition = true; }
  6337. if (!condition || !Tools._performance.mark) {
  6338. return;
  6339. }
  6340. Tools._performance.mark(counterName + "-End");
  6341. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6342. };
  6343. Tools._StartPerformanceConsole = function (counterName, condition) {
  6344. if (condition === void 0) { condition = true; }
  6345. if (!condition) {
  6346. return;
  6347. }
  6348. Tools._StartUserMark(counterName, condition);
  6349. if (console.time) {
  6350. console.time(counterName);
  6351. }
  6352. };
  6353. Tools._EndPerformanceConsole = function (counterName, condition) {
  6354. if (condition === void 0) { condition = true; }
  6355. if (!condition) {
  6356. return;
  6357. }
  6358. Tools._EndUserMark(counterName, condition);
  6359. if (console.time) {
  6360. console.timeEnd(counterName);
  6361. }
  6362. };
  6363. Object.defineProperty(Tools, "Now", {
  6364. get: function () {
  6365. if (window.performance && window.performance.now) {
  6366. return window.performance.now();
  6367. }
  6368. return new Date().getTime();
  6369. },
  6370. enumerable: true,
  6371. configurable: true
  6372. });
  6373. /**
  6374. * This method will return the name of the class used to create the instance of the given object.
  6375. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6376. * @param object the object to get the class name from
  6377. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6378. */
  6379. Tools.GetClassName = function (object, isType) {
  6380. if (isType === void 0) { isType = false; }
  6381. var name = null;
  6382. if (!isType && object.getClassName) {
  6383. name = object.getClassName();
  6384. }
  6385. else {
  6386. if (object instanceof Object) {
  6387. var classObj = isType ? object : Object.getPrototypeOf(object);
  6388. name = classObj.constructor["__bjsclassName__"];
  6389. }
  6390. if (!name) {
  6391. name = typeof object;
  6392. }
  6393. }
  6394. return name;
  6395. };
  6396. Tools.first = function (array, predicate) {
  6397. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6398. var el = array_1[_i];
  6399. if (predicate(el)) {
  6400. return el;
  6401. }
  6402. }
  6403. };
  6404. /**
  6405. * This method will return the name of the full name of the class, including its owning module (if any).
  6406. * 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).
  6407. * @param object the object to get the class name from
  6408. * @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.
  6409. */
  6410. Tools.getFullClassName = function (object, isType) {
  6411. if (isType === void 0) { isType = false; }
  6412. var className = null;
  6413. var moduleName = null;
  6414. if (!isType && object.getClassName) {
  6415. className = object.getClassName();
  6416. }
  6417. else {
  6418. if (object instanceof Object) {
  6419. var classObj = isType ? object : Object.getPrototypeOf(object);
  6420. className = classObj.constructor["__bjsclassName__"];
  6421. moduleName = classObj.constructor["__bjsmoduleName__"];
  6422. }
  6423. if (!className) {
  6424. className = typeof object;
  6425. }
  6426. }
  6427. if (!className) {
  6428. return null;
  6429. }
  6430. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6431. };
  6432. /**
  6433. * 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.
  6434. * @param array
  6435. */
  6436. Tools.arrayOrStringFeeder = function (array) {
  6437. return function (index) {
  6438. if (index >= array.length) {
  6439. return null;
  6440. }
  6441. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6442. if (val && val.getHashCode) {
  6443. val = val.getHashCode();
  6444. }
  6445. if (typeof val === "string") {
  6446. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6447. }
  6448. return val;
  6449. };
  6450. };
  6451. /**
  6452. * Compute the hashCode of a stream of number
  6453. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6454. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6455. * @return the hash code computed
  6456. */
  6457. Tools.hashCodeFromStream = function (feeder) {
  6458. // Based from here: http://stackoverflow.com/a/7616484/802124
  6459. var hash = 0;
  6460. var index = 0;
  6461. var chr = feeder(index++);
  6462. while (chr != null) {
  6463. hash = ((hash << 5) - hash) + chr;
  6464. hash |= 0; // Convert to 32bit integer
  6465. chr = feeder(index++);
  6466. }
  6467. return hash;
  6468. };
  6469. return Tools;
  6470. }());
  6471. Tools.BaseUrl = "";
  6472. Tools.CorsBehavior = "anonymous";
  6473. Tools.UseFallbackTexture = true;
  6474. // Used in case of a texture loading problem
  6475. 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";
  6476. // Logs
  6477. Tools._NoneLogLevel = 0;
  6478. Tools._MessageLogLevel = 1;
  6479. Tools._WarningLogLevel = 2;
  6480. Tools._ErrorLogLevel = 4;
  6481. Tools._LogCache = "";
  6482. Tools.errorsCount = 0;
  6483. Tools.Log = Tools._LogEnabled;
  6484. Tools.Warn = Tools._WarnEnabled;
  6485. Tools.Error = Tools._ErrorEnabled;
  6486. // Performances
  6487. Tools._PerformanceNoneLogLevel = 0;
  6488. Tools._PerformanceUserMarkLogLevel = 1;
  6489. Tools._PerformanceConsoleLogLevel = 2;
  6490. Tools._performance = window.performance;
  6491. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6492. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6493. BABYLON.Tools = Tools;
  6494. /**
  6495. * This class is used to track a performance counter which is number based.
  6496. * The user has access to many properties which give statistics of different nature
  6497. *
  6498. * The implementer can track two kinds of Performance Counter: time and count
  6499. * 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.
  6500. * 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.
  6501. */
  6502. var PerfCounter = (function () {
  6503. function PerfCounter() {
  6504. this._startMonitoringTime = 0;
  6505. this._min = 0;
  6506. this._max = 0;
  6507. this._average = 0;
  6508. this._lastSecAverage = 0;
  6509. this._current = 0;
  6510. this._totalValueCount = 0;
  6511. this._totalAccumulated = 0;
  6512. this._lastSecAccumulated = 0;
  6513. this._lastSecTime = 0;
  6514. this._lastSecValueCount = 0;
  6515. }
  6516. Object.defineProperty(PerfCounter.prototype, "min", {
  6517. /**
  6518. * Returns the smallest value ever
  6519. */
  6520. get: function () {
  6521. return this._min;
  6522. },
  6523. enumerable: true,
  6524. configurable: true
  6525. });
  6526. Object.defineProperty(PerfCounter.prototype, "max", {
  6527. /**
  6528. * Returns the biggest value ever
  6529. */
  6530. get: function () {
  6531. return this._max;
  6532. },
  6533. enumerable: true,
  6534. configurable: true
  6535. });
  6536. Object.defineProperty(PerfCounter.prototype, "average", {
  6537. /**
  6538. * Returns the average value since the performance counter is running
  6539. */
  6540. get: function () {
  6541. return this._average;
  6542. },
  6543. enumerable: true,
  6544. configurable: true
  6545. });
  6546. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6547. /**
  6548. * Returns the average value of the last second the counter was monitored
  6549. */
  6550. get: function () {
  6551. return this._lastSecAverage;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(PerfCounter.prototype, "current", {
  6557. /**
  6558. * Returns the current value
  6559. */
  6560. get: function () {
  6561. return this._current;
  6562. },
  6563. enumerable: true,
  6564. configurable: true
  6565. });
  6566. Object.defineProperty(PerfCounter.prototype, "total", {
  6567. get: function () {
  6568. return this._totalAccumulated;
  6569. },
  6570. enumerable: true,
  6571. configurable: true
  6572. });
  6573. /**
  6574. * Call this method to start monitoring a new frame.
  6575. * 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.
  6576. */
  6577. PerfCounter.prototype.fetchNewFrame = function () {
  6578. this._totalValueCount++;
  6579. this._current = 0;
  6580. this._lastSecValueCount++;
  6581. };
  6582. /**
  6583. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6584. * @param newCount the count value to add to the monitored count
  6585. * @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.
  6586. */
  6587. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6588. if (!PerfCounter.Enabled) {
  6589. return;
  6590. }
  6591. this._current += newCount;
  6592. if (fetchResult) {
  6593. this._fetchResult();
  6594. }
  6595. };
  6596. /**
  6597. * Start monitoring this performance counter
  6598. */
  6599. PerfCounter.prototype.beginMonitoring = function () {
  6600. if (!PerfCounter.Enabled) {
  6601. return;
  6602. }
  6603. this._startMonitoringTime = Tools.Now;
  6604. };
  6605. /**
  6606. * Compute the time lapsed since the previous beginMonitoring() call.
  6607. * @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
  6608. */
  6609. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6610. if (newFrame === void 0) { newFrame = true; }
  6611. if (!PerfCounter.Enabled) {
  6612. return;
  6613. }
  6614. if (newFrame) {
  6615. this.fetchNewFrame();
  6616. }
  6617. var currentTime = Tools.Now;
  6618. this._current = currentTime - this._startMonitoringTime;
  6619. if (newFrame) {
  6620. this._fetchResult();
  6621. }
  6622. };
  6623. PerfCounter.prototype._fetchResult = function () {
  6624. this._totalAccumulated += this._current;
  6625. this._lastSecAccumulated += this._current;
  6626. // Min/Max update
  6627. this._min = Math.min(this._min, this._current);
  6628. this._max = Math.max(this._max, this._current);
  6629. this._average = this._totalAccumulated / this._totalValueCount;
  6630. // Reset last sec?
  6631. var now = Tools.Now;
  6632. if ((now - this._lastSecTime) > 1000) {
  6633. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6634. this._lastSecTime = now;
  6635. this._lastSecAccumulated = 0;
  6636. this._lastSecValueCount = 0;
  6637. }
  6638. };
  6639. return PerfCounter;
  6640. }());
  6641. PerfCounter.Enabled = true;
  6642. BABYLON.PerfCounter = PerfCounter;
  6643. /**
  6644. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6645. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6646. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6647. * @param name The name of the class, case should be preserved
  6648. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6649. */
  6650. function className(name, module) {
  6651. return function (target) {
  6652. target["__bjsclassName__"] = name;
  6653. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6654. };
  6655. }
  6656. BABYLON.className = className;
  6657. /**
  6658. * An implementation of a loop for asynchronous functions.
  6659. */
  6660. var AsyncLoop = (function () {
  6661. /**
  6662. * Constroctor.
  6663. * @param iterations the number of iterations.
  6664. * @param _fn the function to run each iteration
  6665. * @param _successCallback the callback that will be called upon succesful execution
  6666. * @param offset starting offset.
  6667. */
  6668. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6669. if (offset === void 0) { offset = 0; }
  6670. this.iterations = iterations;
  6671. this._fn = _fn;
  6672. this._successCallback = _successCallback;
  6673. this.index = offset - 1;
  6674. this._done = false;
  6675. }
  6676. /**
  6677. * Execute the next iteration. Must be called after the last iteration was finished.
  6678. */
  6679. AsyncLoop.prototype.executeNext = function () {
  6680. if (!this._done) {
  6681. if (this.index + 1 < this.iterations) {
  6682. ++this.index;
  6683. this._fn(this);
  6684. }
  6685. else {
  6686. this.breakLoop();
  6687. }
  6688. }
  6689. };
  6690. /**
  6691. * Break the loop and run the success callback.
  6692. */
  6693. AsyncLoop.prototype.breakLoop = function () {
  6694. this._done = true;
  6695. this._successCallback();
  6696. };
  6697. /**
  6698. * Helper function
  6699. */
  6700. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6701. if (offset === void 0) { offset = 0; }
  6702. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6703. loop.executeNext();
  6704. return loop;
  6705. };
  6706. /**
  6707. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6708. * @param iterations total number of iterations
  6709. * @param syncedIterations number of synchronous iterations in each async iteration.
  6710. * @param fn the function to call each iteration.
  6711. * @param callback a success call back that will be called when iterating stops.
  6712. * @param breakFunction a break condition (optional)
  6713. * @param timeout timeout settings for the setTimeout function. default - 0.
  6714. * @constructor
  6715. */
  6716. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6717. if (timeout === void 0) { timeout = 0; }
  6718. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6719. if (breakFunction && breakFunction())
  6720. loop.breakLoop();
  6721. else {
  6722. setTimeout(function () {
  6723. for (var i = 0; i < syncedIterations; ++i) {
  6724. var iteration = (loop.index * syncedIterations) + i;
  6725. if (iteration >= iterations)
  6726. break;
  6727. fn(iteration);
  6728. if (breakFunction && breakFunction()) {
  6729. loop.breakLoop();
  6730. break;
  6731. }
  6732. }
  6733. loop.executeNext();
  6734. }, timeout);
  6735. }
  6736. }, callback);
  6737. };
  6738. return AsyncLoop;
  6739. }());
  6740. BABYLON.AsyncLoop = AsyncLoop;
  6741. })(BABYLON || (BABYLON = {}));
  6742. //# sourceMappingURL=babylon.tools.js.map
  6743. var BABYLON;
  6744. (function (BABYLON) {
  6745. var Internals;
  6746. (function (Internals) {
  6747. var _AlphaState = (function () {
  6748. /**
  6749. * Initializes the state.
  6750. */
  6751. function _AlphaState() {
  6752. this._isAlphaBlendDirty = false;
  6753. this._isBlendFunctionParametersDirty = false;
  6754. this._isBlendEquationParametersDirty = false;
  6755. this._isBlendConstantsDirty = false;
  6756. this._alphaBlend = false;
  6757. this._blendFunctionParameters = new Array(4);
  6758. this._blendEquationParameters = new Array(2);
  6759. this._blendConstants = new Array(4);
  6760. this.reset();
  6761. }
  6762. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6763. get: function () {
  6764. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6765. },
  6766. enumerable: true,
  6767. configurable: true
  6768. });
  6769. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6770. get: function () {
  6771. return this._alphaBlend;
  6772. },
  6773. set: function (value) {
  6774. if (this._alphaBlend === value) {
  6775. return;
  6776. }
  6777. this._alphaBlend = value;
  6778. this._isAlphaBlendDirty = true;
  6779. },
  6780. enumerable: true,
  6781. configurable: true
  6782. });
  6783. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6784. if (this._blendConstants[0] === r &&
  6785. this._blendConstants[1] === g &&
  6786. this._blendConstants[2] === b &&
  6787. this._blendConstants[3] === a) {
  6788. return;
  6789. }
  6790. this._blendConstants[0] = r;
  6791. this._blendConstants[1] = g;
  6792. this._blendConstants[2] = b;
  6793. this._blendConstants[3] = a;
  6794. this._isBlendConstantsDirty = true;
  6795. };
  6796. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6797. if (this._blendFunctionParameters[0] === value0 &&
  6798. this._blendFunctionParameters[1] === value1 &&
  6799. this._blendFunctionParameters[2] === value2 &&
  6800. this._blendFunctionParameters[3] === value3) {
  6801. return;
  6802. }
  6803. this._blendFunctionParameters[0] = value0;
  6804. this._blendFunctionParameters[1] = value1;
  6805. this._blendFunctionParameters[2] = value2;
  6806. this._blendFunctionParameters[3] = value3;
  6807. this._isBlendFunctionParametersDirty = true;
  6808. };
  6809. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6810. if (this._blendEquationParameters[0] === rgb &&
  6811. this._blendEquationParameters[1] === alpha) {
  6812. return;
  6813. }
  6814. this._blendEquationParameters[0] = rgb;
  6815. this._blendEquationParameters[1] = alpha;
  6816. this._isBlendEquationParametersDirty = true;
  6817. };
  6818. _AlphaState.prototype.reset = function () {
  6819. this._alphaBlend = false;
  6820. this._blendFunctionParameters[0] = null;
  6821. this._blendFunctionParameters[1] = null;
  6822. this._blendFunctionParameters[2] = null;
  6823. this._blendFunctionParameters[3] = null;
  6824. this._blendEquationParameters[0] = null;
  6825. this._blendEquationParameters[1] = null;
  6826. this._blendConstants[0] = null;
  6827. this._blendConstants[1] = null;
  6828. this._blendConstants[2] = null;
  6829. this._blendConstants[3] = null;
  6830. this._isAlphaBlendDirty = true;
  6831. this._isBlendFunctionParametersDirty = false;
  6832. this._isBlendEquationParametersDirty = false;
  6833. this._isBlendConstantsDirty = false;
  6834. };
  6835. _AlphaState.prototype.apply = function (gl) {
  6836. if (!this.isDirty) {
  6837. return;
  6838. }
  6839. // Alpha blend
  6840. if (this._isAlphaBlendDirty) {
  6841. if (this._alphaBlend) {
  6842. gl.enable(gl.BLEND);
  6843. }
  6844. else {
  6845. gl.disable(gl.BLEND);
  6846. }
  6847. this._isAlphaBlendDirty = false;
  6848. }
  6849. // Alpha function
  6850. if (this._isBlendFunctionParametersDirty) {
  6851. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6852. this._isBlendFunctionParametersDirty = false;
  6853. }
  6854. // Alpha equation
  6855. if (this._isBlendEquationParametersDirty) {
  6856. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6857. this._isBlendEquationParametersDirty = false;
  6858. }
  6859. // Constants
  6860. if (this._isBlendConstantsDirty) {
  6861. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6862. this._isBlendConstantsDirty = false;
  6863. }
  6864. };
  6865. return _AlphaState;
  6866. }());
  6867. Internals._AlphaState = _AlphaState;
  6868. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6869. })(BABYLON || (BABYLON = {}));
  6870. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6871. var BABYLON;
  6872. (function (BABYLON) {
  6873. var Internals;
  6874. (function (Internals) {
  6875. var _DepthCullingState = (function () {
  6876. /**
  6877. * Initializes the state.
  6878. */
  6879. function _DepthCullingState() {
  6880. this._isDepthTestDirty = false;
  6881. this._isDepthMaskDirty = false;
  6882. this._isDepthFuncDirty = false;
  6883. this._isCullFaceDirty = false;
  6884. this._isCullDirty = false;
  6885. this._isZOffsetDirty = false;
  6886. this.reset();
  6887. }
  6888. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6889. get: function () {
  6890. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6891. },
  6892. enumerable: true,
  6893. configurable: true
  6894. });
  6895. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6896. get: function () {
  6897. return this._zOffset;
  6898. },
  6899. set: function (value) {
  6900. if (this._zOffset === value) {
  6901. return;
  6902. }
  6903. this._zOffset = value;
  6904. this._isZOffsetDirty = true;
  6905. },
  6906. enumerable: true,
  6907. configurable: true
  6908. });
  6909. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6910. get: function () {
  6911. return this._cullFace;
  6912. },
  6913. set: function (value) {
  6914. if (this._cullFace === value) {
  6915. return;
  6916. }
  6917. this._cullFace = value;
  6918. this._isCullFaceDirty = true;
  6919. },
  6920. enumerable: true,
  6921. configurable: true
  6922. });
  6923. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6924. get: function () {
  6925. return this._cull;
  6926. },
  6927. set: function (value) {
  6928. if (this._cull === value) {
  6929. return;
  6930. }
  6931. this._cull = value;
  6932. this._isCullDirty = true;
  6933. },
  6934. enumerable: true,
  6935. configurable: true
  6936. });
  6937. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6938. get: function () {
  6939. return this._depthFunc;
  6940. },
  6941. set: function (value) {
  6942. if (this._depthFunc === value) {
  6943. return;
  6944. }
  6945. this._depthFunc = value;
  6946. this._isDepthFuncDirty = true;
  6947. },
  6948. enumerable: true,
  6949. configurable: true
  6950. });
  6951. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6952. get: function () {
  6953. return this._depthMask;
  6954. },
  6955. set: function (value) {
  6956. if (this._depthMask === value) {
  6957. return;
  6958. }
  6959. this._depthMask = value;
  6960. this._isDepthMaskDirty = true;
  6961. },
  6962. enumerable: true,
  6963. configurable: true
  6964. });
  6965. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6966. get: function () {
  6967. return this._depthTest;
  6968. },
  6969. set: function (value) {
  6970. if (this._depthTest === value) {
  6971. return;
  6972. }
  6973. this._depthTest = value;
  6974. this._isDepthTestDirty = true;
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. _DepthCullingState.prototype.reset = function () {
  6980. this._depthMask = true;
  6981. this._depthTest = true;
  6982. this._depthFunc = null;
  6983. this._cullFace = null;
  6984. this._cull = null;
  6985. this._zOffset = 0;
  6986. this._isDepthTestDirty = true;
  6987. this._isDepthMaskDirty = true;
  6988. this._isDepthFuncDirty = false;
  6989. this._isCullFaceDirty = false;
  6990. this._isCullDirty = false;
  6991. this._isZOffsetDirty = false;
  6992. };
  6993. _DepthCullingState.prototype.apply = function (gl) {
  6994. if (!this.isDirty) {
  6995. return;
  6996. }
  6997. // Cull
  6998. if (this._isCullDirty) {
  6999. if (this.cull) {
  7000. gl.enable(gl.CULL_FACE);
  7001. }
  7002. else {
  7003. gl.disable(gl.CULL_FACE);
  7004. }
  7005. this._isCullDirty = false;
  7006. }
  7007. // Cull face
  7008. if (this._isCullFaceDirty) {
  7009. gl.cullFace(this.cullFace);
  7010. this._isCullFaceDirty = false;
  7011. }
  7012. // Depth mask
  7013. if (this._isDepthMaskDirty) {
  7014. gl.depthMask(this.depthMask);
  7015. this._isDepthMaskDirty = false;
  7016. }
  7017. // Depth test
  7018. if (this._isDepthTestDirty) {
  7019. if (this.depthTest) {
  7020. gl.enable(gl.DEPTH_TEST);
  7021. }
  7022. else {
  7023. gl.disable(gl.DEPTH_TEST);
  7024. }
  7025. this._isDepthTestDirty = false;
  7026. }
  7027. // Depth func
  7028. if (this._isDepthFuncDirty) {
  7029. gl.depthFunc(this.depthFunc);
  7030. this._isDepthFuncDirty = false;
  7031. }
  7032. // zOffset
  7033. if (this._isZOffsetDirty) {
  7034. if (this.zOffset) {
  7035. gl.enable(gl.POLYGON_OFFSET_FILL);
  7036. gl.polygonOffset(this.zOffset, 0);
  7037. }
  7038. else {
  7039. gl.disable(gl.POLYGON_OFFSET_FILL);
  7040. }
  7041. this._isZOffsetDirty = false;
  7042. }
  7043. };
  7044. return _DepthCullingState;
  7045. }());
  7046. Internals._DepthCullingState = _DepthCullingState;
  7047. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7048. })(BABYLON || (BABYLON = {}));
  7049. //# sourceMappingURL=babylon.depthCullingState.js.map
  7050. var BABYLON;
  7051. (function (BABYLON) {
  7052. var Internals;
  7053. (function (Internals) {
  7054. var _StencilState = (function () {
  7055. function _StencilState() {
  7056. this._isStencilTestDirty = false;
  7057. this._isStencilMaskDirty = false;
  7058. this._isStencilFuncDirty = false;
  7059. this._isStencilOpDirty = false;
  7060. this.reset();
  7061. }
  7062. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7063. get: function () {
  7064. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7065. },
  7066. enumerable: true,
  7067. configurable: true
  7068. });
  7069. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7070. get: function () {
  7071. return this._stencilFunc;
  7072. },
  7073. set: function (value) {
  7074. if (this._stencilFunc === value) {
  7075. return;
  7076. }
  7077. this._stencilFunc = value;
  7078. this._isStencilFuncDirty = true;
  7079. },
  7080. enumerable: true,
  7081. configurable: true
  7082. });
  7083. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7084. get: function () {
  7085. return this._stencilFuncRef;
  7086. },
  7087. set: function (value) {
  7088. if (this._stencilFuncRef === value) {
  7089. return;
  7090. }
  7091. this._stencilFuncRef = value;
  7092. this._isStencilFuncDirty = true;
  7093. },
  7094. enumerable: true,
  7095. configurable: true
  7096. });
  7097. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7098. get: function () {
  7099. return this._stencilFuncMask;
  7100. },
  7101. set: function (value) {
  7102. if (this._stencilFuncMask === value) {
  7103. return;
  7104. }
  7105. this._stencilFuncMask = value;
  7106. this._isStencilFuncDirty = true;
  7107. },
  7108. enumerable: true,
  7109. configurable: true
  7110. });
  7111. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7112. get: function () {
  7113. return this._stencilOpStencilFail;
  7114. },
  7115. set: function (value) {
  7116. if (this._stencilOpStencilFail === value) {
  7117. return;
  7118. }
  7119. this._stencilOpStencilFail = value;
  7120. this._isStencilOpDirty = true;
  7121. },
  7122. enumerable: true,
  7123. configurable: true
  7124. });
  7125. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7126. get: function () {
  7127. return this._stencilOpDepthFail;
  7128. },
  7129. set: function (value) {
  7130. if (this._stencilOpDepthFail === value) {
  7131. return;
  7132. }
  7133. this._stencilOpDepthFail = value;
  7134. this._isStencilOpDirty = true;
  7135. },
  7136. enumerable: true,
  7137. configurable: true
  7138. });
  7139. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7140. get: function () {
  7141. return this._stencilOpStencilDepthPass;
  7142. },
  7143. set: function (value) {
  7144. if (this._stencilOpStencilDepthPass === value) {
  7145. return;
  7146. }
  7147. this._stencilOpStencilDepthPass = value;
  7148. this._isStencilOpDirty = true;
  7149. },
  7150. enumerable: true,
  7151. configurable: true
  7152. });
  7153. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7154. get: function () {
  7155. return this._stencilMask;
  7156. },
  7157. set: function (value) {
  7158. if (this._stencilMask === value) {
  7159. return;
  7160. }
  7161. this._stencilMask = value;
  7162. this._isStencilMaskDirty = true;
  7163. },
  7164. enumerable: true,
  7165. configurable: true
  7166. });
  7167. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7168. get: function () {
  7169. return this._stencilTest;
  7170. },
  7171. set: function (value) {
  7172. if (this._stencilTest === value) {
  7173. return;
  7174. }
  7175. this._stencilTest = value;
  7176. this._isStencilTestDirty = true;
  7177. },
  7178. enumerable: true,
  7179. configurable: true
  7180. });
  7181. _StencilState.prototype.reset = function () {
  7182. this._stencilTest = false;
  7183. this._stencilMask = 0xFF;
  7184. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7185. this._stencilFuncRef = 1;
  7186. this._stencilFuncMask = 0xFF;
  7187. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7188. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7189. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7190. this._isStencilTestDirty = true;
  7191. this._isStencilMaskDirty = true;
  7192. this._isStencilFuncDirty = true;
  7193. this._isStencilOpDirty = true;
  7194. };
  7195. _StencilState.prototype.apply = function (gl) {
  7196. if (!this.isDirty) {
  7197. return;
  7198. }
  7199. // Stencil test
  7200. if (this._isStencilTestDirty) {
  7201. if (this.stencilTest) {
  7202. gl.enable(gl.STENCIL_TEST);
  7203. }
  7204. else {
  7205. gl.disable(gl.STENCIL_TEST);
  7206. }
  7207. this._isStencilTestDirty = false;
  7208. }
  7209. // Stencil mask
  7210. if (this._isStencilMaskDirty) {
  7211. gl.stencilMask(this.stencilMask);
  7212. this._isStencilMaskDirty = false;
  7213. }
  7214. // Stencil func
  7215. if (this._isStencilFuncDirty) {
  7216. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7217. this._isStencilFuncDirty = false;
  7218. }
  7219. // Stencil op
  7220. if (this._isStencilOpDirty) {
  7221. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7222. this._isStencilOpDirty = false;
  7223. }
  7224. };
  7225. return _StencilState;
  7226. }());
  7227. Internals._StencilState = _StencilState;
  7228. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7229. })(BABYLON || (BABYLON = {}));
  7230. //# sourceMappingURL=babylon.stencilState.js.map
  7231. var BABYLON;
  7232. (function (BABYLON) {
  7233. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7234. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7235. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7236. gl.compileShader(shader);
  7237. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7238. throw new Error(gl.getShaderInfoLog(shader));
  7239. }
  7240. return shader;
  7241. };
  7242. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7243. var magFilter = gl.NEAREST;
  7244. var minFilter = gl.NEAREST;
  7245. switch (samplingMode) {
  7246. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7247. magFilter = gl.LINEAR;
  7248. if (generateMipMaps) {
  7249. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7250. }
  7251. else {
  7252. minFilter = gl.LINEAR;
  7253. }
  7254. break;
  7255. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7256. magFilter = gl.LINEAR;
  7257. if (generateMipMaps) {
  7258. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7259. }
  7260. else {
  7261. minFilter = gl.LINEAR;
  7262. }
  7263. break;
  7264. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7265. magFilter = gl.NEAREST;
  7266. if (generateMipMaps) {
  7267. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7268. }
  7269. else {
  7270. minFilter = gl.NEAREST;
  7271. }
  7272. break;
  7273. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7274. magFilter = gl.NEAREST;
  7275. if (generateMipMaps) {
  7276. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7277. }
  7278. else {
  7279. minFilter = gl.NEAREST;
  7280. }
  7281. break;
  7282. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7283. magFilter = gl.NEAREST;
  7284. if (generateMipMaps) {
  7285. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7286. }
  7287. else {
  7288. minFilter = gl.LINEAR;
  7289. }
  7290. break;
  7291. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7292. magFilter = gl.NEAREST;
  7293. if (generateMipMaps) {
  7294. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7295. }
  7296. else {
  7297. minFilter = gl.LINEAR;
  7298. }
  7299. break;
  7300. case BABYLON.Texture.NEAREST_LINEAR:
  7301. magFilter = gl.NEAREST;
  7302. minFilter = gl.LINEAR;
  7303. break;
  7304. case BABYLON.Texture.NEAREST_NEAREST:
  7305. magFilter = gl.NEAREST;
  7306. minFilter = gl.NEAREST;
  7307. break;
  7308. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7309. magFilter = gl.LINEAR;
  7310. if (generateMipMaps) {
  7311. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7312. }
  7313. else {
  7314. minFilter = gl.NEAREST;
  7315. }
  7316. break;
  7317. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7318. magFilter = gl.LINEAR;
  7319. if (generateMipMaps) {
  7320. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7321. }
  7322. else {
  7323. minFilter = gl.NEAREST;
  7324. }
  7325. break;
  7326. case BABYLON.Texture.LINEAR_LINEAR:
  7327. magFilter = gl.LINEAR;
  7328. minFilter = gl.LINEAR;
  7329. break;
  7330. case BABYLON.Texture.LINEAR_NEAREST:
  7331. magFilter = gl.LINEAR;
  7332. minFilter = gl.NEAREST;
  7333. break;
  7334. }
  7335. return {
  7336. min: minFilter,
  7337. mag: magFilter
  7338. };
  7339. };
  7340. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7341. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7342. var engine = scene.getEngine();
  7343. if (!engine) {
  7344. return;
  7345. }
  7346. var potWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize) : width;
  7347. var potHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize) : height;
  7348. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7349. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7350. texture._baseWidth = width;
  7351. texture._baseHeight = height;
  7352. texture._width = potWidth;
  7353. texture._height = potHeight;
  7354. texture.isReady = true;
  7355. processFunction(potWidth, potHeight);
  7356. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7357. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7358. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7359. if (!noMipmap && !isCompressed) {
  7360. gl.generateMipmap(gl.TEXTURE_2D);
  7361. }
  7362. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7363. engine.resetTextureCache();
  7364. scene._removePendingData(texture);
  7365. texture.onLoadedCallbacks.forEach(function (callback) {
  7366. callback();
  7367. });
  7368. texture.onLoadedCallbacks = [];
  7369. };
  7370. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7371. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7372. var img;
  7373. var onload = function () {
  7374. loadedImages[index] = img;
  7375. loadedImages._internalCount++;
  7376. scene._removePendingData(img);
  7377. if (loadedImages._internalCount === 6) {
  7378. onfinish(loadedImages);
  7379. }
  7380. };
  7381. var onerror = function () {
  7382. scene._removePendingData(img);
  7383. if (onErrorCallBack) {
  7384. onErrorCallBack();
  7385. }
  7386. };
  7387. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7388. scene._addPendingData(img);
  7389. };
  7390. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7391. if (onError === void 0) { onError = null; }
  7392. var loadedImages = [];
  7393. loadedImages._internalCount = 0;
  7394. for (var index = 0; index < 6; index++) {
  7395. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7396. }
  7397. };
  7398. var BufferPointer = (function () {
  7399. function BufferPointer() {
  7400. }
  7401. return BufferPointer;
  7402. }());
  7403. var InstancingAttributeInfo = (function () {
  7404. function InstancingAttributeInfo() {
  7405. }
  7406. return InstancingAttributeInfo;
  7407. }());
  7408. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7409. /**
  7410. * Regroup several parameters relative to the browser in use
  7411. */
  7412. var EngineCapabilities = (function () {
  7413. function EngineCapabilities() {
  7414. }
  7415. return EngineCapabilities;
  7416. }());
  7417. BABYLON.EngineCapabilities = EngineCapabilities;
  7418. /**
  7419. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7420. */
  7421. var Engine = (function () {
  7422. /**
  7423. * @constructor
  7424. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7425. * @param {boolean} [antialias] - enable antialias
  7426. * @param options - further options to be sent to the getContext function
  7427. */
  7428. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7429. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7430. var _this = this;
  7431. // Public members
  7432. this.forcePOTTextures = false;
  7433. this.isFullscreen = false;
  7434. this.isPointerLock = false;
  7435. this.cullBackFaces = true;
  7436. this.renderEvenInBackground = true;
  7437. this.preventCacheWipeBetweenFrames = false;
  7438. // To enable/disable IDB support and avoid XHR on .manifest
  7439. this.enableOfflineSupport = false;
  7440. this.scenes = new Array();
  7441. // Observables
  7442. /**
  7443. * Observable event triggered each time the rendering canvas is resized
  7444. */
  7445. this.onResizeObservable = new BABYLON.Observable();
  7446. /**
  7447. * Observable event triggered each time the canvas lost focus
  7448. */
  7449. this.onCanvasBlurObservable = new BABYLON.Observable();
  7450. this._windowIsBackground = false;
  7451. this._webGLVersion = 1.0;
  7452. this._badOS = false;
  7453. this._badDesktopOS = false;
  7454. this._drawCalls = new BABYLON.PerfCounter();
  7455. this._renderingQueueLaunched = false;
  7456. this._activeRenderLoops = [];
  7457. // FPS
  7458. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7459. this._fps = 60;
  7460. this._deltaTime = 0;
  7461. // States
  7462. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7463. this._stencilState = new BABYLON.Internals._StencilState();
  7464. this._alphaState = new BABYLON.Internals._AlphaState();
  7465. this._alphaMode = Engine.ALPHA_DISABLE;
  7466. // Cache
  7467. this._loadedTexturesCache = new Array();
  7468. this._maxTextureChannels = 16;
  7469. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7470. this._compiledEffects = {};
  7471. this._vertexAttribArraysEnabled = [];
  7472. this._uintIndicesCurrentlySet = false;
  7473. this._currentBoundBuffer = new Array();
  7474. this._currentBufferPointers = new Array();
  7475. this._currentInstanceLocations = new Array();
  7476. this._currentInstanceBuffers = new Array();
  7477. this._vaoRecordInProgress = false;
  7478. this._mustWipeVertexAttributes = false;
  7479. // Hardware supported Compressed Textures
  7480. this._texturesSupported = new Array();
  7481. this._onVRFullScreenTriggered = function () {
  7482. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7483. //get the old size before we change
  7484. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7485. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7486. //get the width and height, change the render size
  7487. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7488. var width, height;
  7489. _this.setHardwareScalingLevel(1);
  7490. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7491. }
  7492. else {
  7493. //When the specs are implemented, need to uncomment this.
  7494. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7495. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7496. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7497. _this._vrDisplayEnabled = undefined;
  7498. }
  7499. };
  7500. var canvas;
  7501. Engine.Instances.push(this);
  7502. options = options || {};
  7503. if (canvasOrContext.getContext) {
  7504. canvas = canvasOrContext;
  7505. this._renderingCanvas = canvas;
  7506. if (antialias != null) {
  7507. options.antialias = antialias;
  7508. }
  7509. if (options.preserveDrawingBuffer === undefined) {
  7510. options.preserveDrawingBuffer = false;
  7511. }
  7512. if (options.audioEngine === undefined) {
  7513. options.audioEngine = true;
  7514. }
  7515. if (options.stencil === undefined) {
  7516. options.stencil = true;
  7517. }
  7518. // GL
  7519. if (!options.disableWebGL2Support) {
  7520. try {
  7521. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7522. if (this._gl) {
  7523. this._webGLVersion = 2.0;
  7524. }
  7525. }
  7526. catch (e) {
  7527. // Do nothing
  7528. }
  7529. }
  7530. if (!this._gl) {
  7531. if (!canvas) {
  7532. throw new Error("The provided canvas is null or undefined.");
  7533. }
  7534. try {
  7535. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7536. }
  7537. catch (e) {
  7538. throw new Error("WebGL not supported");
  7539. }
  7540. }
  7541. if (!this._gl) {
  7542. throw new Error("WebGL not supported");
  7543. }
  7544. this._onBlur = function () {
  7545. _this._performanceMonitor.disable();
  7546. _this._windowIsBackground = true;
  7547. };
  7548. this._onFocus = function () {
  7549. _this._performanceMonitor.enable();
  7550. _this._windowIsBackground = false;
  7551. };
  7552. this._onCanvasBlur = function () {
  7553. _this.onCanvasBlurObservable.notifyObservers(_this);
  7554. };
  7555. window.addEventListener("blur", this._onBlur);
  7556. window.addEventListener("focus", this._onFocus);
  7557. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7558. }
  7559. else {
  7560. this._gl = canvasOrContext;
  7561. this._renderingCanvas = this._gl.canvas;
  7562. if (this._gl.renderbufferStorageMultisample) {
  7563. this._webGLVersion = 2.0;
  7564. }
  7565. options.stencil = this._gl.getContextAttributes().stencil;
  7566. }
  7567. // Viewport
  7568. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7569. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7570. this.resize();
  7571. // Caps
  7572. this._isStencilEnable = options.stencil;
  7573. this._caps = new EngineCapabilities();
  7574. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7575. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7576. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7577. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7578. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7579. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7580. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7581. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7582. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7583. // Infos
  7584. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7585. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7586. if (rendererInfo != null) {
  7587. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7588. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7589. }
  7590. if (!this._glVendor) {
  7591. this._glVendor = "Unknown vendor";
  7592. }
  7593. if (!this._glRenderer) {
  7594. this._glRenderer = "Unknown renderer";
  7595. }
  7596. // Constants
  7597. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7598. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7599. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7600. this._gl.DEPTH24_STENCIL8 = 35056;
  7601. // Extensions
  7602. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7603. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7604. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7605. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7606. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7607. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7608. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7609. 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');
  7610. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7611. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7612. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7613. this._caps.highPrecisionShaderSupported = true;
  7614. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7615. // Checks if some of the format renders first to allow the use of webgl inspector.
  7616. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7617. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7618. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7619. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7620. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7621. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7622. if (this._webGLVersion > 1) {
  7623. this._gl.HALF_FLOAT_OES = 0x140B;
  7624. }
  7625. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7626. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7627. // Vertex array object
  7628. if (this._webGLVersion > 1) {
  7629. this._caps.vertexArrayObject = true;
  7630. }
  7631. else {
  7632. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7633. if (vertexArrayObjectExtension != null) {
  7634. this._caps.vertexArrayObject = true;
  7635. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7636. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7637. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7638. }
  7639. else {
  7640. this._caps.vertexArrayObject = false;
  7641. }
  7642. }
  7643. // Instances count
  7644. if (this._webGLVersion > 1) {
  7645. this._caps.instancedArrays = true;
  7646. }
  7647. else {
  7648. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7649. if (instanceExtension != null) {
  7650. this._caps.instancedArrays = true;
  7651. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7652. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7653. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7654. }
  7655. else {
  7656. this._caps.instancedArrays = false;
  7657. }
  7658. }
  7659. // Intelligently add supported compressed formats in order to check for.
  7660. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7661. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7662. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7663. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7664. if (this._caps.astc)
  7665. this.texturesSupported.push('-astc.ktx');
  7666. if (this._caps.s3tc)
  7667. this.texturesSupported.push('-dxt.ktx');
  7668. if (this._caps.pvrtc)
  7669. this.texturesSupported.push('-pvrtc.ktx');
  7670. if (this._caps.etc2)
  7671. this.texturesSupported.push('-etc2.ktx');
  7672. if (this._caps.etc1)
  7673. this.texturesSupported.push('-etc1.ktx');
  7674. if (this._gl.getShaderPrecisionFormat) {
  7675. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7676. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7677. }
  7678. // Depth buffer
  7679. this.setDepthBuffer(true);
  7680. this.setDepthFunctionToLessOrEqual();
  7681. this.setDepthWrite(true);
  7682. if (canvas) {
  7683. // Fullscreen
  7684. this._onFullscreenChange = function () {
  7685. if (document.fullscreen !== undefined) {
  7686. _this.isFullscreen = document.fullscreen;
  7687. }
  7688. else if (document.mozFullScreen !== undefined) {
  7689. _this.isFullscreen = document.mozFullScreen;
  7690. }
  7691. else if (document.webkitIsFullScreen !== undefined) {
  7692. _this.isFullscreen = document.webkitIsFullScreen;
  7693. }
  7694. else if (document.msIsFullScreen !== undefined) {
  7695. _this.isFullscreen = document.msIsFullScreen;
  7696. }
  7697. // Pointer lock
  7698. if (_this.isFullscreen && _this._pointerLockRequested) {
  7699. canvas.requestPointerLock = canvas.requestPointerLock ||
  7700. canvas.msRequestPointerLock ||
  7701. canvas.mozRequestPointerLock ||
  7702. canvas.webkitRequestPointerLock;
  7703. if (canvas.requestPointerLock) {
  7704. canvas.requestPointerLock();
  7705. }
  7706. }
  7707. };
  7708. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7709. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7710. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7711. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7712. // Pointer lock
  7713. this._onPointerLockChange = function () {
  7714. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7715. document.webkitPointerLockElement === canvas ||
  7716. document.msPointerLockElement === canvas ||
  7717. document.pointerLockElement === canvas);
  7718. };
  7719. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7720. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7721. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7722. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7723. }
  7724. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7725. Engine.audioEngine = new BABYLON.AudioEngine();
  7726. }
  7727. // Prepare buffer pointers
  7728. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7729. this._currentBufferPointers[i] = new BufferPointer();
  7730. }
  7731. // Load WebVR Devices
  7732. if (options.autoEnableWebVR) {
  7733. this.initWebVR();
  7734. }
  7735. // Detect if we are running on a faulty buggy OS.
  7736. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7737. // Detect if we are running on a faulty buggy desktop OS.
  7738. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7739. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7740. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7741. }
  7742. Object.defineProperty(Engine, "LastCreatedEngine", {
  7743. get: function () {
  7744. if (Engine.Instances.length === 0) {
  7745. return null;
  7746. }
  7747. return Engine.Instances[Engine.Instances.length - 1];
  7748. },
  7749. enumerable: true,
  7750. configurable: true
  7751. });
  7752. Object.defineProperty(Engine, "LastCreatedScene", {
  7753. get: function () {
  7754. var lastCreatedEngine = Engine.LastCreatedEngine;
  7755. if (!lastCreatedEngine) {
  7756. return null;
  7757. }
  7758. if (lastCreatedEngine.scenes.length === 0) {
  7759. return null;
  7760. }
  7761. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7762. },
  7763. enumerable: true,
  7764. configurable: true
  7765. });
  7766. /**
  7767. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7768. */
  7769. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7770. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7771. var engine = Engine.Instances[engineIndex];
  7772. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7773. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7774. }
  7775. }
  7776. };
  7777. Object.defineProperty(Engine, "NEVER", {
  7778. get: function () {
  7779. return Engine._NEVER;
  7780. },
  7781. enumerable: true,
  7782. configurable: true
  7783. });
  7784. Object.defineProperty(Engine, "ALWAYS", {
  7785. get: function () {
  7786. return Engine._ALWAYS;
  7787. },
  7788. enumerable: true,
  7789. configurable: true
  7790. });
  7791. Object.defineProperty(Engine, "LESS", {
  7792. get: function () {
  7793. return Engine._LESS;
  7794. },
  7795. enumerable: true,
  7796. configurable: true
  7797. });
  7798. Object.defineProperty(Engine, "EQUAL", {
  7799. get: function () {
  7800. return Engine._EQUAL;
  7801. },
  7802. enumerable: true,
  7803. configurable: true
  7804. });
  7805. Object.defineProperty(Engine, "LEQUAL", {
  7806. get: function () {
  7807. return Engine._LEQUAL;
  7808. },
  7809. enumerable: true,
  7810. configurable: true
  7811. });
  7812. Object.defineProperty(Engine, "GREATER", {
  7813. get: function () {
  7814. return Engine._GREATER;
  7815. },
  7816. enumerable: true,
  7817. configurable: true
  7818. });
  7819. Object.defineProperty(Engine, "GEQUAL", {
  7820. get: function () {
  7821. return Engine._GEQUAL;
  7822. },
  7823. enumerable: true,
  7824. configurable: true
  7825. });
  7826. Object.defineProperty(Engine, "NOTEQUAL", {
  7827. get: function () {
  7828. return Engine._NOTEQUAL;
  7829. },
  7830. enumerable: true,
  7831. configurable: true
  7832. });
  7833. Object.defineProperty(Engine, "KEEP", {
  7834. get: function () {
  7835. return Engine._KEEP;
  7836. },
  7837. enumerable: true,
  7838. configurable: true
  7839. });
  7840. Object.defineProperty(Engine, "REPLACE", {
  7841. get: function () {
  7842. return Engine._REPLACE;
  7843. },
  7844. enumerable: true,
  7845. configurable: true
  7846. });
  7847. Object.defineProperty(Engine, "INCR", {
  7848. get: function () {
  7849. return Engine._INCR;
  7850. },
  7851. enumerable: true,
  7852. configurable: true
  7853. });
  7854. Object.defineProperty(Engine, "DECR", {
  7855. get: function () {
  7856. return Engine._DECR;
  7857. },
  7858. enumerable: true,
  7859. configurable: true
  7860. });
  7861. Object.defineProperty(Engine, "INVERT", {
  7862. get: function () {
  7863. return Engine._INVERT;
  7864. },
  7865. enumerable: true,
  7866. configurable: true
  7867. });
  7868. Object.defineProperty(Engine, "INCR_WRAP", {
  7869. get: function () {
  7870. return Engine._INCR_WRAP;
  7871. },
  7872. enumerable: true,
  7873. configurable: true
  7874. });
  7875. Object.defineProperty(Engine, "DECR_WRAP", {
  7876. get: function () {
  7877. return Engine._DECR_WRAP;
  7878. },
  7879. enumerable: true,
  7880. configurable: true
  7881. });
  7882. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7883. get: function () {
  7884. return Engine._ALPHA_DISABLE;
  7885. },
  7886. enumerable: true,
  7887. configurable: true
  7888. });
  7889. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7890. get: function () {
  7891. return Engine._ALPHA_ONEONE;
  7892. },
  7893. enumerable: true,
  7894. configurable: true
  7895. });
  7896. Object.defineProperty(Engine, "ALPHA_ADD", {
  7897. get: function () {
  7898. return Engine._ALPHA_ADD;
  7899. },
  7900. enumerable: true,
  7901. configurable: true
  7902. });
  7903. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7904. get: function () {
  7905. return Engine._ALPHA_COMBINE;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7911. get: function () {
  7912. return Engine._ALPHA_SUBTRACT;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7918. get: function () {
  7919. return Engine._ALPHA_MULTIPLY;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7925. get: function () {
  7926. return Engine._ALPHA_MAXIMIZED;
  7927. },
  7928. enumerable: true,
  7929. configurable: true
  7930. });
  7931. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7932. get: function () {
  7933. return Engine._ALPHA_PREMULTIPLIED;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7939. get: function () {
  7940. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7946. get: function () {
  7947. return Engine._ALPHA_INTERPOLATE;
  7948. },
  7949. enumerable: true,
  7950. configurable: true
  7951. });
  7952. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7953. get: function () {
  7954. return Engine._ALPHA_SCREENMODE;
  7955. },
  7956. enumerable: true,
  7957. configurable: true
  7958. });
  7959. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7960. get: function () {
  7961. return Engine._DELAYLOADSTATE_NONE;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7967. get: function () {
  7968. return Engine._DELAYLOADSTATE_LOADED;
  7969. },
  7970. enumerable: true,
  7971. configurable: true
  7972. });
  7973. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7974. get: function () {
  7975. return Engine._DELAYLOADSTATE_LOADING;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7981. get: function () {
  7982. return Engine._DELAYLOADSTATE_NOTLOADED;
  7983. },
  7984. enumerable: true,
  7985. configurable: true
  7986. });
  7987. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7988. get: function () {
  7989. return Engine._TEXTUREFORMAT_ALPHA;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7995. get: function () {
  7996. return Engine._TEXTUREFORMAT_LUMINANCE;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8002. get: function () {
  8003. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8004. },
  8005. enumerable: true,
  8006. configurable: true
  8007. });
  8008. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8009. get: function () {
  8010. return Engine._TEXTUREFORMAT_RGB;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8016. get: function () {
  8017. return Engine._TEXTUREFORMAT_RGBA;
  8018. },
  8019. enumerable: true,
  8020. configurable: true
  8021. });
  8022. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8023. get: function () {
  8024. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8030. get: function () {
  8031. return Engine._TEXTURETYPE_FLOAT;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8037. get: function () {
  8038. return Engine._TEXTURETYPE_HALF_FLOAT;
  8039. },
  8040. enumerable: true,
  8041. configurable: true
  8042. });
  8043. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8044. get: function () {
  8045. return Engine._SCALEMODE_FLOOR;
  8046. },
  8047. enumerable: true,
  8048. configurable: true
  8049. });
  8050. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8051. get: function () {
  8052. return Engine._SCALEMODE_NEAREST;
  8053. },
  8054. enumerable: true,
  8055. configurable: true
  8056. });
  8057. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8058. get: function () {
  8059. return Engine._SCALEMODE_CEILING;
  8060. },
  8061. enumerable: true,
  8062. configurable: true
  8063. });
  8064. Object.defineProperty(Engine, "Version", {
  8065. get: function () {
  8066. return "3.1-alpha";
  8067. },
  8068. enumerable: true,
  8069. configurable: true
  8070. });
  8071. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8072. get: function () {
  8073. return this._webGLVersion < 2 || this.forcePOTTextures;
  8074. },
  8075. enumerable: true,
  8076. configurable: true
  8077. });
  8078. Object.defineProperty(Engine.prototype, "badOS", {
  8079. get: function () {
  8080. return this._badOS;
  8081. },
  8082. enumerable: true,
  8083. configurable: true
  8084. });
  8085. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8086. get: function () {
  8087. return this._badDesktopOS;
  8088. },
  8089. enumerable: true,
  8090. configurable: true
  8091. });
  8092. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8093. get: function () {
  8094. return this._performanceMonitor;
  8095. },
  8096. enumerable: true,
  8097. configurable: true
  8098. });
  8099. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8100. get: function () {
  8101. return this._texturesSupported;
  8102. },
  8103. enumerable: true,
  8104. configurable: true
  8105. });
  8106. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8107. get: function () {
  8108. return this._textureFormatInUse;
  8109. },
  8110. enumerable: true,
  8111. configurable: true
  8112. });
  8113. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8114. // Empty texture
  8115. get: function () {
  8116. if (!this._emptyTexture) {
  8117. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8118. }
  8119. return this._emptyTexture;
  8120. },
  8121. enumerable: true,
  8122. configurable: true
  8123. });
  8124. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8125. get: function () {
  8126. if (!this._emptyCubeTexture) {
  8127. var faceData = new Uint8Array(4);
  8128. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8129. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8130. }
  8131. return this._emptyCubeTexture;
  8132. },
  8133. enumerable: true,
  8134. configurable: true
  8135. });
  8136. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8137. get: function () {
  8138. return this._webGLVersion;
  8139. },
  8140. enumerable: true,
  8141. configurable: true
  8142. });
  8143. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8144. /**
  8145. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8146. */
  8147. get: function () {
  8148. return this._isStencilEnable;
  8149. },
  8150. enumerable: true,
  8151. configurable: true
  8152. });
  8153. Engine.prototype._prepareWorkingCanvas = function () {
  8154. if (this._workingCanvas) {
  8155. return;
  8156. }
  8157. this._workingCanvas = document.createElement("canvas");
  8158. this._workingContext = this._workingCanvas.getContext("2d");
  8159. };
  8160. Engine.prototype.resetTextureCache = function () {
  8161. for (var index = 0; index < this._maxTextureChannels; index++) {
  8162. this._activeTexturesCache[index] = null;
  8163. }
  8164. };
  8165. Engine.prototype.getGlInfo = function () {
  8166. return {
  8167. vendor: this._glVendor,
  8168. renderer: this._glRenderer,
  8169. version: this._glVersion
  8170. };
  8171. };
  8172. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8173. if (useScreen === void 0) { useScreen = false; }
  8174. var viewport = camera.viewport;
  8175. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8176. };
  8177. Engine.prototype.getRenderWidth = function (useScreen) {
  8178. if (useScreen === void 0) { useScreen = false; }
  8179. if (!useScreen && this._currentRenderTarget) {
  8180. return this._currentRenderTarget._width;
  8181. }
  8182. return this._gl.drawingBufferWidth;
  8183. };
  8184. Engine.prototype.getRenderHeight = function (useScreen) {
  8185. if (useScreen === void 0) { useScreen = false; }
  8186. if (!useScreen && this._currentRenderTarget) {
  8187. return this._currentRenderTarget._height;
  8188. }
  8189. return this._gl.drawingBufferHeight;
  8190. };
  8191. Engine.prototype.getRenderingCanvas = function () {
  8192. return this._renderingCanvas;
  8193. };
  8194. Engine.prototype.getRenderingCanvasClientRect = function () {
  8195. return this._renderingCanvas.getBoundingClientRect();
  8196. };
  8197. Engine.prototype.setHardwareScalingLevel = function (level) {
  8198. this._hardwareScalingLevel = level;
  8199. this.resize();
  8200. };
  8201. Engine.prototype.getHardwareScalingLevel = function () {
  8202. return this._hardwareScalingLevel;
  8203. };
  8204. Engine.prototype.getLoadedTexturesCache = function () {
  8205. return this._loadedTexturesCache;
  8206. };
  8207. Engine.prototype.getCaps = function () {
  8208. return this._caps;
  8209. };
  8210. Object.defineProperty(Engine.prototype, "drawCalls", {
  8211. /** The number of draw calls submitted last frame */
  8212. get: function () {
  8213. return this._drawCalls.current;
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8219. get: function () {
  8220. return this._drawCalls;
  8221. },
  8222. enumerable: true,
  8223. configurable: true
  8224. });
  8225. Engine.prototype.getDepthFunction = function () {
  8226. return this._depthCullingState.depthFunc;
  8227. };
  8228. Engine.prototype.setDepthFunction = function (depthFunc) {
  8229. this._depthCullingState.depthFunc = depthFunc;
  8230. };
  8231. Engine.prototype.setDepthFunctionToGreater = function () {
  8232. this._depthCullingState.depthFunc = this._gl.GREATER;
  8233. };
  8234. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8235. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8236. };
  8237. Engine.prototype.setDepthFunctionToLess = function () {
  8238. this._depthCullingState.depthFunc = this._gl.LESS;
  8239. };
  8240. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8241. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8242. };
  8243. Engine.prototype.getStencilBuffer = function () {
  8244. return this._stencilState.stencilTest;
  8245. };
  8246. Engine.prototype.setStencilBuffer = function (enable) {
  8247. this._stencilState.stencilTest = enable;
  8248. };
  8249. Engine.prototype.getStencilMask = function () {
  8250. return this._stencilState.stencilMask;
  8251. };
  8252. Engine.prototype.setStencilMask = function (mask) {
  8253. this._stencilState.stencilMask = mask;
  8254. };
  8255. Engine.prototype.getStencilFunction = function () {
  8256. return this._stencilState.stencilFunc;
  8257. };
  8258. Engine.prototype.getStencilFunctionReference = function () {
  8259. return this._stencilState.stencilFuncRef;
  8260. };
  8261. Engine.prototype.getStencilFunctionMask = function () {
  8262. return this._stencilState.stencilFuncMask;
  8263. };
  8264. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8265. this._stencilState.stencilFunc = stencilFunc;
  8266. };
  8267. Engine.prototype.setStencilFunctionReference = function (reference) {
  8268. this._stencilState.stencilFuncRef = reference;
  8269. };
  8270. Engine.prototype.setStencilFunctionMask = function (mask) {
  8271. this._stencilState.stencilFuncMask = mask;
  8272. };
  8273. Engine.prototype.getStencilOperationFail = function () {
  8274. return this._stencilState.stencilOpStencilFail;
  8275. };
  8276. Engine.prototype.getStencilOperationDepthFail = function () {
  8277. return this._stencilState.stencilOpDepthFail;
  8278. };
  8279. Engine.prototype.getStencilOperationPass = function () {
  8280. return this._stencilState.stencilOpStencilDepthPass;
  8281. };
  8282. Engine.prototype.setStencilOperationFail = function (operation) {
  8283. this._stencilState.stencilOpStencilFail = operation;
  8284. };
  8285. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8286. this._stencilState.stencilOpDepthFail = operation;
  8287. };
  8288. Engine.prototype.setStencilOperationPass = function (operation) {
  8289. this._stencilState.stencilOpStencilDepthPass = operation;
  8290. };
  8291. Engine.prototype.setDitheringState = function (value) {
  8292. if (value) {
  8293. this._gl.enable(this._gl.DITHER);
  8294. }
  8295. else {
  8296. this._gl.disable(this._gl.DITHER);
  8297. }
  8298. };
  8299. /**
  8300. * stop executing a render loop function and remove it from the execution array
  8301. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8302. */
  8303. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8304. if (!renderFunction) {
  8305. this._activeRenderLoops = [];
  8306. return;
  8307. }
  8308. var index = this._activeRenderLoops.indexOf(renderFunction);
  8309. if (index >= 0) {
  8310. this._activeRenderLoops.splice(index, 1);
  8311. }
  8312. };
  8313. Engine.prototype._renderLoop = function () {
  8314. var shouldRender = true;
  8315. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8316. shouldRender = false;
  8317. }
  8318. if (shouldRender) {
  8319. // Start new frame
  8320. this.beginFrame();
  8321. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8322. var renderFunction = this._activeRenderLoops[index];
  8323. renderFunction();
  8324. }
  8325. // Present
  8326. this.endFrame();
  8327. }
  8328. if (this._activeRenderLoops.length > 0) {
  8329. // Register new frame
  8330. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8331. }
  8332. else {
  8333. this._renderingQueueLaunched = false;
  8334. }
  8335. };
  8336. /**
  8337. * Register and execute a render loop. The engine can have more than one render function.
  8338. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8339. * @example
  8340. * engine.runRenderLoop(function () {
  8341. * scene.render()
  8342. * })
  8343. */
  8344. Engine.prototype.runRenderLoop = function (renderFunction) {
  8345. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8346. return;
  8347. }
  8348. this._activeRenderLoops.push(renderFunction);
  8349. if (!this._renderingQueueLaunched) {
  8350. this._renderingQueueLaunched = true;
  8351. this._bindedRenderFunction = this._renderLoop.bind(this);
  8352. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8353. }
  8354. };
  8355. /**
  8356. * Toggle full screen mode.
  8357. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8358. * @param {any} options - an options object to be sent to the requestFullscreen function
  8359. */
  8360. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8361. if (this.isFullscreen) {
  8362. BABYLON.Tools.ExitFullscreen();
  8363. }
  8364. else {
  8365. this._pointerLockRequested = requestPointerLock;
  8366. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8367. }
  8368. };
  8369. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8370. if (stencil === void 0) { stencil = false; }
  8371. this.applyStates();
  8372. var mode = 0;
  8373. if (backBuffer && color) {
  8374. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8375. mode |= this._gl.COLOR_BUFFER_BIT;
  8376. }
  8377. if (depth) {
  8378. this._gl.clearDepth(1.0);
  8379. mode |= this._gl.DEPTH_BUFFER_BIT;
  8380. }
  8381. if (stencil) {
  8382. this._gl.clearStencil(0);
  8383. mode |= this._gl.STENCIL_BUFFER_BIT;
  8384. }
  8385. this._gl.clear(mode);
  8386. };
  8387. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8388. var gl = this._gl;
  8389. // Save state
  8390. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8391. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8392. // Change state
  8393. gl.enable(gl.SCISSOR_TEST);
  8394. gl.scissor(x, y, width, height);
  8395. // Clear
  8396. this.clear(clearColor, true, true, true);
  8397. // Restore state
  8398. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8399. if (curScissor === true) {
  8400. gl.enable(gl.SCISSOR_TEST);
  8401. }
  8402. else {
  8403. gl.disable(gl.SCISSOR_TEST);
  8404. }
  8405. };
  8406. /**
  8407. * Set the WebGL's viewport
  8408. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8409. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8410. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8411. */
  8412. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8413. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8414. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8415. var x = viewport.x || 0;
  8416. var y = viewport.y || 0;
  8417. this._cachedViewport = viewport;
  8418. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8419. };
  8420. /**
  8421. * Directly set the WebGL Viewport
  8422. * The x, y, width & height are directly passed to the WebGL call
  8423. * @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.
  8424. */
  8425. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8426. var currentViewport = this._cachedViewport;
  8427. this._cachedViewport = null;
  8428. this._gl.viewport(x, y, width, height);
  8429. return currentViewport;
  8430. };
  8431. Engine.prototype.beginFrame = function () {
  8432. this._measureFps();
  8433. };
  8434. Engine.prototype.endFrame = function () {
  8435. //force a flush in case we are using a bad OS.
  8436. if (this._badOS) {
  8437. this.flushFramebuffer();
  8438. }
  8439. //submit frame to the vr device, if enabled
  8440. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8441. this._vrDisplayEnabled.submitFrame();
  8442. }
  8443. };
  8444. /**
  8445. * resize the view according to the canvas' size.
  8446. * @example
  8447. * window.addEventListener("resize", function () {
  8448. * engine.resize();
  8449. * });
  8450. */
  8451. Engine.prototype.resize = function () {
  8452. // We're not resizing the size of the canvas while in VR mode & presenting
  8453. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8454. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8455. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8456. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8457. }
  8458. };
  8459. /**
  8460. * force a specific size of the canvas
  8461. * @param {number} width - the new canvas' width
  8462. * @param {number} height - the new canvas' height
  8463. */
  8464. Engine.prototype.setSize = function (width, height) {
  8465. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8466. return;
  8467. }
  8468. this._renderingCanvas.width = width;
  8469. this._renderingCanvas.height = height;
  8470. for (var index = 0; index < this.scenes.length; index++) {
  8471. var scene = this.scenes[index];
  8472. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8473. var cam = scene.cameras[camIndex];
  8474. cam._currentRenderId = 0;
  8475. }
  8476. }
  8477. if (this.onResizeObservable.hasObservers) {
  8478. this.onResizeObservable.notifyObservers(this);
  8479. }
  8480. };
  8481. //WebVR functions
  8482. Engine.prototype.isVRDevicePresent = function (callback) {
  8483. this.getVRDevice(null, function (device) {
  8484. callback(device !== null);
  8485. });
  8486. };
  8487. Engine.prototype.getVRDevice = function (name, callback) {
  8488. if (!this.vrDisplaysPromise) {
  8489. callback(null);
  8490. return;
  8491. }
  8492. this.vrDisplaysPromise.then(function (devices) {
  8493. if (devices.length > 0) {
  8494. if (name) {
  8495. var found = devices.some(function (device) {
  8496. if (device.displayName === name) {
  8497. callback(device);
  8498. return true;
  8499. }
  8500. else {
  8501. return false;
  8502. }
  8503. });
  8504. if (!found) {
  8505. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8506. callback(devices[0]);
  8507. }
  8508. }
  8509. else {
  8510. //choose the first one
  8511. callback(devices[0]);
  8512. }
  8513. }
  8514. else {
  8515. BABYLON.Tools.Error("No WebVR devices found!");
  8516. callback(null);
  8517. }
  8518. });
  8519. };
  8520. Engine.prototype.initWebVR = function () {
  8521. if (!this.vrDisplaysPromise) {
  8522. this._getVRDisplays();
  8523. }
  8524. };
  8525. Engine.prototype.enableVR = function (vrDevice) {
  8526. this._vrDisplayEnabled = vrDevice;
  8527. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8528. };
  8529. Engine.prototype.disableVR = function () {
  8530. if (this._vrDisplayEnabled) {
  8531. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8532. }
  8533. };
  8534. Engine.prototype._getVRDisplays = function () {
  8535. var _this = this;
  8536. var getWebVRDevices = function (devices) {
  8537. var size = devices.length;
  8538. var i = 0;
  8539. _this._vrDisplays = devices.filter(function (device) {
  8540. return devices[i] instanceof VRDisplay;
  8541. });
  8542. return _this._vrDisplays;
  8543. };
  8544. //using a key due to typescript
  8545. if (navigator.getVRDisplays) {
  8546. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8547. }
  8548. };
  8549. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8550. if (this._currentRenderTarget) {
  8551. this.unBindFramebuffer(this._currentRenderTarget);
  8552. }
  8553. this._currentRenderTarget = texture;
  8554. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8555. var gl = this._gl;
  8556. if (texture.isCube) {
  8557. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8558. }
  8559. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8560. this.wipeCaches();
  8561. };
  8562. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8563. if (this._currentFramebuffer !== framebuffer) {
  8564. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8565. this._currentFramebuffer = framebuffer;
  8566. }
  8567. };
  8568. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8569. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8570. this._currentRenderTarget = null;
  8571. // If MSAA, we need to bitblt back to main texture
  8572. var gl = this._gl;
  8573. if (texture._MSAAFramebuffer) {
  8574. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8575. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8576. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8577. }
  8578. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8579. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8580. gl.generateMipmap(gl.TEXTURE_2D);
  8581. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8582. }
  8583. if (onBeforeUnbind) {
  8584. if (texture._MSAAFramebuffer) {
  8585. // Bind the correct framebuffer
  8586. this.bindUnboundFramebuffer(texture._framebuffer);
  8587. }
  8588. onBeforeUnbind();
  8589. }
  8590. this.bindUnboundFramebuffer(null);
  8591. };
  8592. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8593. if (texture.generateMipMaps) {
  8594. var gl = this._gl;
  8595. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8596. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8597. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8598. }
  8599. };
  8600. Engine.prototype.flushFramebuffer = function () {
  8601. this._gl.flush();
  8602. };
  8603. Engine.prototype.restoreDefaultFramebuffer = function () {
  8604. if (this._currentRenderTarget) {
  8605. this.unBindFramebuffer(this._currentRenderTarget);
  8606. }
  8607. else {
  8608. this.bindUnboundFramebuffer(null);
  8609. }
  8610. if (this._cachedViewport) {
  8611. this.setViewport(this._cachedViewport);
  8612. }
  8613. this.wipeCaches();
  8614. };
  8615. // UBOs
  8616. Engine.prototype.createUniformBuffer = function (elements) {
  8617. var ubo = this._gl.createBuffer();
  8618. this.bindUniformBuffer(ubo);
  8619. if (elements instanceof Float32Array) {
  8620. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8621. }
  8622. else {
  8623. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8624. }
  8625. this.bindUniformBuffer(null);
  8626. ubo.references = 1;
  8627. return ubo;
  8628. };
  8629. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8630. var ubo = this._gl.createBuffer();
  8631. this.bindUniformBuffer(ubo);
  8632. if (elements instanceof Float32Array) {
  8633. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8634. }
  8635. else {
  8636. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8637. }
  8638. this.bindUniformBuffer(null);
  8639. ubo.references = 1;
  8640. return ubo;
  8641. };
  8642. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8643. this.bindUniformBuffer(uniformBuffer);
  8644. if (offset === undefined) {
  8645. offset = 0;
  8646. }
  8647. if (count === undefined) {
  8648. if (elements instanceof Float32Array) {
  8649. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8650. }
  8651. else {
  8652. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8653. }
  8654. }
  8655. else {
  8656. if (elements instanceof Float32Array) {
  8657. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8658. }
  8659. else {
  8660. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8661. }
  8662. }
  8663. this.bindUniformBuffer(null);
  8664. };
  8665. // VBOs
  8666. Engine.prototype._resetVertexBufferBinding = function () {
  8667. this.bindArrayBuffer(null);
  8668. this._cachedVertexBuffers = null;
  8669. };
  8670. Engine.prototype.createVertexBuffer = function (vertices) {
  8671. var vbo = this._gl.createBuffer();
  8672. this.bindArrayBuffer(vbo);
  8673. if (vertices instanceof Float32Array) {
  8674. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8675. }
  8676. else {
  8677. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8678. }
  8679. this._resetVertexBufferBinding();
  8680. vbo.references = 1;
  8681. return vbo;
  8682. };
  8683. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8684. var vbo = this._gl.createBuffer();
  8685. this.bindArrayBuffer(vbo);
  8686. if (vertices instanceof Float32Array) {
  8687. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8688. }
  8689. else {
  8690. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8691. }
  8692. this._resetVertexBufferBinding();
  8693. vbo.references = 1;
  8694. return vbo;
  8695. };
  8696. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8697. this.bindArrayBuffer(vertexBuffer);
  8698. if (offset === undefined) {
  8699. offset = 0;
  8700. }
  8701. if (count === undefined) {
  8702. if (vertices instanceof Float32Array) {
  8703. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8704. }
  8705. else {
  8706. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8707. }
  8708. }
  8709. else {
  8710. if (vertices instanceof Float32Array) {
  8711. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8712. }
  8713. else {
  8714. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8715. }
  8716. }
  8717. this._resetVertexBufferBinding();
  8718. };
  8719. Engine.prototype._resetIndexBufferBinding = function () {
  8720. this.bindIndexBuffer(null);
  8721. this._cachedIndexBuffer = null;
  8722. };
  8723. Engine.prototype.createIndexBuffer = function (indices) {
  8724. var vbo = this._gl.createBuffer();
  8725. this.bindIndexBuffer(vbo);
  8726. // Check for 32 bits indices
  8727. var arrayBuffer;
  8728. var need32Bits = false;
  8729. if (indices instanceof Uint16Array) {
  8730. arrayBuffer = indices;
  8731. }
  8732. else {
  8733. //check 32 bit support
  8734. if (this._caps.uintIndices) {
  8735. if (indices instanceof Uint32Array) {
  8736. arrayBuffer = indices;
  8737. need32Bits = true;
  8738. }
  8739. else {
  8740. //number[] or Int32Array, check if 32 bit is necessary
  8741. for (var index = 0; index < indices.length; index++) {
  8742. if (indices[index] > 65535) {
  8743. need32Bits = true;
  8744. break;
  8745. }
  8746. }
  8747. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8748. }
  8749. }
  8750. else {
  8751. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8752. arrayBuffer = new Uint16Array(indices);
  8753. }
  8754. }
  8755. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8756. this._resetIndexBufferBinding();
  8757. vbo.references = 1;
  8758. vbo.is32Bits = need32Bits;
  8759. return vbo;
  8760. };
  8761. Engine.prototype.bindArrayBuffer = function (buffer) {
  8762. if (!this._vaoRecordInProgress) {
  8763. this._unbindVertexArrayObject();
  8764. }
  8765. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8766. };
  8767. Engine.prototype.bindUniformBuffer = function (buffer) {
  8768. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8769. };
  8770. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8771. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8772. };
  8773. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8774. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8775. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8776. };
  8777. ;
  8778. Engine.prototype.bindIndexBuffer = function (buffer) {
  8779. if (!this._vaoRecordInProgress) {
  8780. this._unbindVertexArrayObject();
  8781. }
  8782. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8783. };
  8784. Engine.prototype.bindBuffer = function (buffer, target) {
  8785. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8786. this._gl.bindBuffer(target, buffer);
  8787. this._currentBoundBuffer[target] = buffer;
  8788. }
  8789. };
  8790. Engine.prototype.updateArrayBuffer = function (data) {
  8791. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8792. };
  8793. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8794. var pointer = this._currentBufferPointers[indx];
  8795. var changed = false;
  8796. if (!pointer.active) {
  8797. changed = true;
  8798. pointer.active = true;
  8799. pointer.index = indx;
  8800. pointer.size = size;
  8801. pointer.type = type;
  8802. pointer.normalized = normalized;
  8803. pointer.stride = stride;
  8804. pointer.offset = offset;
  8805. pointer.buffer = buffer;
  8806. }
  8807. else {
  8808. if (pointer.buffer !== buffer) {
  8809. pointer.buffer = buffer;
  8810. changed = true;
  8811. }
  8812. if (pointer.size !== size) {
  8813. pointer.size = size;
  8814. changed = true;
  8815. }
  8816. if (pointer.type !== type) {
  8817. pointer.type = type;
  8818. changed = true;
  8819. }
  8820. if (pointer.normalized !== normalized) {
  8821. pointer.normalized = normalized;
  8822. changed = true;
  8823. }
  8824. if (pointer.stride !== stride) {
  8825. pointer.stride = stride;
  8826. changed = true;
  8827. }
  8828. if (pointer.offset !== offset) {
  8829. pointer.offset = offset;
  8830. changed = true;
  8831. }
  8832. }
  8833. if (changed || this._vaoRecordInProgress) {
  8834. this.bindArrayBuffer(buffer);
  8835. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8836. }
  8837. };
  8838. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8839. if (indexBuffer == null) {
  8840. return;
  8841. }
  8842. if (this._cachedIndexBuffer !== indexBuffer) {
  8843. this._cachedIndexBuffer = indexBuffer;
  8844. this.bindIndexBuffer(indexBuffer);
  8845. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8846. }
  8847. };
  8848. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8849. var attributes = effect.getAttributesNames();
  8850. if (!this._vaoRecordInProgress) {
  8851. this._unbindVertexArrayObject();
  8852. }
  8853. this.unbindAllAttributes();
  8854. for (var index = 0; index < attributes.length; index++) {
  8855. var order = effect.getAttributeLocation(index);
  8856. if (order >= 0) {
  8857. var vertexBuffer = vertexBuffers[attributes[index]];
  8858. if (!vertexBuffer) {
  8859. continue;
  8860. }
  8861. this._gl.enableVertexAttribArray(order);
  8862. if (!this._vaoRecordInProgress) {
  8863. this._vertexAttribArraysEnabled[order] = true;
  8864. }
  8865. var buffer = vertexBuffer.getBuffer();
  8866. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8867. if (vertexBuffer.getIsInstanced()) {
  8868. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8869. if (!this._vaoRecordInProgress) {
  8870. this._currentInstanceLocations.push(order);
  8871. this._currentInstanceBuffers.push(buffer);
  8872. }
  8873. }
  8874. }
  8875. }
  8876. };
  8877. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8878. var vao = this._gl.createVertexArray();
  8879. this._vaoRecordInProgress = true;
  8880. this._gl.bindVertexArray(vao);
  8881. this._mustWipeVertexAttributes = true;
  8882. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8883. this.bindIndexBuffer(indexBuffer);
  8884. this._vaoRecordInProgress = false;
  8885. this._gl.bindVertexArray(null);
  8886. return vao;
  8887. };
  8888. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8889. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8890. this._cachedVertexArrayObject = vertexArrayObject;
  8891. this._gl.bindVertexArray(vertexArrayObject);
  8892. this._cachedVertexBuffers = null;
  8893. this._cachedIndexBuffer = null;
  8894. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8895. this._mustWipeVertexAttributes = true;
  8896. }
  8897. };
  8898. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8899. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8900. this._cachedVertexBuffers = vertexBuffer;
  8901. this._cachedEffectForVertexBuffers = effect;
  8902. var attributesCount = effect.getAttributesCount();
  8903. this._unbindVertexArrayObject();
  8904. this.unbindAllAttributes();
  8905. var offset = 0;
  8906. for (var index = 0; index < attributesCount; index++) {
  8907. if (index < vertexDeclaration.length) {
  8908. var order = effect.getAttributeLocation(index);
  8909. if (order >= 0) {
  8910. this._gl.enableVertexAttribArray(order);
  8911. this._vertexAttribArraysEnabled[order] = true;
  8912. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8913. }
  8914. offset += vertexDeclaration[index] * 4;
  8915. }
  8916. }
  8917. }
  8918. this._bindIndexBufferWithCache(indexBuffer);
  8919. };
  8920. Engine.prototype._unbindVertexArrayObject = function () {
  8921. if (!this._cachedVertexArrayObject) {
  8922. return;
  8923. }
  8924. this._cachedVertexArrayObject = null;
  8925. this._gl.bindVertexArray(null);
  8926. };
  8927. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8928. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8929. this._cachedVertexBuffers = vertexBuffers;
  8930. this._cachedEffectForVertexBuffers = effect;
  8931. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8932. }
  8933. this._bindIndexBufferWithCache(indexBuffer);
  8934. };
  8935. Engine.prototype.unbindInstanceAttributes = function () {
  8936. var boundBuffer;
  8937. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8938. var instancesBuffer = this._currentInstanceBuffers[i];
  8939. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8940. boundBuffer = instancesBuffer;
  8941. this.bindArrayBuffer(instancesBuffer);
  8942. }
  8943. var offsetLocation = this._currentInstanceLocations[i];
  8944. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8945. }
  8946. this._currentInstanceBuffers.length = 0;
  8947. this._currentInstanceLocations.length = 0;
  8948. };
  8949. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8950. this._gl.deleteVertexArray(vao);
  8951. };
  8952. Engine.prototype._releaseBuffer = function (buffer) {
  8953. buffer.references--;
  8954. if (buffer.references === 0) {
  8955. this._gl.deleteBuffer(buffer);
  8956. return true;
  8957. }
  8958. return false;
  8959. };
  8960. Engine.prototype.createInstancesBuffer = function (capacity) {
  8961. var buffer = this._gl.createBuffer();
  8962. buffer.capacity = capacity;
  8963. this.bindArrayBuffer(buffer);
  8964. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8965. return buffer;
  8966. };
  8967. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8968. this._gl.deleteBuffer(buffer);
  8969. };
  8970. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8971. this.bindArrayBuffer(instancesBuffer);
  8972. if (data) {
  8973. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8974. }
  8975. if (offsetLocations[0].index !== undefined) {
  8976. var stride = 0;
  8977. for (var i = 0; i < offsetLocations.length; i++) {
  8978. var ai = offsetLocations[i];
  8979. stride += ai.attributeSize * 4;
  8980. }
  8981. for (var i = 0; i < offsetLocations.length; i++) {
  8982. var ai = offsetLocations[i];
  8983. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8984. this._gl.enableVertexAttribArray(ai.index);
  8985. this._vertexAttribArraysEnabled[ai.index] = true;
  8986. }
  8987. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8988. this._gl.vertexAttribDivisor(ai.index, 1);
  8989. this._currentInstanceLocations.push(ai.index);
  8990. this._currentInstanceBuffers.push(instancesBuffer);
  8991. }
  8992. }
  8993. else {
  8994. for (var index = 0; index < 4; index++) {
  8995. var offsetLocation = offsetLocations[index];
  8996. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8997. this._gl.enableVertexAttribArray(offsetLocation);
  8998. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8999. }
  9000. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9001. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9002. this._currentInstanceLocations.push(offsetLocation);
  9003. this._currentInstanceBuffers.push(instancesBuffer);
  9004. }
  9005. }
  9006. };
  9007. Engine.prototype.applyStates = function () {
  9008. this._depthCullingState.apply(this._gl);
  9009. this._stencilState.apply(this._gl);
  9010. this._alphaState.apply(this._gl);
  9011. };
  9012. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9013. // Apply states
  9014. this.applyStates();
  9015. this._drawCalls.addCount(1, false);
  9016. // Render
  9017. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9018. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9019. if (instancesCount) {
  9020. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9021. return;
  9022. }
  9023. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9024. };
  9025. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9026. // Apply states
  9027. this.applyStates();
  9028. this._drawCalls.addCount(1, false);
  9029. if (instancesCount) {
  9030. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9031. return;
  9032. }
  9033. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9034. };
  9035. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9036. // Apply states
  9037. this.applyStates();
  9038. this._drawCalls.addCount(1, false);
  9039. if (instancesCount) {
  9040. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9041. return;
  9042. }
  9043. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9044. };
  9045. // Shaders
  9046. Engine.prototype._releaseEffect = function (effect) {
  9047. if (this._compiledEffects[effect._key]) {
  9048. delete this._compiledEffects[effect._key];
  9049. if (effect.getProgram()) {
  9050. this._gl.deleteProgram(effect.getProgram());
  9051. }
  9052. }
  9053. };
  9054. /**
  9055. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9056. * @param samplers An array of string used to represent textures
  9057. */
  9058. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9059. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9060. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9061. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9062. if (this._compiledEffects[name]) {
  9063. var compiledEffect = this._compiledEffects[name];
  9064. if (onCompiled && compiledEffect.isReady()) {
  9065. onCompiled(compiledEffect);
  9066. }
  9067. return compiledEffect;
  9068. }
  9069. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9070. effect._key = name;
  9071. this._compiledEffects[name] = effect;
  9072. return effect;
  9073. };
  9074. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9075. if (uniformsNames === void 0) { uniformsNames = []; }
  9076. if (samplers === void 0) { samplers = []; }
  9077. if (defines === void 0) { defines = ""; }
  9078. return this.createEffect({
  9079. vertex: "particles",
  9080. fragmentElement: fragmentName
  9081. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9082. };
  9083. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9084. context = context || this._gl;
  9085. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9086. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9087. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9088. var shaderProgram = context.createProgram();
  9089. context.attachShader(shaderProgram, vertexShader);
  9090. context.attachShader(shaderProgram, fragmentShader);
  9091. context.linkProgram(shaderProgram);
  9092. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9093. if (!linked) {
  9094. context.validateProgram(shaderProgram);
  9095. var error = context.getProgramInfoLog(shaderProgram);
  9096. if (error) {
  9097. throw new Error(error);
  9098. }
  9099. }
  9100. context.deleteShader(vertexShader);
  9101. context.deleteShader(fragmentShader);
  9102. return shaderProgram;
  9103. };
  9104. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9105. var results = [];
  9106. for (var index = 0; index < uniformsNames.length; index++) {
  9107. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9108. }
  9109. return results;
  9110. };
  9111. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9112. var results = [];
  9113. for (var index = 0; index < attributesNames.length; index++) {
  9114. try {
  9115. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9116. }
  9117. catch (e) {
  9118. results.push(-1);
  9119. }
  9120. }
  9121. return results;
  9122. };
  9123. Engine.prototype.enableEffect = function (effect) {
  9124. // Use program
  9125. this.setProgram(effect.getProgram());
  9126. this._currentEffect = effect;
  9127. if (effect.onBind) {
  9128. effect.onBind(effect);
  9129. }
  9130. effect.onBindObservable.notifyObservers(effect);
  9131. };
  9132. Engine.prototype.setIntArray = function (uniform, array) {
  9133. if (!uniform)
  9134. return;
  9135. this._gl.uniform1iv(uniform, array);
  9136. };
  9137. Engine.prototype.setIntArray2 = function (uniform, array) {
  9138. if (!uniform || array.length % 2 !== 0)
  9139. return;
  9140. this._gl.uniform2iv(uniform, array);
  9141. };
  9142. Engine.prototype.setIntArray3 = function (uniform, array) {
  9143. if (!uniform || array.length % 3 !== 0)
  9144. return;
  9145. this._gl.uniform3iv(uniform, array);
  9146. };
  9147. Engine.prototype.setIntArray4 = function (uniform, array) {
  9148. if (!uniform || array.length % 4 !== 0)
  9149. return;
  9150. this._gl.uniform4iv(uniform, array);
  9151. };
  9152. Engine.prototype.setFloatArray = function (uniform, array) {
  9153. if (!uniform)
  9154. return;
  9155. this._gl.uniform1fv(uniform, array);
  9156. };
  9157. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9158. if (!uniform || array.length % 2 !== 0)
  9159. return;
  9160. this._gl.uniform2fv(uniform, array);
  9161. };
  9162. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9163. if (!uniform || array.length % 3 !== 0)
  9164. return;
  9165. this._gl.uniform3fv(uniform, array);
  9166. };
  9167. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9168. if (!uniform || array.length % 4 !== 0)
  9169. return;
  9170. this._gl.uniform4fv(uniform, array);
  9171. };
  9172. Engine.prototype.setArray = function (uniform, array) {
  9173. if (!uniform)
  9174. return;
  9175. this._gl.uniform1fv(uniform, array);
  9176. };
  9177. Engine.prototype.setArray2 = function (uniform, array) {
  9178. if (!uniform || array.length % 2 !== 0)
  9179. return;
  9180. this._gl.uniform2fv(uniform, array);
  9181. };
  9182. Engine.prototype.setArray3 = function (uniform, array) {
  9183. if (!uniform || array.length % 3 !== 0)
  9184. return;
  9185. this._gl.uniform3fv(uniform, array);
  9186. };
  9187. Engine.prototype.setArray4 = function (uniform, array) {
  9188. if (!uniform || array.length % 4 !== 0)
  9189. return;
  9190. this._gl.uniform4fv(uniform, array);
  9191. };
  9192. Engine.prototype.setMatrices = function (uniform, matrices) {
  9193. if (!uniform)
  9194. return;
  9195. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9196. };
  9197. Engine.prototype.setMatrix = function (uniform, matrix) {
  9198. if (!uniform)
  9199. return;
  9200. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9201. };
  9202. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9203. if (!uniform)
  9204. return;
  9205. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9206. };
  9207. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9208. if (!uniform)
  9209. return;
  9210. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9211. };
  9212. Engine.prototype.setFloat = function (uniform, value) {
  9213. if (!uniform)
  9214. return;
  9215. this._gl.uniform1f(uniform, value);
  9216. };
  9217. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9218. if (!uniform)
  9219. return;
  9220. this._gl.uniform2f(uniform, x, y);
  9221. };
  9222. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9223. if (!uniform)
  9224. return;
  9225. this._gl.uniform3f(uniform, x, y, z);
  9226. };
  9227. Engine.prototype.setBool = function (uniform, bool) {
  9228. if (!uniform)
  9229. return;
  9230. this._gl.uniform1i(uniform, bool);
  9231. };
  9232. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9233. if (!uniform)
  9234. return;
  9235. this._gl.uniform4f(uniform, x, y, z, w);
  9236. };
  9237. Engine.prototype.setColor3 = function (uniform, color3) {
  9238. if (!uniform)
  9239. return;
  9240. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9241. };
  9242. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9243. if (!uniform)
  9244. return;
  9245. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9246. };
  9247. // States
  9248. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9249. if (zOffset === void 0) { zOffset = 0; }
  9250. if (reverseSide === void 0) { reverseSide = false; }
  9251. // Culling
  9252. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9253. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9254. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9255. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9256. if (culling) {
  9257. this._depthCullingState.cullFace = cullFace;
  9258. this._depthCullingState.cull = true;
  9259. }
  9260. else {
  9261. this._depthCullingState.cull = false;
  9262. }
  9263. }
  9264. // Z offset
  9265. this.setZOffset(zOffset);
  9266. };
  9267. Engine.prototype.setZOffset = function (value) {
  9268. this._depthCullingState.zOffset = value;
  9269. };
  9270. Engine.prototype.getZOffset = function () {
  9271. return this._depthCullingState.zOffset;
  9272. };
  9273. Engine.prototype.setDepthBuffer = function (enable) {
  9274. this._depthCullingState.depthTest = enable;
  9275. };
  9276. Engine.prototype.getDepthWrite = function () {
  9277. return this._depthCullingState.depthMask;
  9278. };
  9279. Engine.prototype.setDepthWrite = function (enable) {
  9280. this._depthCullingState.depthMask = enable;
  9281. };
  9282. Engine.prototype.setColorWrite = function (enable) {
  9283. this._gl.colorMask(enable, enable, enable, enable);
  9284. };
  9285. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9286. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9287. };
  9288. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9289. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9290. if (this._alphaMode === mode) {
  9291. return;
  9292. }
  9293. switch (mode) {
  9294. case Engine.ALPHA_DISABLE:
  9295. this._alphaState.alphaBlend = false;
  9296. break;
  9297. case Engine.ALPHA_PREMULTIPLIED:
  9298. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9299. this._alphaState.alphaBlend = true;
  9300. break;
  9301. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9302. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9303. this._alphaState.alphaBlend = true;
  9304. break;
  9305. case Engine.ALPHA_COMBINE:
  9306. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9307. this._alphaState.alphaBlend = true;
  9308. break;
  9309. case Engine.ALPHA_ONEONE:
  9310. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9311. this._alphaState.alphaBlend = true;
  9312. break;
  9313. case Engine.ALPHA_ADD:
  9314. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9315. this._alphaState.alphaBlend = true;
  9316. break;
  9317. case Engine.ALPHA_SUBTRACT:
  9318. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9319. this._alphaState.alphaBlend = true;
  9320. break;
  9321. case Engine.ALPHA_MULTIPLY:
  9322. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9323. this._alphaState.alphaBlend = true;
  9324. break;
  9325. case Engine.ALPHA_MAXIMIZED:
  9326. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9327. this._alphaState.alphaBlend = true;
  9328. break;
  9329. case Engine.ALPHA_INTERPOLATE:
  9330. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9331. this._alphaState.alphaBlend = true;
  9332. break;
  9333. case Engine.ALPHA_SCREENMODE:
  9334. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9335. this._alphaState.alphaBlend = true;
  9336. break;
  9337. }
  9338. if (!noDepthWriteChange) {
  9339. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9340. }
  9341. this._alphaMode = mode;
  9342. };
  9343. Engine.prototype.getAlphaMode = function () {
  9344. return this._alphaMode;
  9345. };
  9346. Engine.prototype.setAlphaTesting = function (enable) {
  9347. this._alphaTest = enable;
  9348. };
  9349. Engine.prototype.getAlphaTesting = function () {
  9350. return !!this._alphaTest;
  9351. };
  9352. // Textures
  9353. Engine.prototype.wipeCaches = function (bruteForce) {
  9354. if (this.preventCacheWipeBetweenFrames) {
  9355. return;
  9356. }
  9357. this.resetTextureCache();
  9358. this._currentEffect = null;
  9359. // 6/8/2017: deltakosh: Should not be required anymore.
  9360. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9361. if (bruteForce) {
  9362. this._currentProgram = null;
  9363. this._stencilState.reset();
  9364. this._depthCullingState.reset();
  9365. this.setDepthFunctionToLessOrEqual();
  9366. this._alphaState.reset();
  9367. }
  9368. this._cachedVertexBuffers = null;
  9369. this._cachedIndexBuffer = null;
  9370. this._cachedEffectForVertexBuffers = null;
  9371. this._unbindVertexArrayObject();
  9372. this.bindIndexBuffer(null);
  9373. this.bindArrayBuffer(null);
  9374. };
  9375. /**
  9376. * Set the compressed texture format to use, based on the formats you have, and the formats
  9377. * supported by the hardware / browser.
  9378. *
  9379. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9380. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9381. * to API arguments needed to compressed textures. This puts the burden on the container
  9382. * generator to house the arcane code for determining these for current & future formats.
  9383. *
  9384. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9385. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9386. *
  9387. * Note: The result of this call is not taken into account when a texture is base64.
  9388. *
  9389. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9390. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9391. *
  9392. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9393. * @returns The extension selected.
  9394. */
  9395. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9396. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9397. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9398. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9399. return this._textureFormatInUse = this._texturesSupported[i];
  9400. }
  9401. }
  9402. }
  9403. // actively set format to nothing, to allow this to be called more than once
  9404. // and possibly fail the 2nd time
  9405. return this._textureFormatInUse = null;
  9406. };
  9407. /**
  9408. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9409. * @param {string} urlArg- This contains one of the following:
  9410. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9411. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9412. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9413. *
  9414. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9415. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9416. * @param {Scene} scene- Needed for loading to the correct scene.
  9417. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9418. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9419. * @param {callback} onError- Optional callback to be called upon failure.
  9420. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9421. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9422. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9423. *
  9424. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9425. */
  9426. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9427. var _this = this;
  9428. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9429. if (onLoad === void 0) { onLoad = null; }
  9430. if (onError === void 0) { onError = null; }
  9431. if (buffer === void 0) { buffer = null; }
  9432. var texture = fallBack ? fallBack : this._gl.createTexture();
  9433. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9434. var fromData = url.substr(0, 5) === "data:";
  9435. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9436. // establish the file extension, if possible
  9437. var lastDot = url.lastIndexOf('.');
  9438. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9439. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9440. var isTGA = (extension === ".tga");
  9441. // determine if a ktx file should be substituted
  9442. var isKTX = false;
  9443. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9444. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9445. isKTX = true;
  9446. }
  9447. scene._addPendingData(texture);
  9448. texture.url = url;
  9449. texture.generateMipMaps = !noMipmap;
  9450. texture.references = 1;
  9451. texture.samplingMode = samplingMode;
  9452. texture.onLoadedCallbacks = [];
  9453. if (onLoad) {
  9454. texture.onLoadedCallbacks.push(onLoad);
  9455. }
  9456. if (!fallBack)
  9457. this._loadedTexturesCache.push(texture);
  9458. var onerror = function () {
  9459. scene._removePendingData(texture);
  9460. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9461. if (isKTX) {
  9462. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9463. }
  9464. else if (onError) {
  9465. onError();
  9466. }
  9467. };
  9468. var callback;
  9469. // processing for non-image formats
  9470. if (isKTX || isTGA || isDDS) {
  9471. if (isKTX) {
  9472. callback = function (data) {
  9473. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9474. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9475. ktx.uploadLevels(_this._gl, !noMipmap);
  9476. }, samplingMode);
  9477. };
  9478. }
  9479. else if (isTGA) {
  9480. callback = function (arrayBuffer) {
  9481. var data = new Uint8Array(arrayBuffer);
  9482. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9483. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9484. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9485. }, samplingMode);
  9486. };
  9487. }
  9488. else if (isDDS) {
  9489. callback = function (data) {
  9490. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9491. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9492. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9493. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 1);
  9494. }, samplingMode);
  9495. };
  9496. }
  9497. if (!buffer) {
  9498. BABYLON.Tools.LoadFile(url, function (data) {
  9499. callback(data);
  9500. }, null, scene.database, true, onerror);
  9501. }
  9502. else {
  9503. callback(buffer);
  9504. }
  9505. // image format processing
  9506. }
  9507. else {
  9508. var onload = function (img) {
  9509. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9510. var isPot = (img.width === potWidth && img.height === potHeight);
  9511. if (!isPot) {
  9512. _this._prepareWorkingCanvas();
  9513. _this._workingCanvas.width = potWidth;
  9514. _this._workingCanvas.height = potHeight;
  9515. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9516. _this._workingContext.imageSmoothingEnabled = false;
  9517. _this._workingContext.mozImageSmoothingEnabled = false;
  9518. _this._workingContext.oImageSmoothingEnabled = false;
  9519. _this._workingContext.webkitImageSmoothingEnabled = false;
  9520. _this._workingContext.msImageSmoothingEnabled = false;
  9521. }
  9522. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9523. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9524. _this._workingContext.imageSmoothingEnabled = true;
  9525. _this._workingContext.mozImageSmoothingEnabled = true;
  9526. _this._workingContext.oImageSmoothingEnabled = true;
  9527. _this._workingContext.webkitImageSmoothingEnabled = true;
  9528. _this._workingContext.msImageSmoothingEnabled = true;
  9529. }
  9530. }
  9531. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9532. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9533. }, samplingMode);
  9534. };
  9535. if (!fromData || isBase64)
  9536. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9537. else if (buffer instanceof Array || typeof buffer === "string")
  9538. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9539. else
  9540. onload(buffer);
  9541. }
  9542. return texture;
  9543. };
  9544. Engine.prototype._getInternalFormat = function (format) {
  9545. var internalFormat = this._gl.RGBA;
  9546. switch (format) {
  9547. case Engine.TEXTUREFORMAT_ALPHA:
  9548. internalFormat = this._gl.ALPHA;
  9549. break;
  9550. case Engine.TEXTUREFORMAT_LUMINANCE:
  9551. internalFormat = this._gl.LUMINANCE;
  9552. break;
  9553. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9554. internalFormat = this._gl.LUMINANCE_ALPHA;
  9555. break;
  9556. case Engine.TEXTUREFORMAT_RGB:
  9557. internalFormat = this._gl.RGB;
  9558. break;
  9559. case Engine.TEXTUREFORMAT_RGBA:
  9560. internalFormat = this._gl.RGBA;
  9561. break;
  9562. }
  9563. return internalFormat;
  9564. };
  9565. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9566. if (compression === void 0) { compression = null; }
  9567. var internalFormat = this._getInternalFormat(format);
  9568. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9569. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9570. if (texture._width % 4 !== 0) {
  9571. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9572. }
  9573. if (compression) {
  9574. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9575. }
  9576. else {
  9577. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9578. }
  9579. if (texture.generateMipMaps) {
  9580. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9581. }
  9582. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9583. this.resetTextureCache();
  9584. texture.isReady = true;
  9585. };
  9586. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9587. if (compression === void 0) { compression = null; }
  9588. var texture = this._gl.createTexture();
  9589. texture._baseWidth = width;
  9590. texture._baseHeight = height;
  9591. texture._width = width;
  9592. texture._height = height;
  9593. texture.references = 1;
  9594. this.updateRawTexture(texture, data, format, invertY, compression);
  9595. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9596. // Filters
  9597. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9600. if (generateMipMaps) {
  9601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9602. }
  9603. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9604. texture.samplingMode = samplingMode;
  9605. this._loadedTexturesCache.push(texture);
  9606. return texture;
  9607. };
  9608. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9609. var texture = this._gl.createTexture();
  9610. texture._baseWidth = width;
  9611. texture._baseHeight = height;
  9612. if (generateMipMaps) {
  9613. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9614. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9615. }
  9616. this.resetTextureCache();
  9617. texture._width = width;
  9618. texture._height = height;
  9619. texture.isReady = false;
  9620. texture.generateMipMaps = generateMipMaps;
  9621. texture.references = 1;
  9622. texture.samplingMode = samplingMode;
  9623. this.updateTextureSamplingMode(samplingMode, texture);
  9624. this._loadedTexturesCache.push(texture);
  9625. return texture;
  9626. };
  9627. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9628. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9629. if (texture.isCube) {
  9630. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9631. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9632. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9633. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9634. }
  9635. else {
  9636. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9637. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9638. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9639. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9640. }
  9641. texture.samplingMode = samplingMode;
  9642. };
  9643. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9644. if (premulAlpha === void 0) { premulAlpha = false; }
  9645. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9646. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9647. if (premulAlpha) {
  9648. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9649. }
  9650. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9651. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9652. if (texture.generateMipMaps) {
  9653. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9654. }
  9655. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9656. if (premulAlpha) {
  9657. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9658. }
  9659. this.resetTextureCache();
  9660. texture.isReady = true;
  9661. };
  9662. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9663. if (texture._isDisabled) {
  9664. return;
  9665. }
  9666. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9667. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9668. try {
  9669. // Testing video texture support
  9670. if (this._videoTextureSupported === undefined) {
  9671. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9672. if (this._gl.getError() !== 0) {
  9673. this._videoTextureSupported = false;
  9674. }
  9675. else {
  9676. this._videoTextureSupported = true;
  9677. }
  9678. }
  9679. // Copy video through the current working canvas if video texture is not supported
  9680. if (!this._videoTextureSupported) {
  9681. if (!texture._workingCanvas) {
  9682. texture._workingCanvas = document.createElement("canvas");
  9683. texture._workingContext = texture._workingCanvas.getContext("2d");
  9684. texture._workingCanvas.width = texture._width;
  9685. texture._workingCanvas.height = texture._height;
  9686. }
  9687. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9688. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9689. }
  9690. else {
  9691. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9692. }
  9693. if (texture.generateMipMaps) {
  9694. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9695. }
  9696. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9697. this.resetTextureCache();
  9698. texture.isReady = true;
  9699. }
  9700. catch (ex) {
  9701. // Something unexpected
  9702. // Let's disable the texture
  9703. texture._isDisabled = true;
  9704. }
  9705. };
  9706. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9707. // old version had a "generateMipMaps" arg instead of options.
  9708. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9709. // in the same way, generateDepthBuffer is defaulted to true
  9710. var generateMipMaps = false;
  9711. var generateDepthBuffer = true;
  9712. var generateStencilBuffer = false;
  9713. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9714. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9715. if (options !== undefined) {
  9716. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9717. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9718. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9719. type = options.type === undefined ? type : options.type;
  9720. if (options.samplingMode !== undefined) {
  9721. samplingMode = options.samplingMode;
  9722. }
  9723. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9724. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9725. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9726. }
  9727. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9728. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9729. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9730. }
  9731. }
  9732. var gl = this._gl;
  9733. var texture = gl.createTexture();
  9734. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9735. var width = size.width || size;
  9736. var height = size.height || size;
  9737. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9738. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9739. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9740. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9741. }
  9742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9746. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9747. // Create the framebuffer
  9748. var framebuffer = gl.createFramebuffer();
  9749. this.bindUnboundFramebuffer(framebuffer);
  9750. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9751. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9752. if (generateMipMaps) {
  9753. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9754. }
  9755. // Unbind
  9756. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9757. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9758. this.bindUnboundFramebuffer(null);
  9759. texture._framebuffer = framebuffer;
  9760. texture._baseWidth = width;
  9761. texture._baseHeight = height;
  9762. texture._width = width;
  9763. texture._height = height;
  9764. texture.isReady = true;
  9765. texture.samples = 1;
  9766. texture.generateMipMaps = generateMipMaps;
  9767. texture.references = 1;
  9768. texture.samplingMode = samplingMode;
  9769. texture.type = type;
  9770. texture._generateDepthBuffer = generateDepthBuffer;
  9771. texture._generateStencilBuffer = generateStencilBuffer;
  9772. this.resetTextureCache();
  9773. this._loadedTexturesCache.push(texture);
  9774. return texture;
  9775. };
  9776. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9777. var generateMipMaps = false;
  9778. var generateDepthBuffer = true;
  9779. var generateStencilBuffer = false;
  9780. var generateDepthTexture = false;
  9781. var textureCount = 1;
  9782. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9783. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9784. var types = [], samplingModes = [];
  9785. if (options !== undefined) {
  9786. generateMipMaps = options.generateMipMaps;
  9787. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9788. generateStencilBuffer = options.generateStencilBuffer;
  9789. generateDepthTexture = options.generateDepthTexture;
  9790. textureCount = options.textureCount || 1;
  9791. if (options.types) {
  9792. types = options.types;
  9793. }
  9794. if (options.samplingModes) {
  9795. samplingModes = options.samplingModes;
  9796. }
  9797. }
  9798. var gl = this._gl;
  9799. // Create the framebuffer
  9800. var framebuffer = gl.createFramebuffer();
  9801. this.bindUnboundFramebuffer(framebuffer);
  9802. var width = size.width || size;
  9803. var height = size.height || size;
  9804. var textures = [];
  9805. var attachments = [];
  9806. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9807. for (var i = 0; i < textureCount; i++) {
  9808. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9809. var type = types[i] || defaultType;
  9810. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9811. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9812. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9813. }
  9814. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9815. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9816. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9817. }
  9818. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9819. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9820. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9821. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9822. }
  9823. var texture = gl.createTexture();
  9824. var attachment = gl["COLOR_ATTACHMENT" + i];
  9825. textures.push(texture);
  9826. attachments.push(attachment);
  9827. gl.activeTexture(gl["TEXTURE" + i]);
  9828. gl.bindTexture(gl.TEXTURE_2D, texture);
  9829. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9830. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9833. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9834. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9835. if (generateMipMaps) {
  9836. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9837. }
  9838. // Unbind
  9839. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9840. texture._framebuffer = framebuffer;
  9841. texture._depthStencilBuffer = depthStencilBuffer;
  9842. texture._baseWidth = width;
  9843. texture._baseHeight = height;
  9844. texture._width = width;
  9845. texture._height = height;
  9846. texture.isReady = true;
  9847. texture.samples = 1;
  9848. texture.generateMipMaps = generateMipMaps;
  9849. texture.references = 1;
  9850. texture.samplingMode = samplingMode;
  9851. texture.type = type;
  9852. texture._generateDepthBuffer = generateDepthBuffer;
  9853. texture._generateStencilBuffer = generateStencilBuffer;
  9854. this._loadedTexturesCache.push(texture);
  9855. }
  9856. if (generateDepthTexture) {
  9857. // Depth texture
  9858. var depthTexture = gl.createTexture();
  9859. gl.activeTexture(gl.TEXTURE0);
  9860. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9861. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9862. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9863. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9864. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9865. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9866. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9867. depthTexture._framebuffer = framebuffer;
  9868. depthTexture._baseWidth = width;
  9869. depthTexture._baseHeight = height;
  9870. depthTexture._width = width;
  9871. depthTexture._height = height;
  9872. depthTexture.isReady = true;
  9873. depthTexture.samples = 1;
  9874. depthTexture.generateMipMaps = generateMipMaps;
  9875. depthTexture.references = 1;
  9876. depthTexture.samplingMode = gl.NEAREST;
  9877. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9878. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9879. textures.push(depthTexture);
  9880. this._loadedTexturesCache.push(depthTexture);
  9881. }
  9882. gl.drawBuffers(attachments);
  9883. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9884. this.bindUnboundFramebuffer(null);
  9885. this.resetTextureCache();
  9886. return textures;
  9887. };
  9888. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9889. if (samples === void 0) { samples = 1; }
  9890. var depthStencilBuffer = null;
  9891. var gl = this._gl;
  9892. // Create the depth/stencil buffer
  9893. if (generateStencilBuffer) {
  9894. depthStencilBuffer = gl.createRenderbuffer();
  9895. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9896. if (samples > 1) {
  9897. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  9898. }
  9899. else {
  9900. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9901. }
  9902. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9903. }
  9904. else if (generateDepthBuffer) {
  9905. depthStencilBuffer = gl.createRenderbuffer();
  9906. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9907. if (samples > 1) {
  9908. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9909. }
  9910. else {
  9911. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9912. }
  9913. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9914. }
  9915. return depthStencilBuffer;
  9916. };
  9917. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9918. if (this.webGLVersion < 2) {
  9919. return 1;
  9920. }
  9921. if (texture.samples === samples) {
  9922. return samples;
  9923. }
  9924. var gl = this._gl;
  9925. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9926. // Dispose previous render buffers
  9927. if (texture._depthStencilBuffer) {
  9928. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9929. }
  9930. if (texture._MSAAFramebuffer) {
  9931. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9932. }
  9933. if (texture._MSAARenderBuffer) {
  9934. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9935. }
  9936. if (samples > 1) {
  9937. texture._MSAAFramebuffer = gl.createFramebuffer();
  9938. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9939. var colorRenderbuffer = gl.createRenderbuffer();
  9940. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9941. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9942. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9943. texture._MSAARenderBuffer = colorRenderbuffer;
  9944. }
  9945. else {
  9946. this.bindUnboundFramebuffer(texture._framebuffer);
  9947. }
  9948. texture.samples = samples;
  9949. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9950. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9951. this.bindUnboundFramebuffer(null);
  9952. return samples;
  9953. };
  9954. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  9955. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  9956. };
  9957. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  9958. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  9959. };
  9960. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9961. var gl = this._gl;
  9962. var texture = gl.createTexture();
  9963. var generateMipMaps = true;
  9964. var generateDepthBuffer = true;
  9965. var generateStencilBuffer = false;
  9966. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9967. if (options !== undefined) {
  9968. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9969. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9970. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9971. if (options.samplingMode !== undefined) {
  9972. samplingMode = options.samplingMode;
  9973. }
  9974. }
  9975. texture.isCube = true;
  9976. texture.references = 1;
  9977. texture.generateMipMaps = generateMipMaps;
  9978. texture.references = 1;
  9979. texture.samples = 1;
  9980. texture.samplingMode = samplingMode;
  9981. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9983. for (var face = 0; face < 6; face++) {
  9984. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9985. }
  9986. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9990. // Create the framebuffer
  9991. var framebuffer = gl.createFramebuffer();
  9992. this.bindUnboundFramebuffer(framebuffer);
  9993. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9994. // Mipmaps
  9995. if (texture.generateMipMaps) {
  9996. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9997. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9998. }
  9999. // Unbind
  10000. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10001. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10002. this.bindUnboundFramebuffer(null);
  10003. texture._framebuffer = framebuffer;
  10004. texture._width = size;
  10005. texture._height = size;
  10006. texture.isReady = true;
  10007. this.resetTextureCache();
  10008. this._loadedTexturesCache.push(texture);
  10009. return texture;
  10010. };
  10011. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10012. var _this = this;
  10013. if (onError === void 0) { onError = null; }
  10014. if (forcedExtension === void 0) { forcedExtension = null; }
  10015. var callback = function (loadData) {
  10016. if (_this._caps.textureLOD || !loadData) {
  10017. // Do not add extra process if texture lod is supported.
  10018. if (onLoad) {
  10019. onLoad();
  10020. }
  10021. return;
  10022. }
  10023. var mipSlices = 3;
  10024. var gl = _this._gl;
  10025. var width = loadData.width;
  10026. if (!width) {
  10027. return;
  10028. }
  10029. var textures = [];
  10030. for (var i = 0; i < mipSlices; i++) {
  10031. //compute LOD from even spacing in smoothness (matching shader calculation)
  10032. var smoothness = i / (mipSlices - 1);
  10033. var roughness = 1 - smoothness;
  10034. var minLODIndex = offset; // roughness = 0
  10035. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10036. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10037. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10038. var glTextureFromLod = gl.createTexture();
  10039. glTextureFromLod.isCube = true;
  10040. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10044. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10045. if (loadData.isDDS) {
  10046. var info = loadData.info;
  10047. var data = loadData.data;
  10048. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10049. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, true, 6, mipmapIndex);
  10050. }
  10051. else {
  10052. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10053. }
  10054. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10055. // Wrap in a base texture for easy binding.
  10056. var lodTexture = new BABYLON.BaseTexture(scene);
  10057. lodTexture.isCube = true;
  10058. lodTexture._texture = glTextureFromLod;
  10059. glTextureFromLod.isReady = true;
  10060. textures.push(lodTexture);
  10061. }
  10062. loadData.texture._lodTextureHigh = textures[2];
  10063. loadData.texture._lodTextureMid = textures[1];
  10064. loadData.texture._lodTextureLow = textures[0];
  10065. if (onLoad) {
  10066. onLoad();
  10067. }
  10068. };
  10069. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10070. };
  10071. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10072. var _this = this;
  10073. if (onLoad === void 0) { onLoad = null; }
  10074. if (onError === void 0) { onError = null; }
  10075. if (forcedExtension === void 0) { forcedExtension = null; }
  10076. var gl = this._gl;
  10077. var texture = gl.createTexture();
  10078. texture.isCube = true;
  10079. texture.url = rootUrl;
  10080. texture.references = 1;
  10081. texture.onLoadedCallbacks = [];
  10082. texture.generateMipMaps = !noMipmap;
  10083. var isKTX = false;
  10084. var isDDS = false;
  10085. var lastDot = rootUrl.lastIndexOf('.');
  10086. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10087. if (this._textureFormatInUse) {
  10088. extension = this._textureFormatInUse;
  10089. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10090. isKTX = true;
  10091. }
  10092. else {
  10093. isDDS = (extension === ".dds");
  10094. }
  10095. if (isKTX) {
  10096. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10097. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10098. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10099. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10100. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10101. ktx.uploadLevels(_this._gl, !noMipmap);
  10102. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10104. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10105. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10106. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10107. _this.resetTextureCache();
  10108. texture._width = ktx.pixelWidth;
  10109. texture._height = ktx.pixelHeight;
  10110. texture.isReady = true;
  10111. }, null, null, true, onError);
  10112. }
  10113. else if (isDDS) {
  10114. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10115. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10116. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10117. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10118. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10119. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  10120. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10121. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10122. }
  10123. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10124. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10127. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10128. _this.resetTextureCache();
  10129. texture._width = info.width;
  10130. texture._height = info.height;
  10131. texture.isReady = true;
  10132. texture.type = info.textureType;
  10133. if (onLoad) {
  10134. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10135. }
  10136. }, null, null, true, onError);
  10137. }
  10138. else {
  10139. cascadeLoad(rootUrl, scene, function (imgs) {
  10140. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10141. var height = width;
  10142. _this._prepareWorkingCanvas();
  10143. _this._workingCanvas.width = width;
  10144. _this._workingCanvas.height = height;
  10145. var faces = [
  10146. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10147. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10148. ];
  10149. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10150. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10151. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10152. for (var index = 0; index < faces.length; index++) {
  10153. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10154. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10155. }
  10156. if (!noMipmap) {
  10157. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10158. }
  10159. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10160. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10163. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10164. _this.resetTextureCache();
  10165. texture._width = width;
  10166. texture._height = height;
  10167. texture.isReady = true;
  10168. texture.onLoadedCallbacks.forEach(function (callback) {
  10169. callback();
  10170. });
  10171. if (onLoad) {
  10172. onLoad();
  10173. }
  10174. }, files, onError);
  10175. }
  10176. this._loadedTexturesCache.push(texture);
  10177. return texture;
  10178. };
  10179. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10180. texture._width = width;
  10181. texture._height = height;
  10182. texture._size = width * height;
  10183. texture._baseWidth = width;
  10184. texture._baseHeight = height;
  10185. };
  10186. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10187. if (compression === void 0) { compression = null; }
  10188. if (level === void 0) { level = 0; }
  10189. var gl = this._gl;
  10190. var textureType = this._getWebGLTextureType(type);
  10191. var internalFormat = this._getInternalFormat(format);
  10192. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10193. var needConversion = false;
  10194. if (internalFormat === gl.RGB) {
  10195. internalFormat = gl.RGBA;
  10196. needConversion = true;
  10197. }
  10198. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10199. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10200. if (texture._width % 4 !== 0) {
  10201. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10202. }
  10203. // Data are known to be in +X +Y +Z -X -Y -Z
  10204. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10205. var faceData = data[faceIndex];
  10206. if (compression) {
  10207. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  10208. }
  10209. else {
  10210. if (needConversion) {
  10211. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  10212. }
  10213. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  10214. }
  10215. }
  10216. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10217. if (isPot && texture.generateMipMaps && level === 0) {
  10218. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10219. }
  10220. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10221. this.resetTextureCache();
  10222. texture.isReady = true;
  10223. };
  10224. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10225. if (compression === void 0) { compression = null; }
  10226. var gl = this._gl;
  10227. var texture = gl.createTexture();
  10228. texture.isCube = true;
  10229. texture.references = 1;
  10230. texture.generateMipMaps = generateMipMaps;
  10231. texture.format = format;
  10232. texture.type = type;
  10233. var textureType = this._getWebGLTextureType(type);
  10234. var internalFormat = this._getInternalFormat(format);
  10235. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10236. var needConversion = false;
  10237. if (internalFormat === gl.RGB) {
  10238. internalFormat = gl.RGBA;
  10239. needConversion = true;
  10240. }
  10241. var width = size;
  10242. var height = width;
  10243. texture._width = width;
  10244. texture._height = height;
  10245. // Double check on POT to generate Mips.
  10246. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10247. if (!isPot) {
  10248. generateMipMaps = false;
  10249. }
  10250. // Upload data if needed. The texture won t be ready until then.
  10251. if (data) {
  10252. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10253. }
  10254. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10255. // Filters
  10256. if (data && generateMipMaps) {
  10257. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10258. }
  10259. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10262. }
  10263. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10266. }
  10267. else {
  10268. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10270. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10271. }
  10272. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10274. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10275. return texture;
  10276. };
  10277. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10278. var _this = this;
  10279. if (onLoad === void 0) { onLoad = null; }
  10280. if (onError === void 0) { onError = null; }
  10281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10282. if (invertY === void 0) { invertY = false; }
  10283. var gl = this._gl;
  10284. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10285. scene._addPendingData(texture);
  10286. texture.url = url;
  10287. this._loadedTexturesCache.push(texture);
  10288. var onerror = function () {
  10289. scene._removePendingData(texture);
  10290. if (onError) {
  10291. onError();
  10292. }
  10293. };
  10294. var internalCallback = function (data) {
  10295. var width = texture._width;
  10296. var height = texture._height;
  10297. var faceDataArrays = callback(data);
  10298. if (mipmmapGenerator) {
  10299. var textureType = _this._getWebGLTextureType(type);
  10300. var internalFormat = _this._getInternalFormat(format);
  10301. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10302. var needConversion = false;
  10303. if (internalFormat === gl.RGB) {
  10304. internalFormat = gl.RGBA;
  10305. needConversion = true;
  10306. }
  10307. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10308. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10309. var mipData = mipmmapGenerator(faceDataArrays);
  10310. for (var level = 0; level < mipData.length; level++) {
  10311. var mipSize = width >> level;
  10312. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10313. var mipFaceData = mipData[level][faceIndex];
  10314. if (needConversion) {
  10315. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10316. }
  10317. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10318. }
  10319. }
  10320. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10321. }
  10322. else {
  10323. texture.generateMipMaps = !noMipmap;
  10324. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10325. }
  10326. texture.isReady = true;
  10327. _this.resetTextureCache();
  10328. scene._removePendingData(texture);
  10329. if (onLoad) {
  10330. onLoad();
  10331. }
  10332. };
  10333. BABYLON.Tools.LoadFile(url, function (data) {
  10334. internalCallback(data);
  10335. }, onerror, scene.database, true);
  10336. return texture;
  10337. };
  10338. ;
  10339. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10340. // Create new RGBA data container.
  10341. var rgbaData;
  10342. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10343. rgbaData = new Float32Array(width * height * 4);
  10344. }
  10345. else {
  10346. rgbaData = new Uint32Array(width * height * 4);
  10347. }
  10348. // Convert each pixel.
  10349. for (var x = 0; x < width; x++) {
  10350. for (var y = 0; y < height; y++) {
  10351. var index = (y * width + x) * 3;
  10352. var newIndex = (y * width + x) * 4;
  10353. // Map Old Value to new value.
  10354. rgbaData[newIndex + 0] = rgbData[index + 0];
  10355. rgbaData[newIndex + 1] = rgbData[index + 1];
  10356. rgbaData[newIndex + 2] = rgbData[index + 2];
  10357. // Add fully opaque alpha channel.
  10358. rgbaData[newIndex + 3] = 1;
  10359. }
  10360. }
  10361. return rgbaData;
  10362. };
  10363. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10364. var gl = this._gl;
  10365. if (texture._framebuffer) {
  10366. gl.deleteFramebuffer(texture._framebuffer);
  10367. texture._framebuffer = null;
  10368. }
  10369. if (texture._depthStencilBuffer) {
  10370. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10371. texture._depthStencilBuffer = null;
  10372. }
  10373. if (texture._MSAAFramebuffer) {
  10374. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10375. texture._MSAAFramebuffer = null;
  10376. }
  10377. if (texture._MSAARenderBuffer) {
  10378. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10379. texture._MSAARenderBuffer = null;
  10380. }
  10381. };
  10382. Engine.prototype._releaseTexture = function (texture) {
  10383. var gl = this._gl;
  10384. this._releaseFramebufferObjects(texture);
  10385. gl.deleteTexture(texture);
  10386. // Unbind channels
  10387. this.unbindAllTextures();
  10388. var index = this._loadedTexturesCache.indexOf(texture);
  10389. if (index !== -1) {
  10390. this._loadedTexturesCache.splice(index, 1);
  10391. }
  10392. // Integrated fixed lod samplers.
  10393. if (texture._lodTextureHigh) {
  10394. texture._lodTextureHigh.dispose();
  10395. }
  10396. if (texture._lodTextureMid) {
  10397. texture._lodTextureMid.dispose();
  10398. }
  10399. if (texture._lodTextureLow) {
  10400. texture._lodTextureLow.dispose();
  10401. }
  10402. };
  10403. Engine.prototype.setProgram = function (program) {
  10404. if (this._currentProgram !== program) {
  10405. this._gl.useProgram(program);
  10406. this._currentProgram = program;
  10407. }
  10408. };
  10409. Engine.prototype.bindSamplers = function (effect) {
  10410. this.setProgram(effect.getProgram());
  10411. var samplers = effect.getSamplers();
  10412. for (var index = 0; index < samplers.length; index++) {
  10413. var uniform = effect.getUniform(samplers[index]);
  10414. this._gl.uniform1i(uniform, index);
  10415. }
  10416. this._currentEffect = null;
  10417. };
  10418. Engine.prototype.activateTexture = function (texture) {
  10419. if (this._activeTexture !== texture) {
  10420. this._gl.activeTexture(texture);
  10421. this._activeTexture = texture;
  10422. }
  10423. };
  10424. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10425. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10426. this._gl.bindTexture(target, texture);
  10427. this._activeTexturesCache[this._activeTexture] = texture;
  10428. }
  10429. };
  10430. Engine.prototype._bindTexture = function (channel, texture) {
  10431. if (channel < 0) {
  10432. return;
  10433. }
  10434. this.activateTexture(this._gl.TEXTURE0 + channel);
  10435. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10436. };
  10437. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10438. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10439. };
  10440. Engine.prototype.unbindAllTextures = function () {
  10441. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10442. this.activateTexture(this._gl["TEXTURE" + channel]);
  10443. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10444. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10445. }
  10446. };
  10447. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10448. if (channel < 0) {
  10449. return;
  10450. }
  10451. this._gl.uniform1i(uniform, channel);
  10452. this._setTexture(channel, texture);
  10453. };
  10454. Engine.prototype._setTexture = function (channel, texture) {
  10455. // Not ready?
  10456. if (!texture) {
  10457. if (this._activeTexturesCache[channel] != null) {
  10458. this.activateTexture(this._gl["TEXTURE" + channel]);
  10459. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10460. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10461. }
  10462. return;
  10463. }
  10464. // Video
  10465. var alreadyActivated = false;
  10466. if (texture.video) {
  10467. this.activateTexture(this._gl["TEXTURE" + channel]);
  10468. alreadyActivated = true;
  10469. texture.update();
  10470. }
  10471. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10472. texture.delayLoad();
  10473. return;
  10474. }
  10475. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10476. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10477. if (this._activeTexturesCache[channel] === internalTexture) {
  10478. return;
  10479. }
  10480. if (!alreadyActivated) {
  10481. this.activateTexture(this._gl["TEXTURE" + channel]);
  10482. }
  10483. if (internalTexture.isCube) {
  10484. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10485. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10486. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10487. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10488. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10489. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10490. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10491. }
  10492. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10493. }
  10494. else {
  10495. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10496. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10497. internalTexture._cachedWrapU = texture.wrapU;
  10498. switch (texture.wrapU) {
  10499. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10500. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10501. break;
  10502. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10503. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10504. break;
  10505. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10506. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10507. break;
  10508. }
  10509. }
  10510. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10511. internalTexture._cachedWrapV = texture.wrapV;
  10512. switch (texture.wrapV) {
  10513. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10514. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10515. break;
  10516. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10517. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10518. break;
  10519. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10520. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10521. break;
  10522. }
  10523. }
  10524. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10525. }
  10526. };
  10527. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10528. if (channel < 0) {
  10529. return;
  10530. }
  10531. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10532. this._textureUnits = new Int32Array(textures.length);
  10533. }
  10534. for (var i = 0; i < textures.length; i++) {
  10535. this._textureUnits[i] = channel + i;
  10536. }
  10537. this._gl.uniform1iv(uniform, this._textureUnits);
  10538. for (var index = 0; index < textures.length; index++) {
  10539. this._setTexture(channel + index, textures[index]);
  10540. }
  10541. };
  10542. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10543. var internalTexture = texture.getInternalTexture();
  10544. if (!internalTexture) {
  10545. return;
  10546. }
  10547. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10548. var value = texture.anisotropicFilteringLevel;
  10549. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10550. value = 1;
  10551. }
  10552. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10553. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10554. texture._cachedAnisotropicFilteringLevel = value;
  10555. }
  10556. };
  10557. Engine.prototype.readPixels = function (x, y, width, height) {
  10558. var data = new Uint8Array(height * width * 4);
  10559. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10560. return data;
  10561. };
  10562. /**
  10563. * Add an externaly attached data from its key.
  10564. * This method call will fail and return false, if such key already exists.
  10565. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10566. * @param key the unique key that identifies the data
  10567. * @param data the data object to associate to the key for this Engine instance
  10568. * @return true if no such key were already present and the data was added successfully, false otherwise
  10569. */
  10570. Engine.prototype.addExternalData = function (key, data) {
  10571. if (!this._externalData) {
  10572. this._externalData = new BABYLON.StringDictionary();
  10573. }
  10574. return this._externalData.add(key, data);
  10575. };
  10576. /**
  10577. * Get an externaly attached data from its key
  10578. * @param key the unique key that identifies the data
  10579. * @return the associated data, if present (can be null), or undefined if not present
  10580. */
  10581. Engine.prototype.getExternalData = function (key) {
  10582. if (!this._externalData) {
  10583. this._externalData = new BABYLON.StringDictionary();
  10584. }
  10585. return this._externalData.get(key);
  10586. };
  10587. /**
  10588. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10589. * @param key the unique key that identifies the data
  10590. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10591. * @return the associated data, can be null if the factory returned null.
  10592. */
  10593. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10594. if (!this._externalData) {
  10595. this._externalData = new BABYLON.StringDictionary();
  10596. }
  10597. return this._externalData.getOrAddWithFactory(key, factory);
  10598. };
  10599. /**
  10600. * Remove an externaly attached data from the Engine instance
  10601. * @param key the unique key that identifies the data
  10602. * @return true if the data was successfully removed, false if it doesn't exist
  10603. */
  10604. Engine.prototype.removeExternalData = function (key) {
  10605. if (!this._externalData) {
  10606. this._externalData = new BABYLON.StringDictionary();
  10607. }
  10608. return this._externalData.remove(key);
  10609. };
  10610. Engine.prototype.releaseInternalTexture = function (texture) {
  10611. if (!texture) {
  10612. return;
  10613. }
  10614. texture.references--;
  10615. // Final reference ?
  10616. if (texture.references === 0) {
  10617. var texturesCache = this.getLoadedTexturesCache();
  10618. var index = texturesCache.indexOf(texture);
  10619. if (index > -1) {
  10620. texturesCache.splice(index, 1);
  10621. }
  10622. this._releaseTexture(texture);
  10623. }
  10624. };
  10625. Engine.prototype.unbindAllAttributes = function () {
  10626. if (this._mustWipeVertexAttributes) {
  10627. this._mustWipeVertexAttributes = false;
  10628. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10629. this._gl.disableVertexAttribArray(i);
  10630. this._vertexAttribArraysEnabled[i] = false;
  10631. this._currentBufferPointers[i].active = false;
  10632. }
  10633. return;
  10634. }
  10635. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10636. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10637. continue;
  10638. }
  10639. this._gl.disableVertexAttribArray(i);
  10640. this._vertexAttribArraysEnabled[i] = false;
  10641. this._currentBufferPointers[i].active = false;
  10642. }
  10643. };
  10644. Engine.prototype.releaseEffects = function () {
  10645. for (var name in this._compiledEffects) {
  10646. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10647. }
  10648. this._compiledEffects = {};
  10649. };
  10650. // Dispose
  10651. Engine.prototype.dispose = function () {
  10652. this.hideLoadingUI();
  10653. this.stopRenderLoop();
  10654. // Empty texture
  10655. if (this._emptyTexture) {
  10656. this._releaseTexture(this._emptyTexture);
  10657. this._emptyTexture = null;
  10658. }
  10659. if (this._emptyCubeTexture) {
  10660. this._releaseTexture(this._emptyCubeTexture);
  10661. this._emptyCubeTexture = null;
  10662. }
  10663. // Release scenes
  10664. while (this.scenes.length) {
  10665. this.scenes[0].dispose();
  10666. }
  10667. // Release audio engine
  10668. if (Engine.audioEngine) {
  10669. Engine.audioEngine.dispose();
  10670. }
  10671. // Release effects
  10672. this.releaseEffects();
  10673. // Unbind
  10674. this.unbindAllAttributes();
  10675. if (this._dummyFramebuffer) {
  10676. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10677. }
  10678. this._gl = null;
  10679. //WebVR
  10680. this.disableVR();
  10681. // Events
  10682. window.removeEventListener("blur", this._onBlur);
  10683. window.removeEventListener("focus", this._onFocus);
  10684. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10685. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10686. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10687. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10688. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10689. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10690. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10691. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10692. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10693. // Remove from Instances
  10694. var index = Engine.Instances.indexOf(this);
  10695. if (index >= 0) {
  10696. Engine.Instances.splice(index, 1);
  10697. }
  10698. };
  10699. // Loading screen
  10700. Engine.prototype.displayLoadingUI = function () {
  10701. var loadingScreen = this.loadingScreen;
  10702. if (loadingScreen) {
  10703. loadingScreen.displayLoadingUI();
  10704. }
  10705. };
  10706. Engine.prototype.hideLoadingUI = function () {
  10707. var loadingScreen = this.loadingScreen;
  10708. if (loadingScreen) {
  10709. loadingScreen.hideLoadingUI();
  10710. }
  10711. };
  10712. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10713. get: function () {
  10714. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10715. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10716. return this._loadingScreen;
  10717. },
  10718. set: function (loadingScreen) {
  10719. this._loadingScreen = loadingScreen;
  10720. },
  10721. enumerable: true,
  10722. configurable: true
  10723. });
  10724. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10725. set: function (text) {
  10726. this.loadingScreen.loadingUIText = text;
  10727. },
  10728. enumerable: true,
  10729. configurable: true
  10730. });
  10731. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10732. set: function (color) {
  10733. this.loadingScreen.loadingUIBackgroundColor = color;
  10734. },
  10735. enumerable: true,
  10736. configurable: true
  10737. });
  10738. Engine.prototype.attachContextLostEvent = function (callback) {
  10739. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10740. };
  10741. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10742. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10743. };
  10744. Engine.prototype.getVertexShaderSource = function (program) {
  10745. var shaders = this._gl.getAttachedShaders(program);
  10746. return this._gl.getShaderSource(shaders[0]);
  10747. };
  10748. Engine.prototype.getFragmentShaderSource = function (program) {
  10749. var shaders = this._gl.getAttachedShaders(program);
  10750. return this._gl.getShaderSource(shaders[1]);
  10751. };
  10752. Engine.prototype.getError = function () {
  10753. return this._gl.getError();
  10754. };
  10755. // FPS
  10756. Engine.prototype.getFps = function () {
  10757. return this._fps;
  10758. };
  10759. Engine.prototype.getDeltaTime = function () {
  10760. return this._deltaTime;
  10761. };
  10762. Engine.prototype._measureFps = function () {
  10763. this._performanceMonitor.sampleFrame();
  10764. this._fps = this._performanceMonitor.averageFPS;
  10765. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10766. };
  10767. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10768. if (faceIndex === void 0) { faceIndex = -1; }
  10769. var gl = this._gl;
  10770. if (!this._dummyFramebuffer) {
  10771. this._dummyFramebuffer = gl.createFramebuffer();
  10772. }
  10773. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10774. if (faceIndex > -1) {
  10775. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10776. }
  10777. else {
  10778. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10779. }
  10780. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10781. var buffer;
  10782. switch (readType) {
  10783. case gl.UNSIGNED_BYTE:
  10784. buffer = new Uint8Array(4 * width * height);
  10785. readType = gl.UNSIGNED_BYTE;
  10786. break;
  10787. default:
  10788. buffer = new Float32Array(4 * width * height);
  10789. readType = gl.FLOAT;
  10790. break;
  10791. }
  10792. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10793. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  10794. return buffer;
  10795. };
  10796. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10797. if (this._webGLVersion > 1) {
  10798. return this._caps.colorBufferFloat;
  10799. }
  10800. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10801. };
  10802. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10803. if (this._webGLVersion > 1) {
  10804. return this._caps.colorBufferFloat;
  10805. }
  10806. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10807. };
  10808. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10809. Engine.prototype._canRenderToFramebuffer = function (type) {
  10810. var gl = this._gl;
  10811. //clear existing errors
  10812. while (gl.getError() !== gl.NO_ERROR) { }
  10813. var successful = true;
  10814. var texture = gl.createTexture();
  10815. gl.bindTexture(gl.TEXTURE_2D, texture);
  10816. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10818. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10819. var fb = gl.createFramebuffer();
  10820. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10821. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10822. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10823. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10824. successful = successful && (gl.getError() === gl.NO_ERROR);
  10825. //try render by clearing frame buffer's color buffer
  10826. if (successful) {
  10827. gl.clear(gl.COLOR_BUFFER_BIT);
  10828. successful = successful && (gl.getError() === gl.NO_ERROR);
  10829. }
  10830. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10831. if (successful) {
  10832. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10833. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10834. var readFormat = gl.RGBA;
  10835. var readType = gl.UNSIGNED_BYTE;
  10836. var buffer = new Uint8Array(4);
  10837. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10838. successful = successful && (gl.getError() === gl.NO_ERROR);
  10839. }
  10840. //clean up
  10841. gl.deleteTexture(texture);
  10842. gl.deleteFramebuffer(fb);
  10843. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10844. //clear accumulated errors
  10845. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10846. return successful;
  10847. };
  10848. Engine.prototype._getWebGLTextureType = function (type) {
  10849. if (type === Engine.TEXTURETYPE_FLOAT) {
  10850. return this._gl.FLOAT;
  10851. }
  10852. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10853. // Add Half Float Constant.
  10854. return this._gl.HALF_FLOAT_OES;
  10855. }
  10856. return this._gl.UNSIGNED_BYTE;
  10857. };
  10858. ;
  10859. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10860. if (this._webGLVersion === 1) {
  10861. return this._gl.RGBA;
  10862. }
  10863. if (type === Engine.TEXTURETYPE_FLOAT) {
  10864. return this._gl.RGBA32F;
  10865. }
  10866. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10867. return this._gl.RGBA16F;
  10868. }
  10869. return this._gl.RGBA;
  10870. };
  10871. ;
  10872. // Statics
  10873. Engine.isSupported = function () {
  10874. try {
  10875. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10876. if (navigator.isCocoonJS) {
  10877. return true;
  10878. }
  10879. var tempcanvas = document.createElement("canvas");
  10880. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10881. return gl != null && !!window.WebGLRenderingContext;
  10882. }
  10883. catch (e) {
  10884. return false;
  10885. }
  10886. };
  10887. return Engine;
  10888. }());
  10889. Engine.Instances = new Array();
  10890. // Const statics
  10891. Engine._ALPHA_DISABLE = 0;
  10892. Engine._ALPHA_ADD = 1;
  10893. Engine._ALPHA_COMBINE = 2;
  10894. Engine._ALPHA_SUBTRACT = 3;
  10895. Engine._ALPHA_MULTIPLY = 4;
  10896. Engine._ALPHA_MAXIMIZED = 5;
  10897. Engine._ALPHA_ONEONE = 6;
  10898. Engine._ALPHA_PREMULTIPLIED = 7;
  10899. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10900. Engine._ALPHA_INTERPOLATE = 9;
  10901. Engine._ALPHA_SCREENMODE = 10;
  10902. Engine._DELAYLOADSTATE_NONE = 0;
  10903. Engine._DELAYLOADSTATE_LOADED = 1;
  10904. Engine._DELAYLOADSTATE_LOADING = 2;
  10905. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10906. Engine._TEXTUREFORMAT_ALPHA = 0;
  10907. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10908. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10909. Engine._TEXTUREFORMAT_RGB = 4;
  10910. Engine._TEXTUREFORMAT_RGBA = 5;
  10911. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10912. Engine._TEXTURETYPE_FLOAT = 1;
  10913. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10914. // Depht or Stencil test Constants.
  10915. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10916. 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.
  10917. 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.
  10918. 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.
  10919. 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.
  10920. 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.
  10921. 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.
  10922. 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.
  10923. // Stencil Actions Constants.
  10924. Engine._KEEP = 0x1E00;
  10925. Engine._REPLACE = 0x1E01;
  10926. Engine._INCR = 0x1E02;
  10927. Engine._DECR = 0x1E03;
  10928. Engine._INVERT = 0x150A;
  10929. Engine._INCR_WRAP = 0x8507;
  10930. Engine._DECR_WRAP = 0x8508;
  10931. // Texture rescaling mode
  10932. Engine._SCALEMODE_FLOOR = 1;
  10933. Engine._SCALEMODE_NEAREST = 2;
  10934. Engine._SCALEMODE_CEILING = 3;
  10935. // Updatable statics so stick with vars here
  10936. Engine.CollisionsEpsilon = 0.001;
  10937. Engine.CodeRepository = "src/";
  10938. Engine.ShadersRepository = "src/Shaders/";
  10939. BABYLON.Engine = Engine;
  10940. })(BABYLON || (BABYLON = {}));
  10941. //# sourceMappingURL=babylon.engine.js.map
  10942. /// <reference path="Tools\babylon.decorators.ts" />
  10943. var BABYLON;
  10944. (function (BABYLON) {
  10945. /**
  10946. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10947. */
  10948. var Node = (function () {
  10949. /**
  10950. * @constructor
  10951. * @param {string} name - the name and id to be given to this node
  10952. * @param {BABYLON.Scene} the scene this node will be added to
  10953. */
  10954. function Node(name, scene) {
  10955. this.state = "";
  10956. this.metadata = null;
  10957. this.doNotSerialize = false;
  10958. this.animations = new Array();
  10959. this._ranges = {};
  10960. this._childrenFlag = -1;
  10961. this._isEnabled = true;
  10962. this._isReady = true;
  10963. this._currentRenderId = -1;
  10964. this._parentRenderId = -1;
  10965. /**
  10966. * An event triggered when the mesh is disposed.
  10967. * @type {BABYLON.Observable}
  10968. */
  10969. this.onDisposeObservable = new BABYLON.Observable();
  10970. this.name = name;
  10971. this.id = name;
  10972. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10973. this._initCache();
  10974. }
  10975. Object.defineProperty(Node.prototype, "parent", {
  10976. get: function () {
  10977. return this._parentNode;
  10978. },
  10979. set: function (parent) {
  10980. if (this._parentNode === parent) {
  10981. return;
  10982. }
  10983. if (this._parentNode) {
  10984. var index = this._parentNode._children.indexOf(this);
  10985. if (index !== -1) {
  10986. this._parentNode._children.splice(index, 1);
  10987. }
  10988. }
  10989. this._parentNode = parent;
  10990. if (this._parentNode) {
  10991. if (!this._parentNode._children) {
  10992. this._parentNode._children = new Array();
  10993. }
  10994. this._parentNode._children.push(this);
  10995. }
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Node.prototype.getClassName = function () {
  11001. return "Node";
  11002. };
  11003. Object.defineProperty(Node.prototype, "onDispose", {
  11004. set: function (callback) {
  11005. if (this._onDisposeObserver) {
  11006. this.onDisposeObservable.remove(this._onDisposeObserver);
  11007. }
  11008. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Node.prototype.getScene = function () {
  11014. return this._scene;
  11015. };
  11016. Node.prototype.getEngine = function () {
  11017. return this._scene.getEngine();
  11018. };
  11019. // override it in derived class
  11020. Node.prototype.getWorldMatrix = function () {
  11021. return BABYLON.Matrix.Identity();
  11022. };
  11023. // override it in derived class if you add new variables to the cache
  11024. // and call the parent class method
  11025. Node.prototype._initCache = function () {
  11026. this._cache = {};
  11027. this._cache.parent = undefined;
  11028. };
  11029. Node.prototype.updateCache = function (force) {
  11030. if (!force && this.isSynchronized())
  11031. return;
  11032. this._cache.parent = this.parent;
  11033. this._updateCache();
  11034. };
  11035. // override it in derived class if you add new variables to the cache
  11036. // and call the parent class method if !ignoreParentClass
  11037. Node.prototype._updateCache = function (ignoreParentClass) {
  11038. };
  11039. // override it in derived class if you add new variables to the cache
  11040. Node.prototype._isSynchronized = function () {
  11041. return true;
  11042. };
  11043. Node.prototype._markSyncedWithParent = function () {
  11044. this._parentRenderId = this.parent._currentRenderId;
  11045. };
  11046. Node.prototype.isSynchronizedWithParent = function () {
  11047. if (!this.parent) {
  11048. return true;
  11049. }
  11050. if (this._parentRenderId !== this.parent._currentRenderId) {
  11051. return false;
  11052. }
  11053. return this.parent.isSynchronized();
  11054. };
  11055. Node.prototype.isSynchronized = function (updateCache) {
  11056. var check = this.hasNewParent();
  11057. check = check || !this.isSynchronizedWithParent();
  11058. check = check || !this._isSynchronized();
  11059. if (updateCache)
  11060. this.updateCache(true);
  11061. return !check;
  11062. };
  11063. Node.prototype.hasNewParent = function (update) {
  11064. if (this._cache.parent === this.parent)
  11065. return false;
  11066. if (update)
  11067. this._cache.parent = this.parent;
  11068. return true;
  11069. };
  11070. /**
  11071. * Is this node ready to be used/rendered
  11072. * @return {boolean} is it ready
  11073. */
  11074. Node.prototype.isReady = function () {
  11075. return this._isReady;
  11076. };
  11077. /**
  11078. * Is this node enabled.
  11079. * If the node has a parent and is enabled, the parent will be inspected as well.
  11080. * @return {boolean} whether this node (and its parent) is enabled.
  11081. * @see setEnabled
  11082. */
  11083. Node.prototype.isEnabled = function () {
  11084. if (!this._isEnabled) {
  11085. return false;
  11086. }
  11087. if (this.parent) {
  11088. return this.parent.isEnabled();
  11089. }
  11090. return true;
  11091. };
  11092. /**
  11093. * Set the enabled state of this node.
  11094. * @param {boolean} value - the new enabled state
  11095. * @see isEnabled
  11096. */
  11097. Node.prototype.setEnabled = function (value) {
  11098. this._isEnabled = value;
  11099. };
  11100. /**
  11101. * Is this node a descendant of the given node.
  11102. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11103. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11104. * @see parent
  11105. */
  11106. Node.prototype.isDescendantOf = function (ancestor) {
  11107. if (this.parent) {
  11108. if (this.parent === ancestor) {
  11109. return true;
  11110. }
  11111. return this.parent.isDescendantOf(ancestor);
  11112. }
  11113. return false;
  11114. };
  11115. /**
  11116. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11117. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11118. * @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.
  11119. * @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.
  11120. */
  11121. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11122. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11123. if (!this._children) {
  11124. return;
  11125. }
  11126. for (var index = 0; index < this._children.length; index++) {
  11127. var item = this._children[index];
  11128. if (!predicate || predicate(item)) {
  11129. results.push(item);
  11130. }
  11131. if (!directDescendantsOnly) {
  11132. item._getDescendants(results, false, predicate);
  11133. }
  11134. }
  11135. };
  11136. /**
  11137. * Will return all nodes that have this node as ascendant.
  11138. * @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.
  11139. * @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.
  11140. * @return {BABYLON.Node[]} all children nodes of all types.
  11141. */
  11142. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11143. var results = [];
  11144. this._getDescendants(results, directDescendantsOnly, predicate);
  11145. return results;
  11146. };
  11147. /**
  11148. * Get all child-meshes of this node.
  11149. */
  11150. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11151. var results = [];
  11152. this._getDescendants(results, directDecendantsOnly, function (node) {
  11153. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11154. });
  11155. return results;
  11156. };
  11157. /**
  11158. * Get all direct children of this node.
  11159. */
  11160. Node.prototype.getChildren = function (predicate) {
  11161. return this.getDescendants(true, predicate);
  11162. };
  11163. Node.prototype._setReady = function (state) {
  11164. if (state === this._isReady) {
  11165. return;
  11166. }
  11167. if (!state) {
  11168. this._isReady = false;
  11169. return;
  11170. }
  11171. this._isReady = true;
  11172. if (this.onReady) {
  11173. this.onReady(this);
  11174. }
  11175. };
  11176. Node.prototype.getAnimationByName = function (name) {
  11177. for (var i = 0; i < this.animations.length; i++) {
  11178. var animation = this.animations[i];
  11179. if (animation.name === name) {
  11180. return animation;
  11181. }
  11182. }
  11183. return null;
  11184. };
  11185. Node.prototype.createAnimationRange = function (name, from, to) {
  11186. // check name not already in use
  11187. if (!this._ranges[name]) {
  11188. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11189. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11190. if (this.animations[i]) {
  11191. this.animations[i].createRange(name, from, to);
  11192. }
  11193. }
  11194. }
  11195. };
  11196. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11197. if (deleteFrames === void 0) { deleteFrames = true; }
  11198. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11199. if (this.animations[i]) {
  11200. this.animations[i].deleteRange(name, deleteFrames);
  11201. }
  11202. }
  11203. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11204. };
  11205. Node.prototype.getAnimationRange = function (name) {
  11206. return this._ranges[name];
  11207. };
  11208. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11209. var range = this.getAnimationRange(name);
  11210. if (!range) {
  11211. return null;
  11212. }
  11213. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11214. };
  11215. Node.prototype.serializeAnimationRanges = function () {
  11216. var serializationRanges = [];
  11217. for (var name in this._ranges) {
  11218. var range = {};
  11219. range.name = name;
  11220. range.from = this._ranges[name].from;
  11221. range.to = this._ranges[name].to;
  11222. serializationRanges.push(range);
  11223. }
  11224. return serializationRanges;
  11225. };
  11226. Node.prototype.dispose = function () {
  11227. this.parent = null;
  11228. // Callback
  11229. this.onDisposeObservable.notifyObservers(this);
  11230. this.onDisposeObservable.clear();
  11231. };
  11232. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11233. if (parsedNode.ranges) {
  11234. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11235. var data = parsedNode.ranges[index];
  11236. node.createAnimationRange(data.name, data.from, data.to);
  11237. }
  11238. }
  11239. };
  11240. return Node;
  11241. }());
  11242. __decorate([
  11243. BABYLON.serialize()
  11244. ], Node.prototype, "name", void 0);
  11245. __decorate([
  11246. BABYLON.serialize()
  11247. ], Node.prototype, "id", void 0);
  11248. __decorate([
  11249. BABYLON.serialize()
  11250. ], Node.prototype, "uniqueId", void 0);
  11251. __decorate([
  11252. BABYLON.serialize()
  11253. ], Node.prototype, "state", void 0);
  11254. __decorate([
  11255. BABYLON.serialize()
  11256. ], Node.prototype, "metadata", void 0);
  11257. BABYLON.Node = Node;
  11258. })(BABYLON || (BABYLON = {}));
  11259. //# sourceMappingURL=babylon.node.js.map
  11260. var BABYLON;
  11261. (function (BABYLON) {
  11262. var BoundingSphere = (function () {
  11263. function BoundingSphere(minimum, maximum) {
  11264. this.minimum = minimum;
  11265. this.maximum = maximum;
  11266. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11267. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11268. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11269. this.radius = distance * 0.5;
  11270. this.centerWorld = BABYLON.Vector3.Zero();
  11271. this._update(BABYLON.Matrix.Identity());
  11272. }
  11273. // Methods
  11274. BoundingSphere.prototype._update = function (world) {
  11275. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11276. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11277. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11278. };
  11279. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11280. for (var i = 0; i < 6; i++) {
  11281. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11282. return false;
  11283. }
  11284. return true;
  11285. };
  11286. BoundingSphere.prototype.intersectsPoint = function (point) {
  11287. var x = this.centerWorld.x - point.x;
  11288. var y = this.centerWorld.y - point.y;
  11289. var z = this.centerWorld.z - point.z;
  11290. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11291. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11292. return false;
  11293. return true;
  11294. };
  11295. // Statics
  11296. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11297. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11298. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11299. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11300. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11301. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11302. return false;
  11303. return true;
  11304. };
  11305. return BoundingSphere;
  11306. }());
  11307. BABYLON.BoundingSphere = BoundingSphere;
  11308. })(BABYLON || (BABYLON = {}));
  11309. //# sourceMappingURL=babylon.boundingSphere.js.map
  11310. var BABYLON;
  11311. (function (BABYLON) {
  11312. var BoundingBox = (function () {
  11313. function BoundingBox(minimum, maximum) {
  11314. this.minimum = minimum;
  11315. this.maximum = maximum;
  11316. this.vectors = new Array();
  11317. this.vectorsWorld = new Array();
  11318. // Bounding vectors
  11319. this.vectors.push(this.minimum.clone());
  11320. this.vectors.push(this.maximum.clone());
  11321. this.vectors.push(this.minimum.clone());
  11322. this.vectors[2].x = this.maximum.x;
  11323. this.vectors.push(this.minimum.clone());
  11324. this.vectors[3].y = this.maximum.y;
  11325. this.vectors.push(this.minimum.clone());
  11326. this.vectors[4].z = this.maximum.z;
  11327. this.vectors.push(this.maximum.clone());
  11328. this.vectors[5].z = this.minimum.z;
  11329. this.vectors.push(this.maximum.clone());
  11330. this.vectors[6].x = this.minimum.x;
  11331. this.vectors.push(this.maximum.clone());
  11332. this.vectors[7].y = this.minimum.y;
  11333. // OBB
  11334. this.center = this.maximum.add(this.minimum).scale(0.5);
  11335. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11336. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11337. // World
  11338. for (var index = 0; index < this.vectors.length; index++) {
  11339. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11340. }
  11341. this.minimumWorld = BABYLON.Vector3.Zero();
  11342. this.maximumWorld = BABYLON.Vector3.Zero();
  11343. this.centerWorld = BABYLON.Vector3.Zero();
  11344. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11345. this._update(BABYLON.Matrix.Identity());
  11346. }
  11347. // Methods
  11348. BoundingBox.prototype.getWorldMatrix = function () {
  11349. return this._worldMatrix;
  11350. };
  11351. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11352. this._worldMatrix.copyFrom(matrix);
  11353. return this;
  11354. };
  11355. BoundingBox.prototype._update = function (world) {
  11356. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11357. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11358. for (var index = 0; index < this.vectors.length; index++) {
  11359. var v = this.vectorsWorld[index];
  11360. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11361. if (v.x < this.minimumWorld.x)
  11362. this.minimumWorld.x = v.x;
  11363. if (v.y < this.minimumWorld.y)
  11364. this.minimumWorld.y = v.y;
  11365. if (v.z < this.minimumWorld.z)
  11366. this.minimumWorld.z = v.z;
  11367. if (v.x > this.maximumWorld.x)
  11368. this.maximumWorld.x = v.x;
  11369. if (v.y > this.maximumWorld.y)
  11370. this.maximumWorld.y = v.y;
  11371. if (v.z > this.maximumWorld.z)
  11372. this.maximumWorld.z = v.z;
  11373. }
  11374. // Extend
  11375. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11376. this.extendSizeWorld.scaleInPlace(0.5);
  11377. // OBB
  11378. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11379. this.centerWorld.scaleInPlace(0.5);
  11380. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11381. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11382. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11383. this._worldMatrix = world;
  11384. };
  11385. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11386. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11387. };
  11388. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11389. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11390. };
  11391. BoundingBox.prototype.intersectsPoint = function (point) {
  11392. var delta = -BABYLON.Epsilon;
  11393. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11394. return false;
  11395. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11396. return false;
  11397. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11398. return false;
  11399. return true;
  11400. };
  11401. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11402. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11403. };
  11404. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11405. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11406. return false;
  11407. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11408. return false;
  11409. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11410. return false;
  11411. return true;
  11412. };
  11413. // Statics
  11414. BoundingBox.Intersects = function (box0, box1) {
  11415. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11416. return false;
  11417. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11418. return false;
  11419. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11420. return false;
  11421. return true;
  11422. };
  11423. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11424. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11425. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11426. return (num <= (sphereRadius * sphereRadius));
  11427. };
  11428. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11429. for (var p = 0; p < 6; p++) {
  11430. for (var i = 0; i < 8; i++) {
  11431. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11432. return false;
  11433. }
  11434. }
  11435. }
  11436. return true;
  11437. };
  11438. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11439. for (var p = 0; p < 6; p++) {
  11440. var inCount = 8;
  11441. for (var i = 0; i < 8; i++) {
  11442. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11443. --inCount;
  11444. }
  11445. else {
  11446. break;
  11447. }
  11448. }
  11449. if (inCount === 0)
  11450. return false;
  11451. }
  11452. return true;
  11453. };
  11454. return BoundingBox;
  11455. }());
  11456. BABYLON.BoundingBox = BoundingBox;
  11457. })(BABYLON || (BABYLON = {}));
  11458. //# sourceMappingURL=babylon.boundingBox.js.map
  11459. var BABYLON;
  11460. (function (BABYLON) {
  11461. var computeBoxExtents = function (axis, box) {
  11462. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11463. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11464. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11465. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11466. var r = r0 + r1 + r2;
  11467. return {
  11468. min: p - r,
  11469. max: p + r
  11470. };
  11471. };
  11472. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11473. var axisOverlap = function (axis, box0, box1) {
  11474. var result0 = computeBoxExtents(axis, box0);
  11475. var result1 = computeBoxExtents(axis, box1);
  11476. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11477. };
  11478. var BoundingInfo = (function () {
  11479. function BoundingInfo(minimum, maximum) {
  11480. this.minimum = minimum;
  11481. this.maximum = maximum;
  11482. this._isLocked = false;
  11483. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11484. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11485. }
  11486. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11487. get: function () {
  11488. return this._isLocked;
  11489. },
  11490. set: function (value) {
  11491. this._isLocked = value;
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. // Methods
  11497. BoundingInfo.prototype.update = function (world) {
  11498. if (this._isLocked) {
  11499. return;
  11500. }
  11501. this.boundingBox._update(world);
  11502. this.boundingSphere._update(world);
  11503. };
  11504. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11505. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11506. return false;
  11507. return this.boundingBox.isInFrustum(frustumPlanes);
  11508. };
  11509. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11510. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11511. };
  11512. BoundingInfo.prototype._checkCollision = function (collider) {
  11513. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11514. };
  11515. BoundingInfo.prototype.intersectsPoint = function (point) {
  11516. if (!this.boundingSphere.centerWorld) {
  11517. return false;
  11518. }
  11519. if (!this.boundingSphere.intersectsPoint(point)) {
  11520. return false;
  11521. }
  11522. if (!this.boundingBox.intersectsPoint(point)) {
  11523. return false;
  11524. }
  11525. return true;
  11526. };
  11527. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11528. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11529. return false;
  11530. }
  11531. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11532. return false;
  11533. }
  11534. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11535. return false;
  11536. }
  11537. if (!precise) {
  11538. return true;
  11539. }
  11540. var box0 = this.boundingBox;
  11541. var box1 = boundingInfo.boundingBox;
  11542. if (!axisOverlap(box0.directions[0], box0, box1))
  11543. return false;
  11544. if (!axisOverlap(box0.directions[1], box0, box1))
  11545. return false;
  11546. if (!axisOverlap(box0.directions[2], box0, box1))
  11547. return false;
  11548. if (!axisOverlap(box1.directions[0], box0, box1))
  11549. return false;
  11550. if (!axisOverlap(box1.directions[1], box0, box1))
  11551. return false;
  11552. if (!axisOverlap(box1.directions[2], box0, box1))
  11553. return false;
  11554. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11555. return false;
  11556. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11557. return false;
  11558. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11559. return false;
  11560. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11561. return false;
  11562. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11563. return false;
  11564. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11565. return false;
  11566. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11567. return false;
  11568. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11569. return false;
  11570. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11571. return false;
  11572. return true;
  11573. };
  11574. return BoundingInfo;
  11575. }());
  11576. BABYLON.BoundingInfo = BoundingInfo;
  11577. })(BABYLON || (BABYLON = {}));
  11578. //# sourceMappingURL=babylon.boundingInfo.js.map
  11579. var BABYLON;
  11580. (function (BABYLON) {
  11581. var AbstractMesh = (function (_super) {
  11582. __extends(AbstractMesh, _super);
  11583. // Constructor
  11584. function AbstractMesh(name, scene) {
  11585. var _this = _super.call(this, name, scene) || this;
  11586. _this._facetNb = 0; // facet number
  11587. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11588. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11589. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11590. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11591. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11592. _this._subDiv = {
  11593. max: 1,
  11594. X: 1,
  11595. Y: 1,
  11596. Z: 1
  11597. };
  11598. // Events
  11599. /**
  11600. * An event triggered when this mesh collides with another one
  11601. * @type {BABYLON.Observable}
  11602. */
  11603. _this.onCollideObservable = new BABYLON.Observable();
  11604. /**
  11605. * An event triggered when the collision's position changes
  11606. * @type {BABYLON.Observable}
  11607. */
  11608. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11609. /**
  11610. * An event triggered after the world matrix is updated
  11611. * @type {BABYLON.Observable}
  11612. */
  11613. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11614. /**
  11615. * An event triggered when material is changed
  11616. * @type {BABYLON.Observable}
  11617. */
  11618. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11619. // Properties
  11620. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11621. _this.position = BABYLON.Vector3.Zero();
  11622. _this._rotation = BABYLON.Vector3.Zero();
  11623. _this._scaling = BABYLON.Vector3.One();
  11624. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11625. _this.visibility = 1.0;
  11626. _this.alphaIndex = Number.MAX_VALUE;
  11627. _this.infiniteDistance = false;
  11628. _this.isVisible = true;
  11629. _this.isPickable = true;
  11630. _this.showBoundingBox = false;
  11631. _this.showSubMeshesBoundingBox = false;
  11632. _this.isBlocker = false;
  11633. _this.enablePointerMoveEvents = false;
  11634. _this.renderingGroupId = 0;
  11635. _this._receiveShadows = false;
  11636. _this.renderOutline = false;
  11637. _this.outlineColor = BABYLON.Color3.Red();
  11638. _this.outlineWidth = 0.02;
  11639. _this.renderOverlay = false;
  11640. _this.overlayColor = BABYLON.Color3.Red();
  11641. _this.overlayAlpha = 0.5;
  11642. _this._hasVertexAlpha = false;
  11643. _this._useVertexColors = true;
  11644. _this._computeBonesUsingShaders = true;
  11645. _this._numBoneInfluencers = 4;
  11646. _this._applyFog = true;
  11647. _this.scalingDeterminant = 1;
  11648. _this.useOctreeForRenderingSelection = true;
  11649. _this.useOctreeForPicking = true;
  11650. _this.useOctreeForCollisions = true;
  11651. _this.layerMask = 0x0FFFFFFF;
  11652. /**
  11653. * True if the mesh must be rendered in any case.
  11654. */
  11655. _this.alwaysSelectAsActiveMesh = false;
  11656. // Collisions
  11657. _this._checkCollisions = false;
  11658. _this._collisionMask = -1;
  11659. _this._collisionGroup = -1;
  11660. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11661. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11662. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11663. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11664. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11665. // Edges
  11666. _this.edgesWidth = 1;
  11667. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11668. // Cache
  11669. _this._localWorld = BABYLON.Matrix.Zero();
  11670. _this._worldMatrix = BABYLON.Matrix.Zero();
  11671. _this._absolutePosition = BABYLON.Vector3.Zero();
  11672. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11673. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11674. _this._isDirty = false;
  11675. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11676. _this._isDisposed = false;
  11677. _this._renderId = 0;
  11678. _this._intersectionsInProgress = new Array();
  11679. _this._isWorldMatrixFrozen = false;
  11680. _this._unIndexed = false;
  11681. _this._lightSources = new Array();
  11682. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11683. if (collidedMesh === void 0) { collidedMesh = null; }
  11684. //TODO move this to the collision coordinator!
  11685. if (_this.getScene().workerCollisions)
  11686. newPosition.multiplyInPlace(_this._collider.radius);
  11687. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11688. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11689. _this.position.addInPlace(_this._diffPositionForCollisions);
  11690. }
  11691. if (collidedMesh) {
  11692. _this.onCollideObservable.notifyObservers(collidedMesh);
  11693. }
  11694. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11695. };
  11696. _this.getScene().addMesh(_this);
  11697. _this._resyncLightSources();
  11698. return _this;
  11699. }
  11700. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11701. get: function () {
  11702. return AbstractMesh._BILLBOARDMODE_NONE;
  11703. },
  11704. enumerable: true,
  11705. configurable: true
  11706. });
  11707. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11708. get: function () {
  11709. return AbstractMesh._BILLBOARDMODE_X;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11715. get: function () {
  11716. return AbstractMesh._BILLBOARDMODE_Y;
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11722. get: function () {
  11723. return AbstractMesh._BILLBOARDMODE_Z;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11729. get: function () {
  11730. return AbstractMesh._BILLBOARDMODE_ALL;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11736. /**
  11737. * Read-only : the number of facets in the mesh
  11738. */
  11739. get: function () {
  11740. return this._facetNb;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11746. /**
  11747. * The number (integer) of subdivisions per axis in the partioning space
  11748. */
  11749. get: function () {
  11750. return this._partitioningSubdivisions;
  11751. },
  11752. set: function (nb) {
  11753. this._partitioningSubdivisions = nb;
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11759. /**
  11760. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11761. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11762. */
  11763. get: function () {
  11764. return this._partitioningBBoxRatio;
  11765. },
  11766. set: function (ratio) {
  11767. this._partitioningBBoxRatio = ratio;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11773. /**
  11774. * Read-only boolean : is the feature facetData enabled ?
  11775. */
  11776. get: function () {
  11777. return this._facetDataEnabled;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11783. set: function (callback) {
  11784. if (this._onCollideObserver) {
  11785. this.onCollideObservable.remove(this._onCollideObserver);
  11786. }
  11787. this._onCollideObserver = this.onCollideObservable.add(callback);
  11788. },
  11789. enumerable: true,
  11790. configurable: true
  11791. });
  11792. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11793. set: function (callback) {
  11794. if (this._onCollisionPositionChangeObserver) {
  11795. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11796. }
  11797. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(AbstractMesh.prototype, "material", {
  11803. get: function () {
  11804. return this._material;
  11805. },
  11806. set: function (value) {
  11807. if (this._material === value) {
  11808. return;
  11809. }
  11810. this._material = value;
  11811. if (this.onMaterialChangedObservable.hasObservers) {
  11812. this.onMaterialChangedObservable.notifyObservers(this);
  11813. }
  11814. if (!this.subMeshes) {
  11815. return;
  11816. }
  11817. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11818. var subMesh = _a[_i];
  11819. subMesh.setEffect(null);
  11820. }
  11821. },
  11822. enumerable: true,
  11823. configurable: true
  11824. });
  11825. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11826. get: function () {
  11827. return this._receiveShadows;
  11828. },
  11829. set: function (value) {
  11830. if (this._receiveShadows === value) {
  11831. return;
  11832. }
  11833. this._receiveShadows = value;
  11834. this._markSubMeshesAsLightDirty();
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11840. get: function () {
  11841. return this._hasVertexAlpha;
  11842. },
  11843. set: function (value) {
  11844. if (this._hasVertexAlpha === value) {
  11845. return;
  11846. }
  11847. this._hasVertexAlpha = value;
  11848. this._markSubMeshesAsAttributesDirty();
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11854. get: function () {
  11855. return this._useVertexColors;
  11856. },
  11857. set: function (value) {
  11858. if (this._useVertexColors === value) {
  11859. return;
  11860. }
  11861. this._useVertexColors = value;
  11862. this._markSubMeshesAsAttributesDirty();
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11868. get: function () {
  11869. return this._computeBonesUsingShaders;
  11870. },
  11871. set: function (value) {
  11872. if (this._computeBonesUsingShaders === value) {
  11873. return;
  11874. }
  11875. this._computeBonesUsingShaders = value;
  11876. this._markSubMeshesAsAttributesDirty();
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11882. get: function () {
  11883. return this._numBoneInfluencers;
  11884. },
  11885. set: function (value) {
  11886. if (this._numBoneInfluencers === value) {
  11887. return;
  11888. }
  11889. this._numBoneInfluencers = value;
  11890. this._markSubMeshesAsAttributesDirty();
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11896. get: function () {
  11897. return this._applyFog;
  11898. },
  11899. set: function (value) {
  11900. if (this._applyFog === value) {
  11901. return;
  11902. }
  11903. this._applyFog = value;
  11904. this._markSubMeshesAsMiscDirty();
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11910. get: function () {
  11911. return this._collisionMask;
  11912. },
  11913. set: function (mask) {
  11914. this._collisionMask = !isNaN(mask) ? mask : -1;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11920. get: function () {
  11921. return this._collisionGroup;
  11922. },
  11923. set: function (mask) {
  11924. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11930. get: function () {
  11931. return null;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11937. get: function () {
  11938. return this._skeleton;
  11939. },
  11940. set: function (value) {
  11941. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11942. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11943. }
  11944. if (value && value.needInitialSkinMatrix) {
  11945. value._registerMeshWithPoseMatrix(this);
  11946. }
  11947. this._skeleton = value;
  11948. if (!this._skeleton) {
  11949. this._bonesTransformMatrices = null;
  11950. }
  11951. this._markSubMeshesAsAttributesDirty();
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. /**
  11957. * Boolean : true if the mesh has been disposed.
  11958. */
  11959. AbstractMesh.prototype.isDisposed = function () {
  11960. return this._isDisposed;
  11961. };
  11962. /**
  11963. * Returns the string "AbstractMesh"
  11964. */
  11965. AbstractMesh.prototype.getClassName = function () {
  11966. return "AbstractMesh";
  11967. };
  11968. /**
  11969. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11970. */
  11971. AbstractMesh.prototype.toString = function (fullDetails) {
  11972. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11973. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11974. if (this._skeleton) {
  11975. ret += ", skeleton: " + this._skeleton.name;
  11976. }
  11977. if (fullDetails) {
  11978. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11979. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11980. }
  11981. return ret;
  11982. };
  11983. AbstractMesh.prototype._resyncLightSources = function () {
  11984. this._lightSources.length = 0;
  11985. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11986. var light = _a[_i];
  11987. if (!light.isEnabled()) {
  11988. continue;
  11989. }
  11990. if (light.canAffectMesh(this)) {
  11991. this._lightSources.push(light);
  11992. }
  11993. }
  11994. this._markSubMeshesAsLightDirty();
  11995. };
  11996. AbstractMesh.prototype._resyncLighSource = function (light) {
  11997. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11998. var index = this._lightSources.indexOf(light);
  11999. if (index === -1) {
  12000. if (!isIn) {
  12001. return;
  12002. }
  12003. this._lightSources.push(light);
  12004. }
  12005. else {
  12006. if (isIn) {
  12007. return;
  12008. }
  12009. this._lightSources.splice(index, 1);
  12010. }
  12011. this._markSubMeshesAsLightDirty();
  12012. };
  12013. AbstractMesh.prototype._removeLightSource = function (light) {
  12014. var index = this._lightSources.indexOf(light);
  12015. if (index === -1) {
  12016. return;
  12017. }
  12018. this._lightSources.splice(index, 1);
  12019. };
  12020. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12021. if (!this.subMeshes) {
  12022. return;
  12023. }
  12024. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12025. var subMesh = _a[_i];
  12026. if (subMesh._materialDefines) {
  12027. func(subMesh._materialDefines);
  12028. }
  12029. }
  12030. };
  12031. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12032. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12033. };
  12034. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12035. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12036. };
  12037. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12038. if (!this.subMeshes) {
  12039. return;
  12040. }
  12041. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12042. var subMesh = _a[_i];
  12043. var material = subMesh.getMaterial();
  12044. if (material) {
  12045. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12046. }
  12047. }
  12048. };
  12049. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12050. /**
  12051. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12052. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12053. * Default : (0.0, 0.0, 0.0)
  12054. */
  12055. get: function () {
  12056. return this._rotation;
  12057. },
  12058. set: function (newRotation) {
  12059. this._rotation = newRotation;
  12060. },
  12061. enumerable: true,
  12062. configurable: true
  12063. });
  12064. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12065. /**
  12066. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12067. * Default : (1.0, 1.0, 1.0)
  12068. */
  12069. get: function () {
  12070. return this._scaling;
  12071. },
  12072. set: function (newScaling) {
  12073. this._scaling = newScaling;
  12074. if (this.physicsImpostor) {
  12075. this.physicsImpostor.forceUpdate();
  12076. }
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12082. /**
  12083. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12084. * It's null by default.
  12085. * 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)
  12086. */
  12087. get: function () {
  12088. return this._rotationQuaternion;
  12089. },
  12090. set: function (quaternion) {
  12091. this._rotationQuaternion = quaternion;
  12092. //reset the rotation vector.
  12093. if (quaternion && this.rotation.length()) {
  12094. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12095. }
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. // Methods
  12101. /**
  12102. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12103. * Returns the AbstractMesh.
  12104. */
  12105. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12106. this._poseMatrix.copyFrom(matrix);
  12107. return this;
  12108. };
  12109. /**
  12110. * Returns the mesh Pose matrix.
  12111. * Returned object : Matrix
  12112. */
  12113. AbstractMesh.prototype.getPoseMatrix = function () {
  12114. return this._poseMatrix;
  12115. };
  12116. /**
  12117. * Disables the mesh edger rendering mode.
  12118. * Returns the AbstractMesh.
  12119. */
  12120. AbstractMesh.prototype.disableEdgesRendering = function () {
  12121. if (this._edgesRenderer !== undefined) {
  12122. this._edgesRenderer.dispose();
  12123. this._edgesRenderer = undefined;
  12124. }
  12125. return this;
  12126. };
  12127. /**
  12128. * Enables the edge rendering mode on the mesh.
  12129. * This mode makes the mesh edges visible.
  12130. * Returns the AbstractMesh.
  12131. */
  12132. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12133. if (epsilon === void 0) { epsilon = 0.95; }
  12134. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12135. this.disableEdgesRendering();
  12136. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12137. return this;
  12138. };
  12139. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12140. /**
  12141. * Returns true if the mesh is blocked. Used by the class Mesh.
  12142. * Returns the boolean `false` by default.
  12143. */
  12144. get: function () {
  12145. return false;
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. /**
  12151. * Returns the mesh itself by default, used by the class Mesh.
  12152. * Returned type : AbstractMesh
  12153. */
  12154. AbstractMesh.prototype.getLOD = function (camera) {
  12155. return this;
  12156. };
  12157. /**
  12158. * Returns 0 by default, used by the class Mesh.
  12159. * Returns an integer.
  12160. */
  12161. AbstractMesh.prototype.getTotalVertices = function () {
  12162. return 0;
  12163. };
  12164. /**
  12165. * Returns null by default, used by the class Mesh.
  12166. * Returned type : integer array
  12167. */
  12168. AbstractMesh.prototype.getIndices = function () {
  12169. return null;
  12170. };
  12171. /**
  12172. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12173. * Returned type : float array or Float32Array
  12174. */
  12175. AbstractMesh.prototype.getVerticesData = function (kind) {
  12176. return null;
  12177. };
  12178. /**
  12179. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12180. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12181. * The `data` are either a numeric array either a Float32Array.
  12182. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12183. * 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).
  12184. * Note that a new underlying VertexBuffer object is created each call.
  12185. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12186. *
  12187. * Possible `kind` values :
  12188. * - BABYLON.VertexBuffer.PositionKind
  12189. * - BABYLON.VertexBuffer.UVKind
  12190. * - BABYLON.VertexBuffer.UV2Kind
  12191. * - BABYLON.VertexBuffer.UV3Kind
  12192. * - BABYLON.VertexBuffer.UV4Kind
  12193. * - BABYLON.VertexBuffer.UV5Kind
  12194. * - BABYLON.VertexBuffer.UV6Kind
  12195. * - BABYLON.VertexBuffer.ColorKind
  12196. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12197. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12198. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12199. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12200. *
  12201. * Returns the Mesh.
  12202. */
  12203. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12204. return null;
  12205. };
  12206. /**
  12207. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12208. * If the mesh has no geometry, it is simply returned as it is.
  12209. * The `data` are either a numeric array either a Float32Array.
  12210. * No new underlying VertexBuffer object is created.
  12211. * 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.
  12212. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12213. *
  12214. * Possible `kind` values :
  12215. * - BABYLON.VertexBuffer.PositionKind
  12216. * - BABYLON.VertexBuffer.UVKind
  12217. * - BABYLON.VertexBuffer.UV2Kind
  12218. * - BABYLON.VertexBuffer.UV3Kind
  12219. * - BABYLON.VertexBuffer.UV4Kind
  12220. * - BABYLON.VertexBuffer.UV5Kind
  12221. * - BABYLON.VertexBuffer.UV6Kind
  12222. * - BABYLON.VertexBuffer.ColorKind
  12223. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12224. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12225. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12226. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12227. *
  12228. * Returns the Mesh.
  12229. */
  12230. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12231. return null;
  12232. };
  12233. /**
  12234. * Sets the mesh indices.
  12235. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12236. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12237. * This method creates a new index buffer each call.
  12238. * Returns the Mesh.
  12239. */
  12240. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12241. return null;
  12242. };
  12243. /** Returns false by default, used by the class Mesh.
  12244. * Returns a boolean
  12245. */
  12246. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12247. return false;
  12248. };
  12249. /**
  12250. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12251. * Returns a BoundingInfo
  12252. */
  12253. AbstractMesh.prototype.getBoundingInfo = function () {
  12254. if (this._masterMesh) {
  12255. return this._masterMesh.getBoundingInfo();
  12256. }
  12257. if (!this._boundingInfo) {
  12258. this._updateBoundingInfo();
  12259. }
  12260. return this._boundingInfo;
  12261. };
  12262. /**
  12263. * Sets a mesh new object BoundingInfo.
  12264. * Returns the AbstractMesh.
  12265. */
  12266. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12267. this._boundingInfo = boundingInfo;
  12268. return this;
  12269. };
  12270. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12271. get: function () {
  12272. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. AbstractMesh.prototype._preActivate = function () {
  12278. };
  12279. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12280. };
  12281. AbstractMesh.prototype._activate = function (renderId) {
  12282. this._renderId = renderId;
  12283. };
  12284. /**
  12285. * Returns the last update of the World matrix
  12286. * Returns a Matrix.
  12287. */
  12288. AbstractMesh.prototype.getWorldMatrix = function () {
  12289. if (this._masterMesh) {
  12290. return this._masterMesh.getWorldMatrix();
  12291. }
  12292. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12293. this.computeWorldMatrix();
  12294. }
  12295. return this._worldMatrix;
  12296. };
  12297. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12298. /**
  12299. * Returns directly the last state of the mesh World matrix.
  12300. * A Matrix is returned.
  12301. */
  12302. get: function () {
  12303. return this._worldMatrix;
  12304. },
  12305. enumerable: true,
  12306. configurable: true
  12307. });
  12308. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12309. /**
  12310. * Returns the current mesh absolute position.
  12311. * Retuns a Vector3.
  12312. */
  12313. get: function () {
  12314. return this._absolutePosition;
  12315. },
  12316. enumerable: true,
  12317. configurable: true
  12318. });
  12319. /**
  12320. * Prevents the World matrix to be computed any longer.
  12321. * Returns the AbstractMesh.
  12322. */
  12323. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12324. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12325. this.computeWorldMatrix(true);
  12326. this._isWorldMatrixFrozen = true;
  12327. return this;
  12328. };
  12329. /**
  12330. * Allows back the World matrix computation.
  12331. * Returns the AbstractMesh.
  12332. */
  12333. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12334. this._isWorldMatrixFrozen = false;
  12335. this.computeWorldMatrix(true);
  12336. return this;
  12337. };
  12338. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12339. /**
  12340. * True if the World matrix has been frozen.
  12341. * Returns a boolean.
  12342. */
  12343. get: function () {
  12344. return this._isWorldMatrixFrozen;
  12345. },
  12346. enumerable: true,
  12347. configurable: true
  12348. });
  12349. /**
  12350. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12351. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12352. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12353. * The passed axis is also normalized.
  12354. * Returns the AbstractMesh.
  12355. */
  12356. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12357. axis.normalize();
  12358. if (!this.rotationQuaternion) {
  12359. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12360. this.rotation = BABYLON.Vector3.Zero();
  12361. }
  12362. var rotationQuaternion;
  12363. if (!space || space === BABYLON.Space.LOCAL) {
  12364. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12365. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12366. }
  12367. else {
  12368. if (this.parent) {
  12369. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12370. invertParentWorldMatrix.invert();
  12371. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12372. }
  12373. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12374. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12375. }
  12376. return this;
  12377. };
  12378. /**
  12379. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12380. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12381. * The passed axis is also normalized.
  12382. * Returns the AbstractMesh.
  12383. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12384. */
  12385. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12386. axis.normalize();
  12387. if (!this.rotationQuaternion) {
  12388. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12389. this.rotation.copyFromFloats(0, 0, 0);
  12390. }
  12391. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12392. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12393. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12394. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12395. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12396. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12397. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12398. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12399. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12400. return this;
  12401. };
  12402. /**
  12403. * Translates the mesh along the axis vector for the passed distance in the given space.
  12404. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12405. * Returns the AbstractMesh.
  12406. */
  12407. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12408. var displacementVector = axis.scale(distance);
  12409. if (!space || space === BABYLON.Space.LOCAL) {
  12410. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12411. this.setPositionWithLocalVector(tempV3);
  12412. }
  12413. else {
  12414. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12415. }
  12416. return this;
  12417. };
  12418. /**
  12419. * Adds a rotation step to the mesh current rotation.
  12420. * x, y, z are Euler angles expressed in radians.
  12421. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12422. * This means this rotation is made in the mesh local space only.
  12423. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12424. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12425. * ```javascript
  12426. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12427. * ```
  12428. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12429. * 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.
  12430. * Returns the AbstractMesh.
  12431. */
  12432. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12433. var rotationQuaternion;
  12434. if (this.rotationQuaternion) {
  12435. rotationQuaternion = this.rotationQuaternion;
  12436. }
  12437. else {
  12438. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12439. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12440. }
  12441. var accumulation = BABYLON.Tmp.Quaternion[0];
  12442. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12443. rotationQuaternion.multiplyInPlace(accumulation);
  12444. if (!this.rotationQuaternion) {
  12445. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12446. }
  12447. return this;
  12448. };
  12449. /**
  12450. * Retuns the mesh absolute position in the World.
  12451. * Returns a Vector3.
  12452. */
  12453. AbstractMesh.prototype.getAbsolutePosition = function () {
  12454. this.computeWorldMatrix();
  12455. return this._absolutePosition;
  12456. };
  12457. /**
  12458. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12459. * Returns the AbstractMesh.
  12460. */
  12461. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12462. if (!absolutePosition) {
  12463. return;
  12464. }
  12465. var absolutePositionX;
  12466. var absolutePositionY;
  12467. var absolutePositionZ;
  12468. if (absolutePosition.x === undefined) {
  12469. if (arguments.length < 3) {
  12470. return;
  12471. }
  12472. absolutePositionX = arguments[0];
  12473. absolutePositionY = arguments[1];
  12474. absolutePositionZ = arguments[2];
  12475. }
  12476. else {
  12477. absolutePositionX = absolutePosition.x;
  12478. absolutePositionY = absolutePosition.y;
  12479. absolutePositionZ = absolutePosition.z;
  12480. }
  12481. if (this.parent) {
  12482. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12483. invertParentWorldMatrix.invert();
  12484. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12485. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12486. }
  12487. else {
  12488. this.position.x = absolutePositionX;
  12489. this.position.y = absolutePositionY;
  12490. this.position.z = absolutePositionZ;
  12491. }
  12492. return this;
  12493. };
  12494. // ================================== Point of View Movement =================================
  12495. /**
  12496. * Perform relative position change from the point of view of behind the front of the mesh.
  12497. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12498. * Supports definition of mesh facing forward or backward.
  12499. * @param {number} amountRight
  12500. * @param {number} amountUp
  12501. * @param {number} amountForward
  12502. *
  12503. * Returns the AbstractMesh.
  12504. */
  12505. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12506. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12507. return this;
  12508. };
  12509. /**
  12510. * Calculate relative position change from the point of view of behind the front of the mesh.
  12511. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12512. * Supports definition of mesh facing forward or backward.
  12513. * @param {number} amountRight
  12514. * @param {number} amountUp
  12515. * @param {number} amountForward
  12516. *
  12517. * Returns a new Vector3.
  12518. */
  12519. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12520. var rotMatrix = new BABYLON.Matrix();
  12521. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12522. rotQuaternion.toRotationMatrix(rotMatrix);
  12523. var translationDelta = BABYLON.Vector3.Zero();
  12524. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12525. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12526. return translationDelta;
  12527. };
  12528. // ================================== Point of View Rotation =================================
  12529. /**
  12530. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12531. * Supports definition of mesh facing forward or backward.
  12532. * @param {number} flipBack
  12533. * @param {number} twirlClockwise
  12534. * @param {number} tiltRight
  12535. *
  12536. * Returns the AbstractMesh.
  12537. */
  12538. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12539. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12540. return this;
  12541. };
  12542. /**
  12543. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12544. * Supports definition of mesh facing forward or backward.
  12545. * @param {number} flipBack
  12546. * @param {number} twirlClockwise
  12547. * @param {number} tiltRight
  12548. *
  12549. * Returns a new Vector3.
  12550. */
  12551. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12552. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12553. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12554. };
  12555. /**
  12556. * Sets a new pivot matrix to the mesh.
  12557. * Returns the AbstractMesh.
  12558. */
  12559. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12560. this._pivotMatrix = matrix;
  12561. this._cache.pivotMatrixUpdated = true;
  12562. return this;
  12563. };
  12564. /**
  12565. * Returns the mesh pivot matrix.
  12566. * Default : Identity.
  12567. * A Matrix is returned.
  12568. */
  12569. AbstractMesh.prototype.getPivotMatrix = function () {
  12570. return this._pivotMatrix;
  12571. };
  12572. AbstractMesh.prototype._isSynchronized = function () {
  12573. if (this._isDirty) {
  12574. return false;
  12575. }
  12576. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12577. return false;
  12578. if (this._cache.pivotMatrixUpdated) {
  12579. return false;
  12580. }
  12581. if (this.infiniteDistance) {
  12582. return false;
  12583. }
  12584. if (!this._cache.position.equals(this.position))
  12585. return false;
  12586. if (this.rotationQuaternion) {
  12587. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12588. return false;
  12589. }
  12590. if (!this._cache.rotation.equals(this.rotation))
  12591. return false;
  12592. if (!this._cache.scaling.equals(this.scaling))
  12593. return false;
  12594. return true;
  12595. };
  12596. AbstractMesh.prototype._initCache = function () {
  12597. _super.prototype._initCache.call(this);
  12598. this._cache.localMatrixUpdated = false;
  12599. this._cache.position = BABYLON.Vector3.Zero();
  12600. this._cache.scaling = BABYLON.Vector3.Zero();
  12601. this._cache.rotation = BABYLON.Vector3.Zero();
  12602. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12603. this._cache.billboardMode = -1;
  12604. };
  12605. AbstractMesh.prototype.markAsDirty = function (property) {
  12606. if (property === "rotation") {
  12607. this.rotationQuaternion = null;
  12608. }
  12609. this._currentRenderId = Number.MAX_VALUE;
  12610. this._isDirty = true;
  12611. return this;
  12612. };
  12613. /**
  12614. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12615. * Returns the AbstractMesh.
  12616. */
  12617. AbstractMesh.prototype._updateBoundingInfo = function () {
  12618. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12619. this._boundingInfo.update(this.worldMatrixFromCache);
  12620. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12621. return this;
  12622. };
  12623. /**
  12624. * Update a mesh's children BoundingInfo objects only.
  12625. * Returns the AbstractMesh.
  12626. */
  12627. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12628. if (!this.subMeshes) {
  12629. return;
  12630. }
  12631. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12632. var subMesh = this.subMeshes[subIndex];
  12633. if (!subMesh.IsGlobal) {
  12634. subMesh.updateBoundingInfo(matrix);
  12635. }
  12636. }
  12637. return this;
  12638. };
  12639. /**
  12640. * Computes the mesh World matrix and returns it.
  12641. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12642. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12643. * If the parameter `force`is set to `true`, the actual computation is done.
  12644. * Returns the mesh World Matrix.
  12645. */
  12646. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12647. if (this._isWorldMatrixFrozen) {
  12648. return this._worldMatrix;
  12649. }
  12650. if (!force && this.isSynchronized(true)) {
  12651. this._currentRenderId = this.getScene().getRenderId();
  12652. return this._worldMatrix;
  12653. }
  12654. this._cache.position.copyFrom(this.position);
  12655. this._cache.scaling.copyFrom(this.scaling);
  12656. this._cache.pivotMatrixUpdated = false;
  12657. this._cache.billboardMode = this.billboardMode;
  12658. this._currentRenderId = this.getScene().getRenderId();
  12659. this._isDirty = false;
  12660. // Scaling
  12661. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12662. // Rotation
  12663. //rotate, if quaternion is set and rotation was used
  12664. if (this.rotationQuaternion) {
  12665. var len = this.rotation.length();
  12666. if (len) {
  12667. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12668. this.rotation.copyFromFloats(0, 0, 0);
  12669. }
  12670. }
  12671. if (this.rotationQuaternion) {
  12672. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12673. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12674. }
  12675. else {
  12676. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12677. this._cache.rotation.copyFrom(this.rotation);
  12678. }
  12679. // Translation
  12680. if (this.infiniteDistance && !this.parent) {
  12681. var camera = this.getScene().activeCamera;
  12682. if (camera) {
  12683. var cameraWorldMatrix = camera.getWorldMatrix();
  12684. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12685. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12686. }
  12687. }
  12688. else {
  12689. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12690. }
  12691. // Composing transformations
  12692. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12693. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12694. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12695. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12696. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12697. // Need to decompose each rotation here
  12698. var currentPosition = BABYLON.Tmp.Vector3[3];
  12699. if (this.parent && this.parent.getWorldMatrix) {
  12700. if (this._meshToBoneReferal) {
  12701. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12702. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12703. }
  12704. else {
  12705. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12706. }
  12707. }
  12708. else {
  12709. currentPosition.copyFrom(this.position);
  12710. }
  12711. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12712. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12713. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12714. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12715. }
  12716. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12717. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12718. }
  12719. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12720. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12721. }
  12722. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12723. }
  12724. else {
  12725. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12726. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12727. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12728. }
  12729. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12730. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12731. }
  12732. // Local world
  12733. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12734. // Parent
  12735. if (this.parent && this.parent.getWorldMatrix) {
  12736. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12737. if (this._meshToBoneReferal) {
  12738. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12739. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12740. }
  12741. else {
  12742. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12743. }
  12744. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12745. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12746. this._worldMatrix.copyFrom(this._localWorld);
  12747. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12748. }
  12749. else {
  12750. if (this._meshToBoneReferal) {
  12751. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12752. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12753. }
  12754. else {
  12755. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12756. }
  12757. }
  12758. this._markSyncedWithParent();
  12759. }
  12760. else {
  12761. this._worldMatrix.copyFrom(this._localWorld);
  12762. }
  12763. // Bounding info
  12764. this._updateBoundingInfo();
  12765. // Absolute position
  12766. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12767. // Callbacks
  12768. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12769. if (!this._poseMatrix) {
  12770. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12771. }
  12772. return this._worldMatrix;
  12773. };
  12774. /**
  12775. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12776. * @param func: callback function to add
  12777. *
  12778. * Returns the AbstractMesh.
  12779. */
  12780. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12781. this.onAfterWorldMatrixUpdateObservable.add(func);
  12782. return this;
  12783. };
  12784. /**
  12785. * Removes a registered callback function.
  12786. * Returns the AbstractMesh.
  12787. */
  12788. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12789. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12790. return this;
  12791. };
  12792. /**
  12793. * Sets the mesh position in its local space.
  12794. * Returns the AbstractMesh.
  12795. */
  12796. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12797. this.computeWorldMatrix();
  12798. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12799. return this;
  12800. };
  12801. /**
  12802. * Returns the mesh position in the local space from the current World matrix values.
  12803. * Returns a new Vector3.
  12804. */
  12805. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12806. this.computeWorldMatrix();
  12807. var invLocalWorldMatrix = this._localWorld.clone();
  12808. invLocalWorldMatrix.invert();
  12809. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12810. };
  12811. /**
  12812. * Translates the mesh along the passed Vector3 in its local space.
  12813. * Returns the AbstractMesh.
  12814. */
  12815. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12816. this.computeWorldMatrix(true);
  12817. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12818. return this;
  12819. };
  12820. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12821. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12822. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12823. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12824. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12825. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12826. /// <returns>Mesh oriented towards targetMesh</returns>
  12827. if (yawCor === void 0) { yawCor = 0; }
  12828. if (pitchCor === void 0) { pitchCor = 0; }
  12829. if (rollCor === void 0) { rollCor = 0; }
  12830. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12831. var dv = AbstractMesh._lookAtVectorCache;
  12832. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12833. targetPoint.subtractToRef(pos, dv);
  12834. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12835. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12836. var pitch = Math.atan2(dv.y, len);
  12837. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12838. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12839. return this;
  12840. };
  12841. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12842. this._meshToBoneReferal = affectedMesh;
  12843. this.parent = bone;
  12844. if (bone.getWorldMatrix().determinant() < 0) {
  12845. this.scalingDeterminant *= -1;
  12846. }
  12847. return this;
  12848. };
  12849. AbstractMesh.prototype.detachFromBone = function () {
  12850. if (this.parent.getWorldMatrix().determinant() < 0) {
  12851. this.scalingDeterminant *= -1;
  12852. }
  12853. this._meshToBoneReferal = null;
  12854. this.parent = null;
  12855. return this;
  12856. };
  12857. /**
  12858. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12859. * A mesh is in the frustum if its bounding box intersects the frustum.
  12860. * Boolean returned.
  12861. */
  12862. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12863. return this._boundingInfo.isInFrustum(frustumPlanes);
  12864. };
  12865. /**
  12866. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12867. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12868. * Boolean returned.
  12869. */
  12870. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12871. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12872. ;
  12873. };
  12874. /**
  12875. * True if the mesh intersects another mesh or a SolidParticle object.
  12876. * 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)
  12877. * Returns a boolean.
  12878. */
  12879. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12880. if (!this._boundingInfo || !mesh._boundingInfo) {
  12881. return false;
  12882. }
  12883. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12884. };
  12885. /**
  12886. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12887. * Returns a boolean.
  12888. */
  12889. AbstractMesh.prototype.intersectsPoint = function (point) {
  12890. if (!this._boundingInfo) {
  12891. return false;
  12892. }
  12893. return this._boundingInfo.intersectsPoint(point);
  12894. };
  12895. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12896. return this.physicsImpostor;
  12897. };
  12898. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12899. if (!camera) {
  12900. camera = this.getScene().activeCamera;
  12901. }
  12902. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12903. };
  12904. /**
  12905. * Returns the distance from the mesh to the active camera.
  12906. * Returns a float.
  12907. */
  12908. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12909. if (!camera) {
  12910. camera = this.getScene().activeCamera;
  12911. }
  12912. return this.absolutePosition.subtract(camera.position).length();
  12913. };
  12914. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12915. if (!this.physicsImpostor) {
  12916. return;
  12917. }
  12918. this.physicsImpostor.applyImpulse(force, contactPoint);
  12919. return this;
  12920. };
  12921. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12922. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12923. return;
  12924. }
  12925. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12926. mainPivot: pivot1,
  12927. connectedPivot: pivot2,
  12928. nativeParams: options
  12929. });
  12930. return this;
  12931. };
  12932. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12933. // Collisions
  12934. /**
  12935. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12936. * Default `false`.
  12937. */
  12938. get: function () {
  12939. return this._checkCollisions;
  12940. },
  12941. set: function (collisionEnabled) {
  12942. this._checkCollisions = collisionEnabled;
  12943. if (this.getScene().workerCollisions) {
  12944. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12945. }
  12946. },
  12947. enumerable: true,
  12948. configurable: true
  12949. });
  12950. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12951. var globalPosition = this.getAbsolutePosition();
  12952. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12953. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12954. if (!this._collider) {
  12955. this._collider = new BABYLON.Collider();
  12956. }
  12957. this._collider.radius = this.ellipsoid;
  12958. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12959. return this;
  12960. };
  12961. // Submeshes octree
  12962. /**
  12963. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12964. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12965. * Returns an Octree of submeshes.
  12966. */
  12967. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12968. if (maxCapacity === void 0) { maxCapacity = 64; }
  12969. if (maxDepth === void 0) { maxDepth = 2; }
  12970. if (!this._submeshesOctree) {
  12971. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12972. }
  12973. this.computeWorldMatrix(true);
  12974. // Update octree
  12975. var bbox = this.getBoundingInfo().boundingBox;
  12976. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12977. return this._submeshesOctree;
  12978. };
  12979. // Collisions
  12980. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12981. this._generatePointsArray();
  12982. // Transformation
  12983. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12984. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12985. subMesh._lastColliderWorldVertices = [];
  12986. subMesh._trianglePlanes = [];
  12987. var start = subMesh.verticesStart;
  12988. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12989. for (var i = start; i < end; i++) {
  12990. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12991. }
  12992. }
  12993. // Collide
  12994. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12995. if (collider.collisionFound) {
  12996. collider.collidedMesh = this;
  12997. }
  12998. return this;
  12999. };
  13000. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13001. var subMeshes;
  13002. var len;
  13003. // Octrees
  13004. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13005. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13006. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13007. len = intersections.length;
  13008. subMeshes = intersections.data;
  13009. }
  13010. else {
  13011. subMeshes = this.subMeshes;
  13012. len = subMeshes.length;
  13013. }
  13014. for (var index = 0; index < len; index++) {
  13015. var subMesh = subMeshes[index];
  13016. // Bounding test
  13017. if (len > 1 && !subMesh._checkCollision(collider))
  13018. continue;
  13019. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13020. }
  13021. return this;
  13022. };
  13023. AbstractMesh.prototype._checkCollision = function (collider) {
  13024. // Bounding box test
  13025. if (!this._boundingInfo._checkCollision(collider))
  13026. return this;
  13027. // Transformation matrix
  13028. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13029. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13030. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13031. return this;
  13032. };
  13033. // Picking
  13034. AbstractMesh.prototype._generatePointsArray = function () {
  13035. return false;
  13036. };
  13037. /**
  13038. * Checks if the passed Ray intersects with the mesh.
  13039. * Returns an object PickingInfo.
  13040. */
  13041. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13042. var pickingInfo = new BABYLON.PickingInfo();
  13043. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13044. return pickingInfo;
  13045. }
  13046. if (!this._generatePointsArray()) {
  13047. return pickingInfo;
  13048. }
  13049. var intersectInfo = null;
  13050. // Octrees
  13051. var subMeshes;
  13052. var len;
  13053. if (this._submeshesOctree && this.useOctreeForPicking) {
  13054. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13055. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13056. len = intersections.length;
  13057. subMeshes = intersections.data;
  13058. }
  13059. else {
  13060. subMeshes = this.subMeshes;
  13061. len = subMeshes.length;
  13062. }
  13063. for (var index = 0; index < len; index++) {
  13064. var subMesh = subMeshes[index];
  13065. // Bounding test
  13066. if (len > 1 && !subMesh.canIntersects(ray))
  13067. continue;
  13068. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13069. if (currentIntersectInfo) {
  13070. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13071. intersectInfo = currentIntersectInfo;
  13072. intersectInfo.subMeshId = index;
  13073. if (fastCheck) {
  13074. break;
  13075. }
  13076. }
  13077. }
  13078. }
  13079. if (intersectInfo) {
  13080. // Get picked point
  13081. var world = this.getWorldMatrix();
  13082. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13083. var direction = ray.direction.clone();
  13084. direction = direction.scale(intersectInfo.distance);
  13085. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13086. var pickedPoint = worldOrigin.add(worldDirection);
  13087. // Return result
  13088. pickingInfo.hit = true;
  13089. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13090. pickingInfo.pickedPoint = pickedPoint;
  13091. pickingInfo.pickedMesh = this;
  13092. pickingInfo.bu = intersectInfo.bu;
  13093. pickingInfo.bv = intersectInfo.bv;
  13094. pickingInfo.faceId = intersectInfo.faceId;
  13095. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13096. return pickingInfo;
  13097. }
  13098. return pickingInfo;
  13099. };
  13100. /**
  13101. * Clones the mesh, used by the class Mesh.
  13102. * Just returns `null` for an AbstractMesh.
  13103. */
  13104. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13105. return null;
  13106. };
  13107. /**
  13108. * Disposes all the mesh submeshes.
  13109. * Returns the AbstractMesh.
  13110. */
  13111. AbstractMesh.prototype.releaseSubMeshes = function () {
  13112. if (this.subMeshes) {
  13113. while (this.subMeshes.length) {
  13114. this.subMeshes[0].dispose();
  13115. }
  13116. }
  13117. else {
  13118. this.subMeshes = new Array();
  13119. }
  13120. return this;
  13121. };
  13122. /**
  13123. * Disposes the AbstractMesh.
  13124. * Some internal references are kept for further use.
  13125. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13126. * Returns nothing.
  13127. */
  13128. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13129. var _this = this;
  13130. var index;
  13131. // Action manager
  13132. if (this.actionManager) {
  13133. this.actionManager.dispose();
  13134. this.actionManager = null;
  13135. }
  13136. // Skeleton
  13137. this.skeleton = null;
  13138. // Animations
  13139. this.getScene().stopAnimation(this);
  13140. // Physics
  13141. if (this.physicsImpostor) {
  13142. this.physicsImpostor.dispose();
  13143. }
  13144. // Intersections in progress
  13145. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13146. var other = this._intersectionsInProgress[index];
  13147. var pos = other._intersectionsInProgress.indexOf(this);
  13148. other._intersectionsInProgress.splice(pos, 1);
  13149. }
  13150. this._intersectionsInProgress = [];
  13151. // Lights
  13152. var lights = this.getScene().lights;
  13153. lights.forEach(function (light) {
  13154. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13155. if (meshIndex !== -1) {
  13156. light.includedOnlyMeshes.splice(meshIndex, 1);
  13157. }
  13158. meshIndex = light.excludedMeshes.indexOf(_this);
  13159. if (meshIndex !== -1) {
  13160. light.excludedMeshes.splice(meshIndex, 1);
  13161. }
  13162. // Shadow generators
  13163. var generator = light.getShadowGenerator();
  13164. if (generator) {
  13165. var shadowMap = generator.getShadowMap();
  13166. meshIndex = shadowMap.renderList.indexOf(_this);
  13167. if (meshIndex !== -1) {
  13168. shadowMap.renderList.splice(meshIndex, 1);
  13169. }
  13170. }
  13171. });
  13172. // Edges
  13173. if (this._edgesRenderer) {
  13174. this._edgesRenderer.dispose();
  13175. this._edgesRenderer = null;
  13176. }
  13177. // SubMeshes
  13178. if (this.getClassName() !== "InstancedMesh") {
  13179. this.releaseSubMeshes();
  13180. }
  13181. // Octree
  13182. var sceneOctree = this.getScene().selectionOctree;
  13183. if (sceneOctree) {
  13184. var index = sceneOctree.dynamicContent.indexOf(this);
  13185. if (index !== -1) {
  13186. sceneOctree.dynamicContent.splice(index, 1);
  13187. }
  13188. }
  13189. // Engine
  13190. this.getScene().getEngine().wipeCaches();
  13191. // Remove from scene
  13192. this.getScene().removeMesh(this);
  13193. if (!doNotRecurse) {
  13194. // Particles
  13195. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13196. if (this.getScene().particleSystems[index].emitter === this) {
  13197. this.getScene().particleSystems[index].dispose();
  13198. index--;
  13199. }
  13200. }
  13201. // Children
  13202. var objects = this.getDescendants(true);
  13203. for (index = 0; index < objects.length; index++) {
  13204. objects[index].dispose();
  13205. }
  13206. }
  13207. else {
  13208. var childMeshes = this.getChildMeshes(true);
  13209. for (index = 0; index < childMeshes.length; index++) {
  13210. var child = childMeshes[index];
  13211. child.parent = null;
  13212. child.computeWorldMatrix(true);
  13213. }
  13214. }
  13215. // facet data
  13216. if (this._facetDataEnabled) {
  13217. this.disableFacetData();
  13218. }
  13219. this.onAfterWorldMatrixUpdateObservable.clear();
  13220. this.onCollideObservable.clear();
  13221. this.onCollisionPositionChangeObservable.clear();
  13222. this._isDisposed = true;
  13223. _super.prototype.dispose.call(this);
  13224. };
  13225. /**
  13226. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13227. * This Vector3 is expressed in the World space.
  13228. */
  13229. AbstractMesh.prototype.getDirection = function (localAxis) {
  13230. var result = BABYLON.Vector3.Zero();
  13231. this.getDirectionToRef(localAxis, result);
  13232. return result;
  13233. };
  13234. /**
  13235. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13236. * localAxis is expressed in the mesh local space.
  13237. * result is computed in the Wordl space from the mesh World matrix.
  13238. * Returns the AbstractMesh.
  13239. */
  13240. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13241. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13242. return this;
  13243. };
  13244. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13245. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13246. if (this.getScene().getRenderId() == 0) {
  13247. this.computeWorldMatrix(true);
  13248. }
  13249. var wm = this.getWorldMatrix();
  13250. if (space == BABYLON.Space.WORLD) {
  13251. var tmat = BABYLON.Tmp.Matrix[0];
  13252. wm.invertToRef(tmat);
  13253. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13254. }
  13255. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13256. this._pivotMatrix.m[12] = -point.x;
  13257. this._pivotMatrix.m[13] = -point.y;
  13258. this._pivotMatrix.m[14] = -point.z;
  13259. this._cache.pivotMatrixUpdated = true;
  13260. return this;
  13261. };
  13262. /**
  13263. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13264. */
  13265. AbstractMesh.prototype.getPivotPoint = function () {
  13266. var point = BABYLON.Vector3.Zero();
  13267. this.getPivotPointToRef(point);
  13268. return point;
  13269. };
  13270. /**
  13271. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13272. * Returns the AbstractMesh.
  13273. */
  13274. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13275. result.x = -this._pivotMatrix.m[12];
  13276. result.y = -this._pivotMatrix.m[13];
  13277. result.z = -this._pivotMatrix.m[14];
  13278. return this;
  13279. };
  13280. /**
  13281. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13282. */
  13283. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13284. var point = BABYLON.Vector3.Zero();
  13285. this.getAbsolutePivotPointToRef(point);
  13286. return point;
  13287. };
  13288. /**
  13289. * Defines the passed mesh as the parent of the current mesh.
  13290. * Returns the AbstractMesh.
  13291. */
  13292. AbstractMesh.prototype.setParent = function (mesh) {
  13293. var child = this;
  13294. var parent = mesh;
  13295. if (mesh == null) {
  13296. var rotation = BABYLON.Tmp.Quaternion[0];
  13297. var position = BABYLON.Tmp.Vector3[0];
  13298. var scale = BABYLON.Tmp.Vector3[1];
  13299. child.getWorldMatrix().decompose(scale, rotation, position);
  13300. if (child.rotationQuaternion) {
  13301. child.rotationQuaternion.copyFrom(rotation);
  13302. }
  13303. else {
  13304. rotation.toEulerAnglesToRef(child.rotation);
  13305. }
  13306. child.position.x = position.x;
  13307. child.position.y = position.y;
  13308. child.position.z = position.z;
  13309. }
  13310. else {
  13311. var rotation = BABYLON.Tmp.Quaternion[0];
  13312. var position = BABYLON.Tmp.Vector3[0];
  13313. var scale = BABYLON.Tmp.Vector3[1];
  13314. var m1 = BABYLON.Tmp.Matrix[0];
  13315. var m2 = BABYLON.Tmp.Matrix[1];
  13316. parent.getWorldMatrix().decompose(scale, rotation, position);
  13317. rotation.toRotationMatrix(m1);
  13318. m2.setTranslation(position);
  13319. m2.multiplyToRef(m1, m1);
  13320. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13321. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13322. m.decompose(scale, rotation, position);
  13323. if (child.rotationQuaternion) {
  13324. child.rotationQuaternion.copyFrom(rotation);
  13325. }
  13326. else {
  13327. rotation.toEulerAnglesToRef(child.rotation);
  13328. }
  13329. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13330. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13331. m.decompose(scale, rotation, position);
  13332. child.position.x = position.x;
  13333. child.position.y = position.y;
  13334. child.position.z = position.z;
  13335. }
  13336. child.parent = parent;
  13337. return this;
  13338. };
  13339. /**
  13340. * Adds the passed mesh as a child to the current mesh.
  13341. * Returns the AbstractMesh.
  13342. */
  13343. AbstractMesh.prototype.addChild = function (mesh) {
  13344. mesh.setParent(this);
  13345. return this;
  13346. };
  13347. /**
  13348. * Removes the passed mesh from the current mesh children list.
  13349. * Returns the AbstractMesh.
  13350. */
  13351. AbstractMesh.prototype.removeChild = function (mesh) {
  13352. mesh.setParent(null);
  13353. return this;
  13354. };
  13355. /**
  13356. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13357. * Returns the AbstractMesh.
  13358. */
  13359. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13360. result.x = this._pivotMatrix.m[12];
  13361. result.y = this._pivotMatrix.m[13];
  13362. result.z = this._pivotMatrix.m[14];
  13363. this.getPivotPointToRef(result);
  13364. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13365. return this;
  13366. };
  13367. // Facet data
  13368. /**
  13369. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13370. * Returns the AbstractMesh.
  13371. */
  13372. AbstractMesh.prototype._initFacetData = function () {
  13373. if (!this._facetNormals) {
  13374. this._facetNormals = new Array();
  13375. }
  13376. if (!this._facetPositions) {
  13377. this._facetPositions = new Array();
  13378. }
  13379. if (!this._facetPartitioning) {
  13380. this._facetPartitioning = new Array();
  13381. }
  13382. this._facetNb = this.getIndices().length / 3;
  13383. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13384. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13385. for (var f = 0; f < this._facetNb; f++) {
  13386. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13387. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13388. }
  13389. this._facetDataEnabled = true;
  13390. return this;
  13391. };
  13392. /**
  13393. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13394. * This method can be called within the render loop.
  13395. * 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.
  13396. * Returns the AbstractMesh.
  13397. */
  13398. AbstractMesh.prototype.updateFacetData = function () {
  13399. if (!this._facetDataEnabled) {
  13400. this._initFacetData();
  13401. }
  13402. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13403. var indices = this.getIndices();
  13404. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13405. var bInfo = this.getBoundingInfo();
  13406. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13407. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13408. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13409. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13410. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13411. this._subDiv.max = this._partitioningSubdivisions;
  13412. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13413. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13414. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13415. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13416. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13417. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13418. // set the parameters for ComputeNormals()
  13419. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13420. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13421. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13422. this._facetParameters.bInfo = bInfo;
  13423. this._facetParameters.bbSize = this._bbSize;
  13424. this._facetParameters.subDiv = this._subDiv;
  13425. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13426. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13427. return this;
  13428. };
  13429. /**
  13430. * Returns the facetLocalNormals array.
  13431. * The normals are expressed in the mesh local space.
  13432. */
  13433. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13434. if (!this._facetNormals) {
  13435. this.updateFacetData();
  13436. }
  13437. return this._facetNormals;
  13438. };
  13439. /**
  13440. * Returns the facetLocalPositions array.
  13441. * The facet positions are expressed in the mesh local space.
  13442. */
  13443. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13444. if (!this._facetPositions) {
  13445. this.updateFacetData();
  13446. }
  13447. return this._facetPositions;
  13448. };
  13449. /**
  13450. * Returns the facetLocalPartioning array.
  13451. */
  13452. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13453. if (!this._facetPartitioning) {
  13454. this.updateFacetData();
  13455. }
  13456. return this._facetPartitioning;
  13457. };
  13458. /**
  13459. * Returns the i-th facet position in the world system.
  13460. * This method allocates a new Vector3 per call.
  13461. */
  13462. AbstractMesh.prototype.getFacetPosition = function (i) {
  13463. var pos = BABYLON.Vector3.Zero();
  13464. this.getFacetPositionToRef(i, pos);
  13465. return pos;
  13466. };
  13467. /**
  13468. * Sets the reference Vector3 with the i-th facet position in the world system.
  13469. * Returns the AbstractMesh.
  13470. */
  13471. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13472. var localPos = (this.getFacetLocalPositions())[i];
  13473. var world = this.getWorldMatrix();
  13474. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13475. return this;
  13476. };
  13477. /**
  13478. * Returns the i-th facet normal in the world system.
  13479. * This method allocates a new Vector3 per call.
  13480. */
  13481. AbstractMesh.prototype.getFacetNormal = function (i) {
  13482. var norm = BABYLON.Vector3.Zero();
  13483. this.getFacetNormalToRef(i, norm);
  13484. return norm;
  13485. };
  13486. /**
  13487. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13488. * Returns the AbstractMesh.
  13489. */
  13490. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13491. var localNorm = (this.getFacetLocalNormals())[i];
  13492. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13493. return this;
  13494. };
  13495. /**
  13496. * 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).
  13497. */
  13498. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13499. var bInfo = this.getBoundingInfo();
  13500. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13501. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13502. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13503. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13504. return null;
  13505. }
  13506. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13507. };
  13508. /**
  13509. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13510. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13511. * 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.
  13512. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13513. * 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.
  13514. */
  13515. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13516. if (checkFace === void 0) { checkFace = false; }
  13517. if (facing === void 0) { facing = true; }
  13518. var world = this.getWorldMatrix();
  13519. var invMat = BABYLON.Tmp.Matrix[5];
  13520. world.invertToRef(invMat);
  13521. var invVect = BABYLON.Tmp.Vector3[8];
  13522. var closest = null;
  13523. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13524. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13525. if (projected) {
  13526. // tranform the local computed projected vector to world coordinates
  13527. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13528. }
  13529. return closest;
  13530. };
  13531. /**
  13532. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13533. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13534. * 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.
  13535. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13536. * 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.
  13537. */
  13538. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13539. if (checkFace === void 0) { checkFace = false; }
  13540. if (facing === void 0) { facing = true; }
  13541. var closest = null;
  13542. var tmpx = 0.0;
  13543. var tmpy = 0.0;
  13544. var tmpz = 0.0;
  13545. var d = 0.0; // tmp dot facet normal * facet position
  13546. var t0 = 0.0;
  13547. var projx = 0.0;
  13548. var projy = 0.0;
  13549. var projz = 0.0;
  13550. // Get all the facets in the same partitioning block than (x, y, z)
  13551. var facetPositions = this.getFacetLocalPositions();
  13552. var facetNormals = this.getFacetLocalNormals();
  13553. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13554. if (!facetsInBlock) {
  13555. return null;
  13556. }
  13557. // Get the closest facet to (x, y, z)
  13558. var shortest = Number.MAX_VALUE; // init distance vars
  13559. var tmpDistance = shortest;
  13560. var fib; // current facet in the block
  13561. var norm; // current facet normal
  13562. var p0; // current facet barycenter position
  13563. // loop on all the facets in the current partitioning block
  13564. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13565. fib = facetsInBlock[idx];
  13566. norm = facetNormals[fib];
  13567. p0 = facetPositions[fib];
  13568. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13569. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13570. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13571. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13572. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13573. projx = x + norm.x * t0;
  13574. projy = y + norm.y * t0;
  13575. projz = z + norm.z * t0;
  13576. tmpx = projx - x;
  13577. tmpy = projy - y;
  13578. tmpz = projz - z;
  13579. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13580. if (tmpDistance < shortest) {
  13581. shortest = tmpDistance;
  13582. closest = fib;
  13583. if (projected) {
  13584. projected.x = projx;
  13585. projected.y = projy;
  13586. projected.z = projz;
  13587. }
  13588. }
  13589. }
  13590. }
  13591. return closest;
  13592. };
  13593. /**
  13594. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13595. */
  13596. AbstractMesh.prototype.getFacetDataParameters = function () {
  13597. return this._facetParameters;
  13598. };
  13599. /**
  13600. * Disables the feature FacetData and frees the related memory.
  13601. * Returns the AbstractMesh.
  13602. */
  13603. AbstractMesh.prototype.disableFacetData = function () {
  13604. if (this._facetDataEnabled) {
  13605. this._facetDataEnabled = false;
  13606. this._facetPositions = null;
  13607. this._facetNormals = null;
  13608. this._facetPartitioning = null;
  13609. this._facetParameters = null;
  13610. }
  13611. return this;
  13612. };
  13613. /**
  13614. * Creates new normals data for the mesh.
  13615. * @param updatable.
  13616. */
  13617. AbstractMesh.prototype.createNormals = function (updatable) {
  13618. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13619. var indices = this.getIndices();
  13620. var normals;
  13621. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13622. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13623. }
  13624. else {
  13625. normals = [];
  13626. }
  13627. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13628. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13629. };
  13630. return AbstractMesh;
  13631. }(BABYLON.Node));
  13632. // Statics
  13633. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13634. AbstractMesh._BILLBOARDMODE_X = 1;
  13635. AbstractMesh._BILLBOARDMODE_Y = 2;
  13636. AbstractMesh._BILLBOARDMODE_Z = 4;
  13637. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13638. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13639. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13640. BABYLON.AbstractMesh = AbstractMesh;
  13641. })(BABYLON || (BABYLON = {}));
  13642. //# sourceMappingURL=babylon.abstractMesh.js.map
  13643. var BABYLON;
  13644. (function (BABYLON) {
  13645. var Light = (function (_super) {
  13646. __extends(Light, _super);
  13647. /**
  13648. * Creates a Light object in the scene.
  13649. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13650. */
  13651. function Light(name, scene) {
  13652. var _this = _super.call(this, name, scene) || this;
  13653. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13654. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13655. _this.intensity = 1.0;
  13656. _this.range = Number.MAX_VALUE;
  13657. /**
  13658. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13659. * of light.
  13660. */
  13661. _this._photometricScale = 1.0;
  13662. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13663. _this._radius = 0.00001;
  13664. _this.renderPriority = 0;
  13665. /**
  13666. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13667. * the current shadow generator.
  13668. */
  13669. _this.shadowEnabled = true;
  13670. _this._excludeWithLayerMask = 0;
  13671. _this._includeOnlyWithLayerMask = 0;
  13672. _this._lightmapMode = 0;
  13673. _this._excludedMeshesIds = new Array();
  13674. _this._includedOnlyMeshesIds = new Array();
  13675. _this.getScene().addLight(_this);
  13676. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13677. _this._buildUniformLayout();
  13678. _this.includedOnlyMeshes = new Array();
  13679. _this.excludedMeshes = new Array();
  13680. _this._resyncMeshes();
  13681. return _this;
  13682. }
  13683. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13684. /**
  13685. * If every light affecting the material is in this lightmapMode,
  13686. * material.lightmapTexture adds or multiplies
  13687. * (depends on material.useLightmapAsShadowmap)
  13688. * after every other light calculations.
  13689. */
  13690. get: function () {
  13691. return Light._LIGHTMAP_DEFAULT;
  13692. },
  13693. enumerable: true,
  13694. configurable: true
  13695. });
  13696. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13697. /**
  13698. * material.lightmapTexture as only diffuse lighting from this light
  13699. * adds pnly specular lighting from this light
  13700. * adds dynamic shadows
  13701. */
  13702. get: function () {
  13703. return Light._LIGHTMAP_SPECULAR;
  13704. },
  13705. enumerable: true,
  13706. configurable: true
  13707. });
  13708. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13709. /**
  13710. * material.lightmapTexture as only lighting
  13711. * no light calculation from this light
  13712. * only adds dynamic shadows from this light
  13713. */
  13714. get: function () {
  13715. return Light._LIGHTMAP_SHADOWSONLY;
  13716. },
  13717. enumerable: true,
  13718. configurable: true
  13719. });
  13720. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13721. /**
  13722. * Each light type uses the default quantity according to its type:
  13723. * point/spot lights use luminous intensity
  13724. * directional lights use illuminance
  13725. */
  13726. get: function () {
  13727. return Light._INTENSITYMODE_AUTOMATIC;
  13728. },
  13729. enumerable: true,
  13730. configurable: true
  13731. });
  13732. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13733. /**
  13734. * lumen (lm)
  13735. */
  13736. get: function () {
  13737. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13738. },
  13739. enumerable: true,
  13740. configurable: true
  13741. });
  13742. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13743. /**
  13744. * candela (lm/sr)
  13745. */
  13746. get: function () {
  13747. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13748. },
  13749. enumerable: true,
  13750. configurable: true
  13751. });
  13752. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13753. /**
  13754. * lux (lm/m^2)
  13755. */
  13756. get: function () {
  13757. return Light._INTENSITYMODE_ILLUMINANCE;
  13758. },
  13759. enumerable: true,
  13760. configurable: true
  13761. });
  13762. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13763. /**
  13764. * nit (cd/m^2)
  13765. */
  13766. get: function () {
  13767. return Light._INTENSITYMODE_LUMINANCE;
  13768. },
  13769. enumerable: true,
  13770. configurable: true
  13771. });
  13772. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13773. /**
  13774. * Light type const id of the point light.
  13775. */
  13776. get: function () {
  13777. return Light._LIGHTTYPEID_POINTLIGHT;
  13778. },
  13779. enumerable: true,
  13780. configurable: true
  13781. });
  13782. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13783. /**
  13784. * Light type const id of the directional light.
  13785. */
  13786. get: function () {
  13787. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13788. },
  13789. enumerable: true,
  13790. configurable: true
  13791. });
  13792. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13793. /**
  13794. * Light type const id of the spot light.
  13795. */
  13796. get: function () {
  13797. return Light._LIGHTTYPEID_SPOTLIGHT;
  13798. },
  13799. enumerable: true,
  13800. configurable: true
  13801. });
  13802. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13803. /**
  13804. * Light type const id of the hemispheric light.
  13805. */
  13806. get: function () {
  13807. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13808. },
  13809. enumerable: true,
  13810. configurable: true
  13811. });
  13812. Object.defineProperty(Light.prototype, "intensityMode", {
  13813. /**
  13814. * Gets the photometric scale used to interpret the intensity.
  13815. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13816. */
  13817. get: function () {
  13818. return this._intensityMode;
  13819. },
  13820. /**
  13821. * Sets the photometric scale used to interpret the intensity.
  13822. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13823. */
  13824. set: function (value) {
  13825. this._intensityMode = value;
  13826. this._computePhotometricScale();
  13827. },
  13828. enumerable: true,
  13829. configurable: true
  13830. });
  13831. ;
  13832. ;
  13833. Object.defineProperty(Light.prototype, "radius", {
  13834. /**
  13835. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13836. */
  13837. get: function () {
  13838. return this._radius;
  13839. },
  13840. /**
  13841. * sets the light radius used by PBR Materials to simulate soft area lights.
  13842. */
  13843. set: function (value) {
  13844. this._radius = value;
  13845. this._computePhotometricScale();
  13846. },
  13847. enumerable: true,
  13848. configurable: true
  13849. });
  13850. ;
  13851. ;
  13852. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13853. get: function () {
  13854. return this._includedOnlyMeshes;
  13855. },
  13856. set: function (value) {
  13857. this._includedOnlyMeshes = value;
  13858. this._hookArrayForIncludedOnly(value);
  13859. },
  13860. enumerable: true,
  13861. configurable: true
  13862. });
  13863. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13864. get: function () {
  13865. return this._excludedMeshes;
  13866. },
  13867. set: function (value) {
  13868. this._excludedMeshes = value;
  13869. this._hookArrayForExcluded(value);
  13870. },
  13871. enumerable: true,
  13872. configurable: true
  13873. });
  13874. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13875. get: function () {
  13876. return this._excludeWithLayerMask;
  13877. },
  13878. set: function (value) {
  13879. this._excludeWithLayerMask = value;
  13880. this._resyncMeshes();
  13881. },
  13882. enumerable: true,
  13883. configurable: true
  13884. });
  13885. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13886. get: function () {
  13887. return this._includeOnlyWithLayerMask;
  13888. },
  13889. set: function (value) {
  13890. this._includeOnlyWithLayerMask = value;
  13891. this._resyncMeshes();
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(Light.prototype, "lightmapMode", {
  13897. get: function () {
  13898. return this._lightmapMode;
  13899. },
  13900. set: function (value) {
  13901. if (this._lightmapMode === value) {
  13902. return;
  13903. }
  13904. this._lightmapMode = value;
  13905. this._markMeshesAsLightDirty();
  13906. },
  13907. enumerable: true,
  13908. configurable: true
  13909. });
  13910. Light.prototype._buildUniformLayout = function () {
  13911. // Overridden
  13912. };
  13913. /**
  13914. * Returns the string "Light".
  13915. */
  13916. Light.prototype.getClassName = function () {
  13917. return "Light";
  13918. };
  13919. /**
  13920. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13921. */
  13922. Light.prototype.toString = function (fullDetails) {
  13923. var ret = "Name: " + this.name;
  13924. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13925. if (this.animations) {
  13926. for (var i = 0; i < this.animations.length; i++) {
  13927. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13928. }
  13929. }
  13930. if (fullDetails) {
  13931. }
  13932. return ret;
  13933. };
  13934. /**
  13935. * Set the enabled state of this node.
  13936. * @param {boolean} value - the new enabled state
  13937. * @see isEnabled
  13938. */
  13939. Light.prototype.setEnabled = function (value) {
  13940. _super.prototype.setEnabled.call(this, value);
  13941. this._resyncMeshes();
  13942. };
  13943. /**
  13944. * Returns the Light associated shadow generator.
  13945. */
  13946. Light.prototype.getShadowGenerator = function () {
  13947. return this._shadowGenerator;
  13948. };
  13949. /**
  13950. * Returns a Vector3, the absolute light position in the World.
  13951. */
  13952. Light.prototype.getAbsolutePosition = function () {
  13953. return BABYLON.Vector3.Zero();
  13954. };
  13955. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13956. };
  13957. Light.prototype._getWorldMatrix = function () {
  13958. return BABYLON.Matrix.Identity();
  13959. };
  13960. /**
  13961. * Boolean : True if the light will affect the passed mesh.
  13962. */
  13963. Light.prototype.canAffectMesh = function (mesh) {
  13964. if (!mesh) {
  13965. return true;
  13966. }
  13967. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13968. return false;
  13969. }
  13970. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13971. return false;
  13972. }
  13973. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13974. return false;
  13975. }
  13976. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13977. return false;
  13978. }
  13979. return true;
  13980. };
  13981. /**
  13982. * Returns the light World matrix.
  13983. */
  13984. Light.prototype.getWorldMatrix = function () {
  13985. this._currentRenderId = this.getScene().getRenderId();
  13986. var worldMatrix = this._getWorldMatrix();
  13987. if (this.parent && this.parent.getWorldMatrix) {
  13988. if (!this._parentedWorldMatrix) {
  13989. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13990. }
  13991. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13992. this._markSyncedWithParent();
  13993. return this._parentedWorldMatrix;
  13994. }
  13995. return worldMatrix;
  13996. };
  13997. /**
  13998. * Sort function to order lights for rendering.
  13999. * @param a First Light object to compare to second.
  14000. * @param b Second Light object to compare first.
  14001. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14002. */
  14003. Light.compareLightsPriority = function (a, b) {
  14004. //shadow-casting lights have priority over non-shadow-casting lights
  14005. //the renderPrioirty is a secondary sort criterion
  14006. if (a.shadowEnabled !== b.shadowEnabled) {
  14007. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14008. }
  14009. return b.renderPriority - a.renderPriority;
  14010. };
  14011. /**
  14012. * Disposes the light.
  14013. */
  14014. Light.prototype.dispose = function () {
  14015. if (this._shadowGenerator) {
  14016. this._shadowGenerator.dispose();
  14017. this._shadowGenerator = null;
  14018. }
  14019. // Animations
  14020. this.getScene().stopAnimation(this);
  14021. // Remove from meshes
  14022. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14023. var mesh = _a[_i];
  14024. mesh._removeLightSource(this);
  14025. }
  14026. this._uniformBuffer.dispose();
  14027. // Remove from scene
  14028. this.getScene().removeLight(this);
  14029. _super.prototype.dispose.call(this);
  14030. };
  14031. /**
  14032. * Returns the light type ID (integer).
  14033. */
  14034. Light.prototype.getTypeID = function () {
  14035. return 0;
  14036. };
  14037. /**
  14038. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14039. */
  14040. Light.prototype.getScaledIntensity = function () {
  14041. return this._photometricScale * this.intensity;
  14042. };
  14043. /**
  14044. * Returns a new Light object, named "name", from the current one.
  14045. */
  14046. Light.prototype.clone = function (name) {
  14047. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14048. };
  14049. /**
  14050. * Serializes the current light into a Serialization object.
  14051. * Returns the serialized object.
  14052. */
  14053. Light.prototype.serialize = function () {
  14054. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14055. // Type
  14056. serializationObject.type = this.getTypeID();
  14057. // Parent
  14058. if (this.parent) {
  14059. serializationObject.parentId = this.parent.id;
  14060. }
  14061. // Inclusion / exclusions
  14062. if (this.excludedMeshes.length > 0) {
  14063. serializationObject.excludedMeshesIds = [];
  14064. this.excludedMeshes.forEach(function (mesh) {
  14065. serializationObject.excludedMeshesIds.push(mesh.id);
  14066. });
  14067. }
  14068. if (this.includedOnlyMeshes.length > 0) {
  14069. serializationObject.includedOnlyMeshesIds = [];
  14070. this.includedOnlyMeshes.forEach(function (mesh) {
  14071. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14072. });
  14073. }
  14074. // Animations
  14075. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14076. serializationObject.ranges = this.serializeAnimationRanges();
  14077. return serializationObject;
  14078. };
  14079. /**
  14080. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14081. * This new light is named "name" and added to the passed scene.
  14082. */
  14083. Light.GetConstructorFromName = function (type, name, scene) {
  14084. switch (type) {
  14085. case 0:
  14086. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14087. case 1:
  14088. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14089. case 2:
  14090. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14091. case 3:
  14092. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14093. }
  14094. };
  14095. /**
  14096. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14097. */
  14098. Light.Parse = function (parsedLight, scene) {
  14099. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14100. // Inclusion / exclusions
  14101. if (parsedLight.excludedMeshesIds) {
  14102. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14103. }
  14104. if (parsedLight.includedOnlyMeshesIds) {
  14105. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14106. }
  14107. // Parent
  14108. if (parsedLight.parentId) {
  14109. light._waitingParentId = parsedLight.parentId;
  14110. }
  14111. // Animations
  14112. if (parsedLight.animations) {
  14113. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14114. var parsedAnimation = parsedLight.animations[animationIndex];
  14115. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14116. }
  14117. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14118. }
  14119. if (parsedLight.autoAnimate) {
  14120. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14121. }
  14122. return light;
  14123. };
  14124. Light.prototype._hookArrayForExcluded = function (array) {
  14125. var _this = this;
  14126. var oldPush = array.push;
  14127. array.push = function () {
  14128. var items = [];
  14129. for (var _i = 0; _i < arguments.length; _i++) {
  14130. items[_i] = arguments[_i];
  14131. }
  14132. var result = oldPush.apply(array, items);
  14133. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14134. var item = items_1[_a];
  14135. item._resyncLighSource(_this);
  14136. }
  14137. return result;
  14138. };
  14139. var oldSplice = array.splice;
  14140. array.splice = function (index, deleteCount) {
  14141. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14142. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14143. var item = deleted_1[_i];
  14144. item._resyncLighSource(_this);
  14145. }
  14146. return deleted;
  14147. };
  14148. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14149. var item = array_1[_i];
  14150. item._resyncLighSource(this);
  14151. }
  14152. };
  14153. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14154. var _this = this;
  14155. var oldPush = array.push;
  14156. array.push = function () {
  14157. var items = [];
  14158. for (var _i = 0; _i < arguments.length; _i++) {
  14159. items[_i] = arguments[_i];
  14160. }
  14161. var result = oldPush.apply(array, items);
  14162. _this._resyncMeshes();
  14163. return result;
  14164. };
  14165. var oldSplice = array.splice;
  14166. array.splice = function (index, deleteCount) {
  14167. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14168. _this._resyncMeshes();
  14169. return deleted;
  14170. };
  14171. this._resyncMeshes();
  14172. };
  14173. Light.prototype._resyncMeshes = function () {
  14174. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14175. var mesh = _a[_i];
  14176. mesh._resyncLighSource(this);
  14177. }
  14178. };
  14179. Light.prototype._markMeshesAsLightDirty = function () {
  14180. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14181. var mesh = _a[_i];
  14182. if (mesh._lightSources.indexOf(this) !== -1) {
  14183. mesh._markSubMeshesAsLightDirty();
  14184. }
  14185. }
  14186. };
  14187. /**
  14188. * Recomputes the cached photometric scale if needed.
  14189. */
  14190. Light.prototype._computePhotometricScale = function () {
  14191. this._photometricScale = this._getPhotometricScale();
  14192. this.getScene().resetCachedMaterial();
  14193. };
  14194. /**
  14195. * Returns the Photometric Scale according to the light type and intensity mode.
  14196. */
  14197. Light.prototype._getPhotometricScale = function () {
  14198. var photometricScale = 0.0;
  14199. var lightTypeID = this.getTypeID();
  14200. //get photometric mode
  14201. var photometricMode = this.intensityMode;
  14202. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14203. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14204. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14205. }
  14206. else {
  14207. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14208. }
  14209. }
  14210. //compute photometric scale
  14211. switch (lightTypeID) {
  14212. case Light.LIGHTTYPEID_POINTLIGHT:
  14213. case Light.LIGHTTYPEID_SPOTLIGHT:
  14214. switch (photometricMode) {
  14215. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14216. photometricScale = 1.0 / (4.0 * Math.PI);
  14217. break;
  14218. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14219. photometricScale = 1.0;
  14220. break;
  14221. case Light.INTENSITYMODE_LUMINANCE:
  14222. photometricScale = this.radius * this.radius;
  14223. break;
  14224. }
  14225. break;
  14226. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14227. switch (photometricMode) {
  14228. case Light.INTENSITYMODE_ILLUMINANCE:
  14229. photometricScale = 1.0;
  14230. break;
  14231. case Light.INTENSITYMODE_LUMINANCE:
  14232. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14233. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14234. var apexAngleRadians = this.radius;
  14235. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14236. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14237. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14238. photometricScale = solidAngle;
  14239. break;
  14240. }
  14241. break;
  14242. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14243. // No fall off in hemisperic light.
  14244. photometricScale = 1.0;
  14245. break;
  14246. }
  14247. return photometricScale;
  14248. };
  14249. Light.prototype._reorderLightsInScene = function () {
  14250. var scene = this.getScene();
  14251. if (this.renderPriority != 0) {
  14252. scene.requireLightSorting = true;
  14253. }
  14254. this.getScene().sortLightsByPriority();
  14255. };
  14256. return Light;
  14257. }(BABYLON.Node));
  14258. //lightmapMode Consts
  14259. Light._LIGHTMAP_DEFAULT = 0;
  14260. Light._LIGHTMAP_SPECULAR = 1;
  14261. Light._LIGHTMAP_SHADOWSONLY = 2;
  14262. // Intensity Mode Consts
  14263. Light._INTENSITYMODE_AUTOMATIC = 0;
  14264. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14265. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14266. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14267. Light._INTENSITYMODE_LUMINANCE = 4;
  14268. // Light types ids const.
  14269. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14270. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14271. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14272. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14273. __decorate([
  14274. BABYLON.serializeAsColor3()
  14275. ], Light.prototype, "diffuse", void 0);
  14276. __decorate([
  14277. BABYLON.serializeAsColor3()
  14278. ], Light.prototype, "specular", void 0);
  14279. __decorate([
  14280. BABYLON.serialize()
  14281. ], Light.prototype, "intensity", void 0);
  14282. __decorate([
  14283. BABYLON.serialize()
  14284. ], Light.prototype, "range", void 0);
  14285. __decorate([
  14286. BABYLON.serialize()
  14287. ], Light.prototype, "intensityMode", null);
  14288. __decorate([
  14289. BABYLON.serialize()
  14290. ], Light.prototype, "radius", null);
  14291. __decorate([
  14292. BABYLON.serialize()
  14293. ], Light.prototype, "_renderPriority", void 0);
  14294. __decorate([
  14295. BABYLON.expandToProperty("_reorderLightsInScene")
  14296. ], Light.prototype, "renderPriority", void 0);
  14297. __decorate([
  14298. BABYLON.serialize()
  14299. ], Light.prototype, "shadowEnabled", void 0);
  14300. __decorate([
  14301. BABYLON.serialize("excludeWithLayerMask")
  14302. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14303. __decorate([
  14304. BABYLON.serialize("includeOnlyWithLayerMask")
  14305. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14306. __decorate([
  14307. BABYLON.serialize("lightmapMode")
  14308. ], Light.prototype, "_lightmapMode", void 0);
  14309. BABYLON.Light = Light;
  14310. })(BABYLON || (BABYLON = {}));
  14311. //# sourceMappingURL=babylon.light.js.map
  14312. var BABYLON;
  14313. (function (BABYLON) {
  14314. var Camera = (function (_super) {
  14315. __extends(Camera, _super);
  14316. function Camera(name, position, scene) {
  14317. var _this = _super.call(this, name, scene) || this;
  14318. _this.upVector = BABYLON.Vector3.Up();
  14319. _this.orthoLeft = null;
  14320. _this.orthoRight = null;
  14321. _this.orthoBottom = null;
  14322. _this.orthoTop = null;
  14323. _this.fov = 0.8;
  14324. _this.minZ = 1.0;
  14325. _this.maxZ = 10000.0;
  14326. _this.inertia = 0.9;
  14327. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14328. _this.isIntermediate = false;
  14329. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14330. _this.layerMask = 0x0FFFFFFF;
  14331. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14332. // Camera rig members
  14333. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14334. _this._rigCameras = new Array();
  14335. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14336. _this.customRenderTargets = new Array();
  14337. // Observables
  14338. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14339. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14340. // Cache
  14341. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14342. _this._projectionMatrix = new BABYLON.Matrix();
  14343. _this._doNotComputeProjectionMatrix = false;
  14344. _this._postProcesses = new Array();
  14345. _this._transformMatrix = BABYLON.Matrix.Zero();
  14346. _this._activeMeshes = new BABYLON.SmartArray(256);
  14347. _this._globalPosition = BABYLON.Vector3.Zero();
  14348. _this._refreshFrustumPlanes = true;
  14349. _this.getScene().addCamera(_this);
  14350. if (!_this.getScene().activeCamera) {
  14351. _this.getScene().activeCamera = _this;
  14352. }
  14353. _this.position = position;
  14354. return _this;
  14355. }
  14356. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14357. get: function () {
  14358. return Camera._PERSPECTIVE_CAMERA;
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14364. get: function () {
  14365. return Camera._ORTHOGRAPHIC_CAMERA;
  14366. },
  14367. enumerable: true,
  14368. configurable: true
  14369. });
  14370. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14371. get: function () {
  14372. return Camera._FOVMODE_VERTICAL_FIXED;
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14378. get: function () {
  14379. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14385. get: function () {
  14386. return Camera._RIG_MODE_NONE;
  14387. },
  14388. enumerable: true,
  14389. configurable: true
  14390. });
  14391. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14392. get: function () {
  14393. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14394. },
  14395. enumerable: true,
  14396. configurable: true
  14397. });
  14398. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14399. get: function () {
  14400. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14401. },
  14402. enumerable: true,
  14403. configurable: true
  14404. });
  14405. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14406. get: function () {
  14407. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14408. },
  14409. enumerable: true,
  14410. configurable: true
  14411. });
  14412. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14413. get: function () {
  14414. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14415. },
  14416. enumerable: true,
  14417. configurable: true
  14418. });
  14419. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14420. get: function () {
  14421. return Camera._RIG_MODE_VR;
  14422. },
  14423. enumerable: true,
  14424. configurable: true
  14425. });
  14426. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14427. get: function () {
  14428. return Camera._RIG_MODE_WEBVR;
  14429. },
  14430. enumerable: true,
  14431. configurable: true
  14432. });
  14433. Camera.prototype.getClassName = function () {
  14434. return "Camera";
  14435. };
  14436. /**
  14437. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14438. */
  14439. Camera.prototype.toString = function (fullDetails) {
  14440. var ret = "Name: " + this.name;
  14441. ret += ", type: " + this.getClassName();
  14442. if (this.animations) {
  14443. for (var i = 0; i < this.animations.length; i++) {
  14444. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14445. }
  14446. }
  14447. if (fullDetails) {
  14448. }
  14449. return ret;
  14450. };
  14451. Object.defineProperty(Camera.prototype, "globalPosition", {
  14452. get: function () {
  14453. return this._globalPosition;
  14454. },
  14455. enumerable: true,
  14456. configurable: true
  14457. });
  14458. Camera.prototype.getActiveMeshes = function () {
  14459. return this._activeMeshes;
  14460. };
  14461. Camera.prototype.isActiveMesh = function (mesh) {
  14462. return (this._activeMeshes.indexOf(mesh) !== -1);
  14463. };
  14464. //Cache
  14465. Camera.prototype._initCache = function () {
  14466. _super.prototype._initCache.call(this);
  14467. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14468. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14469. this._cache.mode = undefined;
  14470. this._cache.minZ = undefined;
  14471. this._cache.maxZ = undefined;
  14472. this._cache.fov = undefined;
  14473. this._cache.fovMode = undefined;
  14474. this._cache.aspectRatio = undefined;
  14475. this._cache.orthoLeft = undefined;
  14476. this._cache.orthoRight = undefined;
  14477. this._cache.orthoBottom = undefined;
  14478. this._cache.orthoTop = undefined;
  14479. this._cache.renderWidth = undefined;
  14480. this._cache.renderHeight = undefined;
  14481. };
  14482. Camera.prototype._updateCache = function (ignoreParentClass) {
  14483. if (!ignoreParentClass) {
  14484. _super.prototype._updateCache.call(this);
  14485. }
  14486. var engine = this.getEngine();
  14487. this._cache.position.copyFrom(this.position);
  14488. this._cache.upVector.copyFrom(this.upVector);
  14489. this._cache.mode = this.mode;
  14490. this._cache.minZ = this.minZ;
  14491. this._cache.maxZ = this.maxZ;
  14492. this._cache.fov = this.fov;
  14493. this._cache.fovMode = this.fovMode;
  14494. this._cache.aspectRatio = engine.getAspectRatio(this);
  14495. this._cache.orthoLeft = this.orthoLeft;
  14496. this._cache.orthoRight = this.orthoRight;
  14497. this._cache.orthoBottom = this.orthoBottom;
  14498. this._cache.orthoTop = this.orthoTop;
  14499. this._cache.renderWidth = engine.getRenderWidth();
  14500. this._cache.renderHeight = engine.getRenderHeight();
  14501. };
  14502. Camera.prototype._updateFromScene = function () {
  14503. this.updateCache();
  14504. this.update();
  14505. };
  14506. // Synchronized
  14507. Camera.prototype._isSynchronized = function () {
  14508. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14509. };
  14510. Camera.prototype._isSynchronizedViewMatrix = function () {
  14511. if (!_super.prototype._isSynchronized.call(this))
  14512. return false;
  14513. return this._cache.position.equals(this.position)
  14514. && this._cache.upVector.equals(this.upVector)
  14515. && this.isSynchronizedWithParent();
  14516. };
  14517. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14518. var check = this._cache.mode === this.mode
  14519. && this._cache.minZ === this.minZ
  14520. && this._cache.maxZ === this.maxZ;
  14521. if (!check) {
  14522. return false;
  14523. }
  14524. var engine = this.getEngine();
  14525. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14526. check = this._cache.fov === this.fov
  14527. && this._cache.fovMode === this.fovMode
  14528. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14529. }
  14530. else {
  14531. check = this._cache.orthoLeft === this.orthoLeft
  14532. && this._cache.orthoRight === this.orthoRight
  14533. && this._cache.orthoBottom === this.orthoBottom
  14534. && this._cache.orthoTop === this.orthoTop
  14535. && this._cache.renderWidth === engine.getRenderWidth()
  14536. && this._cache.renderHeight === engine.getRenderHeight();
  14537. }
  14538. return check;
  14539. };
  14540. // Controls
  14541. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14542. };
  14543. Camera.prototype.detachControl = function (element) {
  14544. };
  14545. Camera.prototype.update = function () {
  14546. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14547. this._updateRigCameras();
  14548. }
  14549. this._checkInputs();
  14550. };
  14551. Camera.prototype._checkInputs = function () {
  14552. };
  14553. Object.defineProperty(Camera.prototype, "rigCameras", {
  14554. get: function () {
  14555. return this._rigCameras;
  14556. },
  14557. enumerable: true,
  14558. configurable: true
  14559. });
  14560. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14561. get: function () {
  14562. return this._rigPostProcess;
  14563. },
  14564. enumerable: true,
  14565. configurable: true
  14566. });
  14567. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14568. // invalidate framebuffer
  14569. if (this._postProcesses.length > 0) {
  14570. this._postProcesses[0].markTextureDirty();
  14571. }
  14572. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14573. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14574. var cam = this._rigCameras[i];
  14575. var rigPostProcess = cam._rigPostProcess;
  14576. // for VR rig, there does not have to be a post process
  14577. if (rigPostProcess) {
  14578. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14579. if (isPass) {
  14580. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14581. cam.isIntermediate = this._postProcesses.length === 0;
  14582. }
  14583. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14584. rigPostProcess.markTextureDirty();
  14585. }
  14586. else {
  14587. cam._postProcesses = this._postProcesses.slice(0);
  14588. }
  14589. }
  14590. };
  14591. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14592. if (insertAt === void 0) { insertAt = null; }
  14593. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14594. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14595. return 0;
  14596. }
  14597. if (insertAt == null || insertAt < 0) {
  14598. this._postProcesses.push(postProcess);
  14599. }
  14600. else {
  14601. this._postProcesses.splice(insertAt, 0, postProcess);
  14602. }
  14603. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14604. return this._postProcesses.indexOf(postProcess);
  14605. };
  14606. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14607. if (atIndices === void 0) { atIndices = null; }
  14608. var result = [];
  14609. var i;
  14610. var index;
  14611. if (!atIndices) {
  14612. var idx = this._postProcesses.indexOf(postProcess);
  14613. if (idx !== -1) {
  14614. this._postProcesses.splice(idx, 1);
  14615. }
  14616. }
  14617. else {
  14618. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14619. // iterate descending, so can just splice as we go
  14620. for (i = atIndices.length - 1; i >= 0; i--) {
  14621. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14622. result.push(i);
  14623. continue;
  14624. }
  14625. index = atIndices[i];
  14626. this._postProcesses.splice(index, 1);
  14627. }
  14628. }
  14629. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14630. return result;
  14631. };
  14632. Camera.prototype.getWorldMatrix = function () {
  14633. if (!this._worldMatrix) {
  14634. this._worldMatrix = BABYLON.Matrix.Identity();
  14635. }
  14636. var viewMatrix = this.getViewMatrix();
  14637. viewMatrix.invertToRef(this._worldMatrix);
  14638. return this._worldMatrix;
  14639. };
  14640. Camera.prototype._getViewMatrix = function () {
  14641. return BABYLON.Matrix.Identity();
  14642. };
  14643. Camera.prototype.getViewMatrix = function (force) {
  14644. if (!force && this._isSynchronizedViewMatrix()) {
  14645. return this._computedViewMatrix;
  14646. }
  14647. this._computedViewMatrix = this._getViewMatrix();
  14648. this._currentRenderId = this.getScene().getRenderId();
  14649. this._refreshFrustumPlanes = true;
  14650. if (!this.parent || !this.parent.getWorldMatrix) {
  14651. this._globalPosition.copyFrom(this.position);
  14652. }
  14653. else {
  14654. if (!this._worldMatrix) {
  14655. this._worldMatrix = BABYLON.Matrix.Identity();
  14656. }
  14657. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14658. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14659. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14660. this._computedViewMatrix.invert();
  14661. this._markSyncedWithParent();
  14662. }
  14663. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14664. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14665. }
  14666. this.onViewMatrixChangedObservable.notifyObservers(this);
  14667. return this._computedViewMatrix;
  14668. };
  14669. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14670. this._doNotComputeProjectionMatrix = true;
  14671. if (projection !== undefined) {
  14672. this._projectionMatrix = projection;
  14673. }
  14674. };
  14675. ;
  14676. Camera.prototype.unfreezeProjectionMatrix = function () {
  14677. this._doNotComputeProjectionMatrix = false;
  14678. };
  14679. ;
  14680. Camera.prototype.getProjectionMatrix = function (force) {
  14681. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14682. return this._projectionMatrix;
  14683. }
  14684. this._refreshFrustumPlanes = true;
  14685. var engine = this.getEngine();
  14686. var scene = this.getScene();
  14687. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14688. if (this.minZ <= 0) {
  14689. this.minZ = 0.1;
  14690. }
  14691. if (scene.useRightHandedSystem) {
  14692. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14693. }
  14694. else {
  14695. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14696. }
  14697. }
  14698. else {
  14699. var halfWidth = engine.getRenderWidth() / 2.0;
  14700. var halfHeight = engine.getRenderHeight() / 2.0;
  14701. if (scene.useRightHandedSystem) {
  14702. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14703. }
  14704. else {
  14705. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14706. }
  14707. }
  14708. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  14709. return this._projectionMatrix;
  14710. };
  14711. Camera.prototype.getTranformationMatrix = function () {
  14712. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14713. return this._transformMatrix;
  14714. };
  14715. Camera.prototype.updateFrustumPlanes = function () {
  14716. if (!this._refreshFrustumPlanes) {
  14717. return;
  14718. }
  14719. this.getTranformationMatrix();
  14720. if (!this._frustumPlanes) {
  14721. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14722. }
  14723. else {
  14724. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14725. }
  14726. this._refreshFrustumPlanes = false;
  14727. };
  14728. Camera.prototype.isInFrustum = function (target) {
  14729. this.updateFrustumPlanes();
  14730. return target.isInFrustum(this._frustumPlanes);
  14731. };
  14732. Camera.prototype.isCompletelyInFrustum = function (target) {
  14733. this.updateFrustumPlanes();
  14734. return target.isCompletelyInFrustum(this._frustumPlanes);
  14735. };
  14736. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14737. if (length === void 0) { length = 100; }
  14738. if (!transform) {
  14739. transform = this.getWorldMatrix();
  14740. }
  14741. if (!origin) {
  14742. origin = this.position;
  14743. }
  14744. var forward = new BABYLON.Vector3(0, 0, 1);
  14745. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14746. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14747. return new BABYLON.Ray(origin, direction, length);
  14748. };
  14749. Camera.prototype.dispose = function () {
  14750. // Observables
  14751. this.onViewMatrixChangedObservable.clear();
  14752. this.onProjectionMatrixChangedObservable.clear();
  14753. // Animations
  14754. this.getScene().stopAnimation(this);
  14755. // Remove from scene
  14756. this.getScene().removeCamera(this);
  14757. while (this._rigCameras.length > 0) {
  14758. this._rigCameras.pop().dispose();
  14759. }
  14760. // Postprocesses
  14761. var i = this._postProcesses.length;
  14762. while (--i >= 0) {
  14763. this._postProcesses[i].dispose(this);
  14764. }
  14765. _super.prototype.dispose.call(this);
  14766. };
  14767. Object.defineProperty(Camera.prototype, "leftCamera", {
  14768. // ---- Camera rigs section ----
  14769. get: function () {
  14770. if (this._rigCameras.length < 1) {
  14771. return undefined;
  14772. }
  14773. return this._rigCameras[0];
  14774. },
  14775. enumerable: true,
  14776. configurable: true
  14777. });
  14778. Object.defineProperty(Camera.prototype, "rightCamera", {
  14779. get: function () {
  14780. if (this._rigCameras.length < 2) {
  14781. return undefined;
  14782. }
  14783. return this._rigCameras[1];
  14784. },
  14785. enumerable: true,
  14786. configurable: true
  14787. });
  14788. Camera.prototype.getLeftTarget = function () {
  14789. if (this._rigCameras.length < 1) {
  14790. return undefined;
  14791. }
  14792. return this._rigCameras[0].getTarget();
  14793. };
  14794. Camera.prototype.getRightTarget = function () {
  14795. if (this._rigCameras.length < 2) {
  14796. return undefined;
  14797. }
  14798. return this._rigCameras[1].getTarget();
  14799. };
  14800. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14801. while (this._rigCameras.length > 0) {
  14802. this._rigCameras.pop().dispose();
  14803. }
  14804. this.cameraRigMode = mode;
  14805. this._cameraRigParams = {};
  14806. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14807. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14808. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14809. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14810. // create the rig cameras, unless none
  14811. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14812. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14813. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14814. }
  14815. switch (this.cameraRigMode) {
  14816. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14817. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14818. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14819. break;
  14820. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14821. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14822. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14823. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14824. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14825. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14826. break;
  14827. case Camera.RIG_MODE_VR:
  14828. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14829. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14830. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14831. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14832. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14833. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14834. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14835. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14836. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14837. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14838. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14839. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14840. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14841. if (metrics.compensateDistortion) {
  14842. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14843. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14844. }
  14845. break;
  14846. case Camera.RIG_MODE_WEBVR:
  14847. if (rigParams.vrDisplay) {
  14848. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14849. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14850. //Left eye
  14851. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14852. this._rigCameras[0].setCameraRigParameter("left", true);
  14853. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14854. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14855. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14856. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14857. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14858. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14859. this._rigCameras[0].parent = this;
  14860. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14861. //Right eye
  14862. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14863. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14864. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14865. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14866. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14867. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14868. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14869. this._rigCameras[1].parent = this;
  14870. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14871. }
  14872. break;
  14873. }
  14874. this._cascadePostProcessesToRigCams();
  14875. this.
  14876. update();
  14877. };
  14878. Camera.prototype._getVRProjectionMatrix = function () {
  14879. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14880. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14881. return this._projectionMatrix;
  14882. };
  14883. Camera.prototype._updateCameraRotationMatrix = function () {
  14884. //Here for WebVR
  14885. };
  14886. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14887. //Here for WebVR
  14888. };
  14889. /**
  14890. * This function MUST be overwritten by the different WebVR cameras available.
  14891. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14892. */
  14893. Camera.prototype._getWebVRProjectionMatrix = function () {
  14894. return BABYLON.Matrix.Identity();
  14895. };
  14896. /**
  14897. * This function MUST be overwritten by the different WebVR cameras available.
  14898. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14899. */
  14900. Camera.prototype._getWebVRViewMatrix = function () {
  14901. return BABYLON.Matrix.Identity();
  14902. };
  14903. Camera.prototype.setCameraRigParameter = function (name, value) {
  14904. if (!this._cameraRigParams) {
  14905. this._cameraRigParams = {};
  14906. }
  14907. this._cameraRigParams[name] = value;
  14908. //provisionnally:
  14909. if (name === "interaxialDistance") {
  14910. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14911. }
  14912. };
  14913. /**
  14914. * needs to be overridden by children so sub has required properties to be copied
  14915. */
  14916. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14917. return null;
  14918. };
  14919. /**
  14920. * May need to be overridden by children
  14921. */
  14922. Camera.prototype._updateRigCameras = function () {
  14923. for (var i = 0; i < this._rigCameras.length; i++) {
  14924. this._rigCameras[i].minZ = this.minZ;
  14925. this._rigCameras[i].maxZ = this.maxZ;
  14926. this._rigCameras[i].fov = this.fov;
  14927. }
  14928. // only update viewport when ANAGLYPH
  14929. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14930. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14931. }
  14932. };
  14933. Camera.prototype._setupInputs = function () {
  14934. };
  14935. Camera.prototype.serialize = function () {
  14936. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14937. // Type
  14938. serializationObject.type = this.getClassName();
  14939. // Parent
  14940. if (this.parent) {
  14941. serializationObject.parentId = this.parent.id;
  14942. }
  14943. if (this.inputs) {
  14944. this.inputs.serialize(serializationObject);
  14945. }
  14946. // Animations
  14947. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14948. serializationObject.ranges = this.serializeAnimationRanges();
  14949. return serializationObject;
  14950. };
  14951. Camera.prototype.clone = function (name) {
  14952. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14953. };
  14954. Camera.prototype.getDirection = function (localAxis) {
  14955. var result = BABYLON.Vector3.Zero();
  14956. this.getDirectionToRef(localAxis, result);
  14957. return result;
  14958. };
  14959. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14960. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14961. };
  14962. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14963. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14964. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14965. switch (type) {
  14966. case "ArcRotateCamera":
  14967. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14968. case "DeviceOrientationCamera":
  14969. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14970. case "FollowCamera":
  14971. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14972. case "ArcFollowCamera":
  14973. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14974. case "GamepadCamera":
  14975. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14976. case "TouchCamera":
  14977. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14978. case "VirtualJoysticksCamera":
  14979. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14980. case "WebVRFreeCamera":
  14981. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14982. case "WebVRGamepadCamera":
  14983. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14984. case "VRDeviceOrientationFreeCamera":
  14985. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14986. case "VRDeviceOrientationGamepadCamera":
  14987. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14988. case "AnaglyphArcRotateCamera":
  14989. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14990. case "AnaglyphFreeCamera":
  14991. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14992. case "AnaglyphGamepadCamera":
  14993. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14994. case "AnaglyphUniversalCamera":
  14995. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14996. case "StereoscopicArcRotateCamera":
  14997. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14998. case "StereoscopicFreeCamera":
  14999. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15000. case "StereoscopicGamepadCamera":
  15001. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15002. case "StereoscopicUniversalCamera":
  15003. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15004. case "FreeCamera":
  15005. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15006. default:
  15007. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15008. }
  15009. };
  15010. Camera.Parse = function (parsedCamera, scene) {
  15011. var type = parsedCamera.type;
  15012. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15013. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15014. // Parent
  15015. if (parsedCamera.parentId) {
  15016. camera._waitingParentId = parsedCamera.parentId;
  15017. }
  15018. //If camera has an input manager, let it parse inputs settings
  15019. if (camera.inputs) {
  15020. camera.inputs.parse(parsedCamera);
  15021. camera._setupInputs();
  15022. }
  15023. if (camera.setPosition) {
  15024. camera.position.copyFromFloats(0, 0, 0);
  15025. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15026. }
  15027. // Target
  15028. if (parsedCamera.target) {
  15029. if (camera.setTarget) {
  15030. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15031. }
  15032. }
  15033. // Apply 3d rig, when found
  15034. if (parsedCamera.cameraRigMode) {
  15035. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15036. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15037. }
  15038. // Animations
  15039. if (parsedCamera.animations) {
  15040. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15041. var parsedAnimation = parsedCamera.animations[animationIndex];
  15042. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15043. }
  15044. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15045. }
  15046. if (parsedCamera.autoAnimate) {
  15047. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15048. }
  15049. return camera;
  15050. };
  15051. return Camera;
  15052. }(BABYLON.Node));
  15053. // Statics
  15054. Camera._PERSPECTIVE_CAMERA = 0;
  15055. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15056. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15057. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15058. Camera._RIG_MODE_NONE = 0;
  15059. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15060. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15061. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15062. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15063. Camera._RIG_MODE_VR = 20;
  15064. Camera._RIG_MODE_WEBVR = 21;
  15065. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15066. __decorate([
  15067. BABYLON.serializeAsVector3()
  15068. ], Camera.prototype, "position", void 0);
  15069. __decorate([
  15070. BABYLON.serializeAsVector3()
  15071. ], Camera.prototype, "upVector", void 0);
  15072. __decorate([
  15073. BABYLON.serialize()
  15074. ], Camera.prototype, "orthoLeft", void 0);
  15075. __decorate([
  15076. BABYLON.serialize()
  15077. ], Camera.prototype, "orthoRight", void 0);
  15078. __decorate([
  15079. BABYLON.serialize()
  15080. ], Camera.prototype, "orthoBottom", void 0);
  15081. __decorate([
  15082. BABYLON.serialize()
  15083. ], Camera.prototype, "orthoTop", void 0);
  15084. __decorate([
  15085. BABYLON.serialize()
  15086. ], Camera.prototype, "fov", void 0);
  15087. __decorate([
  15088. BABYLON.serialize()
  15089. ], Camera.prototype, "minZ", void 0);
  15090. __decorate([
  15091. BABYLON.serialize()
  15092. ], Camera.prototype, "maxZ", void 0);
  15093. __decorate([
  15094. BABYLON.serialize()
  15095. ], Camera.prototype, "inertia", void 0);
  15096. __decorate([
  15097. BABYLON.serialize()
  15098. ], Camera.prototype, "mode", void 0);
  15099. __decorate([
  15100. BABYLON.serialize()
  15101. ], Camera.prototype, "layerMask", void 0);
  15102. __decorate([
  15103. BABYLON.serialize()
  15104. ], Camera.prototype, "fovMode", void 0);
  15105. __decorate([
  15106. BABYLON.serialize()
  15107. ], Camera.prototype, "cameraRigMode", void 0);
  15108. __decorate([
  15109. BABYLON.serialize()
  15110. ], Camera.prototype, "interaxialDistance", void 0);
  15111. __decorate([
  15112. BABYLON.serialize()
  15113. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15114. BABYLON.Camera = Camera;
  15115. })(BABYLON || (BABYLON = {}));
  15116. //# sourceMappingURL=babylon.camera.js.map
  15117. var BABYLON;
  15118. (function (BABYLON) {
  15119. var RenderingManager = (function () {
  15120. function RenderingManager(scene) {
  15121. this._renderingGroups = new Array();
  15122. this._autoClearDepthStencil = {};
  15123. this._customOpaqueSortCompareFn = {};
  15124. this._customAlphaTestSortCompareFn = {};
  15125. this._customTransparentSortCompareFn = {};
  15126. this._renderinGroupInfo = null;
  15127. this._scene = scene;
  15128. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15129. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15130. }
  15131. }
  15132. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15133. if (depth === void 0) { depth = true; }
  15134. if (stencil === void 0) { stencil = true; }
  15135. if (this._depthStencilBufferAlreadyCleaned) {
  15136. return;
  15137. }
  15138. this._scene.getEngine().clear(null, false, depth, stencil);
  15139. this._depthStencilBufferAlreadyCleaned = true;
  15140. };
  15141. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15142. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15143. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15144. var info = null;
  15145. if (observable) {
  15146. if (!this._renderinGroupInfo) {
  15147. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15148. }
  15149. info = this._renderinGroupInfo;
  15150. info.scene = this._scene;
  15151. info.camera = this._scene.activeCamera;
  15152. }
  15153. // Dispatch sprites
  15154. if (renderSprites) {
  15155. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15156. var manager = this._scene.spriteManagers[index];
  15157. this.dispatchSprites(manager);
  15158. }
  15159. }
  15160. // Render
  15161. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15162. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15163. var renderingGroup = this._renderingGroups[index];
  15164. if (!renderingGroup && !observable)
  15165. continue;
  15166. this._currentIndex = index;
  15167. var renderingGroupMask = 0;
  15168. // Fire PRECLEAR stage
  15169. if (observable) {
  15170. renderingGroupMask = Math.pow(2, index);
  15171. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15172. info.renderingGroupId = index;
  15173. observable.notifyObservers(info, renderingGroupMask);
  15174. }
  15175. // Clear depth/stencil if needed
  15176. if (RenderingManager.AUTOCLEAR) {
  15177. var autoClear = this._autoClearDepthStencil[index];
  15178. if (autoClear && autoClear.autoClear) {
  15179. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15180. }
  15181. }
  15182. if (observable) {
  15183. // Fire PREOPAQUE stage
  15184. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15185. observable.notifyObservers(info, renderingGroupMask);
  15186. // Fire PRETRANSPARENT stage
  15187. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15188. observable.notifyObservers(info, renderingGroupMask);
  15189. }
  15190. if (renderingGroup)
  15191. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15192. // Fire POSTTRANSPARENT stage
  15193. if (observable) {
  15194. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15195. observable.notifyObservers(info, renderingGroupMask);
  15196. }
  15197. }
  15198. };
  15199. RenderingManager.prototype.reset = function () {
  15200. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15201. var renderingGroup = this._renderingGroups[index];
  15202. if (renderingGroup) {
  15203. renderingGroup.prepare();
  15204. }
  15205. }
  15206. };
  15207. RenderingManager.prototype.dispose = function () {
  15208. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15209. var renderingGroup = this._renderingGroups[index];
  15210. if (renderingGroup) {
  15211. renderingGroup.dispose();
  15212. }
  15213. }
  15214. this._renderingGroups.length = 0;
  15215. };
  15216. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15217. if (!this._renderingGroups[renderingGroupId]) {
  15218. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15219. }
  15220. };
  15221. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15222. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15223. this._prepareRenderingGroup(renderingGroupId);
  15224. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15225. };
  15226. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15227. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15228. this._prepareRenderingGroup(renderingGroupId);
  15229. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15230. };
  15231. RenderingManager.prototype.dispatch = function (subMesh) {
  15232. var mesh = subMesh.getMesh();
  15233. var renderingGroupId = mesh.renderingGroupId || 0;
  15234. this._prepareRenderingGroup(renderingGroupId);
  15235. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15236. };
  15237. /**
  15238. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15239. * This allowed control for front to back rendering or reversly depending of the special needs.
  15240. *
  15241. * @param renderingGroupId The rendering group id corresponding to its index
  15242. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15243. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15244. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15245. */
  15246. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15247. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15248. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15249. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15250. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15251. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15252. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15253. if (this._renderingGroups[renderingGroupId]) {
  15254. var group = this._renderingGroups[renderingGroupId];
  15255. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15256. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15257. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15258. }
  15259. };
  15260. /**
  15261. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15262. *
  15263. * @param renderingGroupId The rendering group id corresponding to its index
  15264. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15265. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15266. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15267. */
  15268. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15269. if (depth === void 0) { depth = true; }
  15270. if (stencil === void 0) { stencil = true; }
  15271. this._autoClearDepthStencil[renderingGroupId] = {
  15272. autoClear: autoClearDepthStencil,
  15273. depth: depth,
  15274. stencil: stencil
  15275. };
  15276. };
  15277. return RenderingManager;
  15278. }());
  15279. /**
  15280. * The max id used for rendering groups (not included)
  15281. */
  15282. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15283. /**
  15284. * The min id used for rendering groups (included)
  15285. */
  15286. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15287. /**
  15288. * Used to globally prevent autoclearing scenes.
  15289. */
  15290. RenderingManager.AUTOCLEAR = true;
  15291. BABYLON.RenderingManager = RenderingManager;
  15292. })(BABYLON || (BABYLON = {}));
  15293. //# sourceMappingURL=babylon.renderingManager.js.map
  15294. var BABYLON;
  15295. (function (BABYLON) {
  15296. var RenderingGroup = (function () {
  15297. /**
  15298. * Creates a new rendering group.
  15299. * @param index The rendering group index
  15300. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15301. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15302. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15303. */
  15304. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15305. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15306. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15307. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15308. this.index = index;
  15309. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15310. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15311. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15312. this._particleSystems = new BABYLON.SmartArray(256);
  15313. this._spriteManagers = new BABYLON.SmartArray(256);
  15314. this._edgesRenderers = new BABYLON.SmartArray(16);
  15315. this._scene = scene;
  15316. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15317. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15318. this.transparentSortCompareFn = transparentSortCompareFn;
  15319. }
  15320. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15321. /**
  15322. * Set the opaque sort comparison function.
  15323. * If null the sub meshes will be render in the order they were created
  15324. */
  15325. set: function (value) {
  15326. this._opaqueSortCompareFn = value;
  15327. if (value) {
  15328. this._renderOpaque = this.renderOpaqueSorted;
  15329. }
  15330. else {
  15331. this._renderOpaque = RenderingGroup.renderUnsorted;
  15332. }
  15333. },
  15334. enumerable: true,
  15335. configurable: true
  15336. });
  15337. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15338. /**
  15339. * Set the alpha test sort comparison function.
  15340. * If null the sub meshes will be render in the order they were created
  15341. */
  15342. set: function (value) {
  15343. this._alphaTestSortCompareFn = value;
  15344. if (value) {
  15345. this._renderAlphaTest = this.renderAlphaTestSorted;
  15346. }
  15347. else {
  15348. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15349. }
  15350. },
  15351. enumerable: true,
  15352. configurable: true
  15353. });
  15354. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15355. /**
  15356. * Set the transparent sort comparison function.
  15357. * If null the sub meshes will be render in the order they were created
  15358. */
  15359. set: function (value) {
  15360. if (value) {
  15361. this._transparentSortCompareFn = value;
  15362. }
  15363. else {
  15364. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15365. }
  15366. this._renderTransparent = this.renderTransparentSorted;
  15367. },
  15368. enumerable: true,
  15369. configurable: true
  15370. });
  15371. /**
  15372. * Render all the sub meshes contained in the group.
  15373. * @param customRenderFunction Used to override the default render behaviour of the group.
  15374. * @returns true if rendered some submeshes.
  15375. */
  15376. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15377. if (customRenderFunction) {
  15378. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15379. return;
  15380. }
  15381. var engine = this._scene.getEngine();
  15382. // Opaque
  15383. if (this._opaqueSubMeshes.length !== 0) {
  15384. this._renderOpaque(this._opaqueSubMeshes);
  15385. }
  15386. // Alpha test
  15387. if (this._alphaTestSubMeshes.length !== 0) {
  15388. engine.setAlphaTesting(true);
  15389. this._renderAlphaTest(this._alphaTestSubMeshes);
  15390. engine.setAlphaTesting(false);
  15391. }
  15392. var stencilState = engine.getStencilBuffer();
  15393. engine.setStencilBuffer(false);
  15394. // Sprites
  15395. if (renderSprites) {
  15396. this._renderSprites();
  15397. }
  15398. // Particles
  15399. if (renderParticles) {
  15400. this._renderParticles(activeMeshes);
  15401. }
  15402. if (this.onBeforeTransparentRendering) {
  15403. this.onBeforeTransparentRendering();
  15404. }
  15405. // Transparent
  15406. if (this._transparentSubMeshes.length !== 0) {
  15407. this._renderTransparent(this._transparentSubMeshes);
  15408. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15409. }
  15410. // Set back stencil to false in case it changes before the edge renderer.
  15411. engine.setStencilBuffer(false);
  15412. // Edges
  15413. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15414. this._edgesRenderers.data[edgesRendererIndex].render();
  15415. }
  15416. // Restore Stencil state.
  15417. engine.setStencilBuffer(stencilState);
  15418. };
  15419. /**
  15420. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15421. * @param subMeshes The submeshes to render
  15422. */
  15423. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15424. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15425. };
  15426. /**
  15427. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15428. * @param subMeshes The submeshes to render
  15429. */
  15430. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15431. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15432. };
  15433. /**
  15434. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15435. * @param subMeshes The submeshes to render
  15436. */
  15437. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15438. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15439. };
  15440. /**
  15441. * Renders the submeshes in a specified order.
  15442. * @param subMeshes The submeshes to sort before render
  15443. * @param sortCompareFn The comparison function use to sort
  15444. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15445. * @param transparent Specifies to activate blending if true
  15446. */
  15447. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15448. var subIndex = 0;
  15449. var subMesh;
  15450. for (; subIndex < subMeshes.length; subIndex++) {
  15451. subMesh = subMeshes.data[subIndex];
  15452. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15453. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15454. }
  15455. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15456. sortedArray.sort(sortCompareFn);
  15457. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15458. subMesh = sortedArray[subIndex];
  15459. subMesh.render(transparent);
  15460. }
  15461. };
  15462. /**
  15463. * Renders the submeshes in the order they were dispatched (no sort applied).
  15464. * @param subMeshes The submeshes to render
  15465. */
  15466. RenderingGroup.renderUnsorted = function (subMeshes) {
  15467. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15468. var submesh = subMeshes.data[subIndex];
  15469. submesh.render(false);
  15470. }
  15471. };
  15472. /**
  15473. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15474. * are rendered back to front if in the same alpha index.
  15475. *
  15476. * @param a The first submesh
  15477. * @param b The second submesh
  15478. * @returns The result of the comparison
  15479. */
  15480. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15481. // Alpha index first
  15482. if (a._alphaIndex > b._alphaIndex) {
  15483. return 1;
  15484. }
  15485. if (a._alphaIndex < b._alphaIndex) {
  15486. return -1;
  15487. }
  15488. // Then distance to camera
  15489. return RenderingGroup.backToFrontSortCompare(a, b);
  15490. };
  15491. /**
  15492. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15493. * are rendered back to front.
  15494. *
  15495. * @param a The first submesh
  15496. * @param b The second submesh
  15497. * @returns The result of the comparison
  15498. */
  15499. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15500. // Then distance to camera
  15501. if (a._distanceToCamera < b._distanceToCamera) {
  15502. return 1;
  15503. }
  15504. if (a._distanceToCamera > b._distanceToCamera) {
  15505. return -1;
  15506. }
  15507. return 0;
  15508. };
  15509. /**
  15510. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15511. * are rendered front to back (prevent overdraw).
  15512. *
  15513. * @param a The first submesh
  15514. * @param b The second submesh
  15515. * @returns The result of the comparison
  15516. */
  15517. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15518. // Then distance to camera
  15519. if (a._distanceToCamera < b._distanceToCamera) {
  15520. return -1;
  15521. }
  15522. if (a._distanceToCamera > b._distanceToCamera) {
  15523. return 1;
  15524. }
  15525. return 0;
  15526. };
  15527. /**
  15528. * Resets the different lists of submeshes to prepare a new frame.
  15529. */
  15530. RenderingGroup.prototype.prepare = function () {
  15531. this._opaqueSubMeshes.reset();
  15532. this._transparentSubMeshes.reset();
  15533. this._alphaTestSubMeshes.reset();
  15534. this._particleSystems.reset();
  15535. this._spriteManagers.reset();
  15536. this._edgesRenderers.reset();
  15537. };
  15538. RenderingGroup.prototype.dispose = function () {
  15539. this._opaqueSubMeshes.dispose();
  15540. this._transparentSubMeshes.dispose();
  15541. this._alphaTestSubMeshes.dispose();
  15542. this._particleSystems.dispose();
  15543. this._spriteManagers.dispose();
  15544. this._edgesRenderers.dispose();
  15545. };
  15546. /**
  15547. * Inserts the submesh in its correct queue depending on its material.
  15548. * @param subMesh The submesh to dispatch
  15549. */
  15550. RenderingGroup.prototype.dispatch = function (subMesh) {
  15551. var material = subMesh.getMaterial();
  15552. var mesh = subMesh.getMesh();
  15553. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15554. this._transparentSubMeshes.push(subMesh);
  15555. }
  15556. else if (material.needAlphaTesting()) {
  15557. this._alphaTestSubMeshes.push(subMesh);
  15558. }
  15559. else {
  15560. this._opaqueSubMeshes.push(subMesh); // Opaque
  15561. }
  15562. if (mesh._edgesRenderer) {
  15563. this._edgesRenderers.push(mesh._edgesRenderer);
  15564. }
  15565. };
  15566. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15567. this._spriteManagers.push(spriteManager);
  15568. };
  15569. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15570. this._particleSystems.push(particleSystem);
  15571. };
  15572. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15573. if (this._particleSystems.length === 0) {
  15574. return;
  15575. }
  15576. // Particles
  15577. var activeCamera = this._scene.activeCamera;
  15578. this._scene._particlesDuration.beginMonitoring();
  15579. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15580. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15581. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15582. continue;
  15583. }
  15584. var emitter = particleSystem.emitter;
  15585. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  15586. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15587. }
  15588. }
  15589. this._scene._particlesDuration.endMonitoring(false);
  15590. };
  15591. RenderingGroup.prototype._renderSprites = function () {
  15592. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15593. return;
  15594. }
  15595. // Sprites
  15596. var activeCamera = this._scene.activeCamera;
  15597. this._scene._spritesDuration.beginMonitoring();
  15598. for (var id = 0; id < this._spriteManagers.length; id++) {
  15599. var spriteManager = this._spriteManagers.data[id];
  15600. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15601. spriteManager.render();
  15602. }
  15603. }
  15604. this._scene._spritesDuration.endMonitoring(false);
  15605. };
  15606. return RenderingGroup;
  15607. }());
  15608. BABYLON.RenderingGroup = RenderingGroup;
  15609. })(BABYLON || (BABYLON = {}));
  15610. //# sourceMappingURL=babylon.renderingGroup.js.map
  15611. var BABYLON;
  15612. (function (BABYLON) {
  15613. var ClickInfo = (function () {
  15614. function ClickInfo() {
  15615. this._singleClick = false;
  15616. this._doubleClick = false;
  15617. this._hasSwiped = false;
  15618. this._ignore = false;
  15619. }
  15620. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15621. get: function () {
  15622. return this._singleClick;
  15623. },
  15624. set: function (b) {
  15625. this._singleClick = b;
  15626. },
  15627. enumerable: true,
  15628. configurable: true
  15629. });
  15630. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15631. get: function () {
  15632. return this._doubleClick;
  15633. },
  15634. set: function (b) {
  15635. this._doubleClick = b;
  15636. },
  15637. enumerable: true,
  15638. configurable: true
  15639. });
  15640. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15641. get: function () {
  15642. return this._hasSwiped;
  15643. },
  15644. set: function (b) {
  15645. this._hasSwiped = b;
  15646. },
  15647. enumerable: true,
  15648. configurable: true
  15649. });
  15650. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15651. get: function () {
  15652. return this._ignore;
  15653. },
  15654. set: function (b) {
  15655. this._ignore = b;
  15656. },
  15657. enumerable: true,
  15658. configurable: true
  15659. });
  15660. return ClickInfo;
  15661. }());
  15662. var PointerEventTypes = (function () {
  15663. function PointerEventTypes() {
  15664. }
  15665. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15666. get: function () {
  15667. return PointerEventTypes._POINTERDOWN;
  15668. },
  15669. enumerable: true,
  15670. configurable: true
  15671. });
  15672. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15673. get: function () {
  15674. return PointerEventTypes._POINTERUP;
  15675. },
  15676. enumerable: true,
  15677. configurable: true
  15678. });
  15679. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15680. get: function () {
  15681. return PointerEventTypes._POINTERMOVE;
  15682. },
  15683. enumerable: true,
  15684. configurable: true
  15685. });
  15686. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15687. get: function () {
  15688. return PointerEventTypes._POINTERWHEEL;
  15689. },
  15690. enumerable: true,
  15691. configurable: true
  15692. });
  15693. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15694. get: function () {
  15695. return PointerEventTypes._POINTERPICK;
  15696. },
  15697. enumerable: true,
  15698. configurable: true
  15699. });
  15700. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15701. get: function () {
  15702. return PointerEventTypes._POINTERTAP;
  15703. },
  15704. enumerable: true,
  15705. configurable: true
  15706. });
  15707. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15708. get: function () {
  15709. return PointerEventTypes._POINTERDOUBLETAP;
  15710. },
  15711. enumerable: true,
  15712. configurable: true
  15713. });
  15714. return PointerEventTypes;
  15715. }());
  15716. PointerEventTypes._POINTERDOWN = 0x01;
  15717. PointerEventTypes._POINTERUP = 0x02;
  15718. PointerEventTypes._POINTERMOVE = 0x04;
  15719. PointerEventTypes._POINTERWHEEL = 0x08;
  15720. PointerEventTypes._POINTERPICK = 0x10;
  15721. PointerEventTypes._POINTERTAP = 0x20;
  15722. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15723. BABYLON.PointerEventTypes = PointerEventTypes;
  15724. var PointerInfoBase = (function () {
  15725. function PointerInfoBase(type, event) {
  15726. this.type = type;
  15727. this.event = event;
  15728. }
  15729. return PointerInfoBase;
  15730. }());
  15731. BABYLON.PointerInfoBase = PointerInfoBase;
  15732. /**
  15733. * This class is used to store pointer related info for the onPrePointerObservable event.
  15734. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15735. */
  15736. var PointerInfoPre = (function (_super) {
  15737. __extends(PointerInfoPre, _super);
  15738. function PointerInfoPre(type, event, localX, localY) {
  15739. var _this = _super.call(this, type, event) || this;
  15740. _this.skipOnPointerObservable = false;
  15741. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15742. return _this;
  15743. }
  15744. return PointerInfoPre;
  15745. }(PointerInfoBase));
  15746. BABYLON.PointerInfoPre = PointerInfoPre;
  15747. /**
  15748. * This type contains all the data related to a pointer event in Babylon.js.
  15749. * 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.
  15750. */
  15751. var PointerInfo = (function (_super) {
  15752. __extends(PointerInfo, _super);
  15753. function PointerInfo(type, event, pickInfo) {
  15754. var _this = _super.call(this, type, event) || this;
  15755. _this.pickInfo = pickInfo;
  15756. return _this;
  15757. }
  15758. return PointerInfo;
  15759. }(PointerInfoBase));
  15760. BABYLON.PointerInfo = PointerInfo;
  15761. /**
  15762. * This class is used by the onRenderingGroupObservable
  15763. */
  15764. var RenderingGroupInfo = (function () {
  15765. function RenderingGroupInfo() {
  15766. }
  15767. return RenderingGroupInfo;
  15768. }());
  15769. /**
  15770. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15771. * This stage will be fired no matter what
  15772. */
  15773. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15774. /**
  15775. * Called before opaque object are rendered.
  15776. * This stage will be fired only if there's 3D Opaque content to render
  15777. */
  15778. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15779. /**
  15780. * Called after the opaque objects are rendered and before the transparent ones
  15781. * This stage will be fired only if there's 3D transparent content to render
  15782. */
  15783. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15784. /**
  15785. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15786. * This stage will be fired no matter what
  15787. */
  15788. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15789. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15790. /**
  15791. * Represents a scene to be rendered by the engine.
  15792. * @see http://doc.babylonjs.com/page.php?p=21911
  15793. */
  15794. var Scene = (function () {
  15795. /**
  15796. * @constructor
  15797. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15798. */
  15799. function Scene(engine) {
  15800. // Members
  15801. this.autoClear = true;
  15802. this.autoClearDepthAndStencil = true;
  15803. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15804. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15805. this.forceWireframe = false;
  15806. this._forcePointsCloud = false;
  15807. this.forceShowBoundingBoxes = false;
  15808. this.animationsEnabled = true;
  15809. this.constantlyUpdateMeshUnderPointer = false;
  15810. this.hoverCursor = "pointer";
  15811. // Metadata
  15812. this.metadata = null;
  15813. // Events
  15814. /**
  15815. * An event triggered when the scene is disposed.
  15816. * @type {BABYLON.Observable}
  15817. */
  15818. this.onDisposeObservable = new BABYLON.Observable();
  15819. /**
  15820. * An event triggered before rendering the scene
  15821. * @type {BABYLON.Observable}
  15822. */
  15823. this.onBeforeRenderObservable = new BABYLON.Observable();
  15824. /**
  15825. * An event triggered after rendering the scene
  15826. * @type {BABYLON.Observable}
  15827. */
  15828. this.onAfterRenderObservable = new BABYLON.Observable();
  15829. /**
  15830. * An event triggered when the scene is ready
  15831. * @type {BABYLON.Observable}
  15832. */
  15833. this.onReadyObservable = new BABYLON.Observable();
  15834. /**
  15835. * An event triggered before rendering a camera
  15836. * @type {BABYLON.Observable}
  15837. */
  15838. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15839. /**
  15840. * An event triggered after rendering a camera
  15841. * @type {BABYLON.Observable}
  15842. */
  15843. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15844. /**
  15845. * An event triggered when a camera is created
  15846. * @type {BABYLON.Observable}
  15847. */
  15848. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15849. /**
  15850. * An event triggered when a camera is removed
  15851. * @type {BABYLON.Observable}
  15852. */
  15853. this.onCameraRemovedObservable = new BABYLON.Observable();
  15854. /**
  15855. * An event triggered when a light is created
  15856. * @type {BABYLON.Observable}
  15857. */
  15858. this.onNewLightAddedObservable = new BABYLON.Observable();
  15859. /**
  15860. * An event triggered when a light is removed
  15861. * @type {BABYLON.Observable}
  15862. */
  15863. this.onLightRemovedObservable = new BABYLON.Observable();
  15864. /**
  15865. * An event triggered when a geometry is created
  15866. * @type {BABYLON.Observable}
  15867. */
  15868. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15869. /**
  15870. * An event triggered when a geometry is removed
  15871. * @type {BABYLON.Observable}
  15872. */
  15873. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15874. /**
  15875. * An event triggered when a mesh is created
  15876. * @type {BABYLON.Observable}
  15877. */
  15878. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15879. /**
  15880. * An event triggered when a mesh is removed
  15881. * @type {BABYLON.Observable}
  15882. */
  15883. this.onMeshRemovedObservable = new BABYLON.Observable();
  15884. /**
  15885. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15886. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15887. * 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)
  15888. */
  15889. this.onRenderingGroupObservable = new BABYLON.Observable();
  15890. // Animations
  15891. this.animations = [];
  15892. /**
  15893. * 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).
  15894. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15895. */
  15896. this.onPrePointerObservable = new BABYLON.Observable();
  15897. /**
  15898. * Observable event triggered each time an input event is received from the rendering canvas
  15899. */
  15900. this.onPointerObservable = new BABYLON.Observable();
  15901. this._meshPickProceed = false;
  15902. this._previousHasSwiped = false;
  15903. this._currentPickResult = null;
  15904. this._previousPickResult = null;
  15905. this._isButtonPressed = false;
  15906. this._doubleClickOccured = false;
  15907. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  15908. this.cameraToUseForPointers = null;
  15909. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15910. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15911. this._startingPointerTime = 0;
  15912. this._previousStartingPointerTime = 0;
  15913. // Coordinate system
  15914. /**
  15915. * use right-handed coordinate system on this scene.
  15916. * @type {boolean}
  15917. */
  15918. this._useRightHandedSystem = false;
  15919. // Fog
  15920. this._fogEnabled = true;
  15921. this._fogMode = Scene.FOGMODE_NONE;
  15922. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15923. this.fogDensity = 0.1;
  15924. this.fogStart = 0;
  15925. this.fogEnd = 1000.0;
  15926. // Lights
  15927. /**
  15928. * is shadow enabled on this scene.
  15929. * @type {boolean}
  15930. */
  15931. this._shadowsEnabled = true;
  15932. /**
  15933. * is light enabled on this scene.
  15934. * @type {boolean}
  15935. */
  15936. this._lightsEnabled = true;
  15937. /**
  15938. * All of the lights added to this scene.
  15939. * @see BABYLON.Light
  15940. * @type {BABYLON.Light[]}
  15941. */
  15942. this.lights = new Array();
  15943. // Cameras
  15944. /** All of the cameras added to this scene. */
  15945. this.cameras = new Array();
  15946. /** All of the active cameras added to this scene. */
  15947. this.activeCameras = new Array();
  15948. // Meshes
  15949. /**
  15950. * All of the (abstract) meshes added to this scene.
  15951. * @see BABYLON.AbstractMesh
  15952. * @type {BABYLON.AbstractMesh[]}
  15953. */
  15954. this.meshes = new Array();
  15955. // Geometries
  15956. this._geometries = new Array();
  15957. this.materials = new Array();
  15958. this.multiMaterials = new Array();
  15959. // Textures
  15960. this._texturesEnabled = true;
  15961. this.textures = new Array();
  15962. // Particles
  15963. this.particlesEnabled = true;
  15964. this.particleSystems = new Array();
  15965. // Sprites
  15966. this.spritesEnabled = true;
  15967. this.spriteManagers = new Array();
  15968. // Layers
  15969. this.layers = new Array();
  15970. this.highlightLayers = new Array();
  15971. // Skeletons
  15972. this._skeletonsEnabled = true;
  15973. this.skeletons = new Array();
  15974. // Morph targets
  15975. this.morphTargetManagers = new Array();
  15976. // Lens flares
  15977. this.lensFlaresEnabled = true;
  15978. this.lensFlareSystems = new Array();
  15979. // Collisions
  15980. this.collisionsEnabled = true;
  15981. /** Defines the gravity applied to this scene */
  15982. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15983. // Postprocesses
  15984. this.postProcessesEnabled = true;
  15985. // Customs render targets
  15986. this.renderTargetsEnabled = true;
  15987. this.dumpNextRenderTargets = false;
  15988. this.customRenderTargets = new Array();
  15989. // Imported meshes
  15990. this.importedMeshesFiles = new Array();
  15991. // Probes
  15992. this.probesEnabled = true;
  15993. this.reflectionProbes = new Array();
  15994. this._actionManagers = new Array();
  15995. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15996. // Procedural textures
  15997. this.proceduralTexturesEnabled = true;
  15998. this._proceduralTextures = new Array();
  15999. this.soundTracks = new Array();
  16000. this._audioEnabled = true;
  16001. this._headphone = false;
  16002. // Performance counters
  16003. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16004. this._totalLightsCounter = new BABYLON.PerfCounter();
  16005. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16006. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16007. this._totalVertices = new BABYLON.PerfCounter();
  16008. this._activeIndices = new BABYLON.PerfCounter();
  16009. this._activeParticles = new BABYLON.PerfCounter();
  16010. this._lastFrameDuration = new BABYLON.PerfCounter();
  16011. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16012. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16013. this._particlesDuration = new BABYLON.PerfCounter();
  16014. this._renderDuration = new BABYLON.PerfCounter();
  16015. this._spritesDuration = new BABYLON.PerfCounter();
  16016. this._activeBones = new BABYLON.PerfCounter();
  16017. this._animationTime = 0;
  16018. this.animationTimeScale = 1;
  16019. this._renderId = 0;
  16020. this._executeWhenReadyTimeoutId = -1;
  16021. this._intermediateRendering = false;
  16022. this._viewUpdateFlag = -1;
  16023. this._projectionUpdateFlag = -1;
  16024. this._toBeDisposed = new BABYLON.SmartArray(256);
  16025. this._pendingData = []; //ANY
  16026. this._activeMeshes = new BABYLON.SmartArray(256);
  16027. this._processedMaterials = new BABYLON.SmartArray(256);
  16028. this._renderTargets = new BABYLON.SmartArray(256);
  16029. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16030. this._activeSkeletons = new BABYLON.SmartArray(32);
  16031. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16032. this._activeAnimatables = new Array();
  16033. this._transformMatrix = BABYLON.Matrix.Zero();
  16034. this.requireLightSorting = false;
  16035. this._uniqueIdCounter = 0;
  16036. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16037. this._engine.scenes.push(this);
  16038. this._uid = null;
  16039. this._renderingManager = new BABYLON.RenderingManager(this);
  16040. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16041. if (BABYLON.OutlineRenderer) {
  16042. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16043. }
  16044. this.attachControl();
  16045. if (BABYLON.SoundTrack) {
  16046. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16047. }
  16048. //simplification queue
  16049. if (BABYLON.SimplificationQueue) {
  16050. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16051. }
  16052. //collision coordinator initialization. For now legacy per default.
  16053. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16054. // Uniform Buffer
  16055. this._createUbo();
  16056. // Default Image processing definition.
  16057. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16058. }
  16059. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16060. /** The fog is deactivated */
  16061. get: function () {
  16062. return Scene._FOGMODE_NONE;
  16063. },
  16064. enumerable: true,
  16065. configurable: true
  16066. });
  16067. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16068. /** The fog density is following an exponential function */
  16069. get: function () {
  16070. return Scene._FOGMODE_EXP;
  16071. },
  16072. enumerable: true,
  16073. configurable: true
  16074. });
  16075. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16076. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16077. get: function () {
  16078. return Scene._FOGMODE_EXP2;
  16079. },
  16080. enumerable: true,
  16081. configurable: true
  16082. });
  16083. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16084. /** The fog density is following a linear function. */
  16085. get: function () {
  16086. return Scene._FOGMODE_LINEAR;
  16087. },
  16088. enumerable: true,
  16089. configurable: true
  16090. });
  16091. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16092. /**
  16093. * Texture used in all pbr material as the reflection texture.
  16094. * As in the majority of the scene they are the same (exception for multi room and so on),
  16095. * this is easier to reference from here than from all the materials.
  16096. */
  16097. get: function () {
  16098. return this._environmentTexture;
  16099. },
  16100. /**
  16101. * Texture used in all pbr material as the reflection texture.
  16102. * As in the majority of the scene they are the same (exception for multi room and so on),
  16103. * this is easier to set here than in all the materials.
  16104. */
  16105. set: function (value) {
  16106. this._environmentTexture = value;
  16107. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16113. /**
  16114. * Default image processing configuration used either in the rendering
  16115. * Forward main pass or through the imageProcessingPostProcess if present.
  16116. * As in the majority of the scene they are the same (exception for multi camera),
  16117. * this is easier to reference from here than from all the materials and post process.
  16118. *
  16119. * No setter as we it is a shared configuration, you can set the values instead.
  16120. */
  16121. get: function () {
  16122. return this._imageProcessingConfiguration;
  16123. },
  16124. enumerable: true,
  16125. configurable: true
  16126. });
  16127. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16128. get: function () {
  16129. return this._forcePointsCloud;
  16130. },
  16131. set: function (value) {
  16132. if (this._forcePointsCloud === value) {
  16133. return;
  16134. }
  16135. this._forcePointsCloud = value;
  16136. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16137. },
  16138. enumerable: true,
  16139. configurable: true
  16140. });
  16141. Object.defineProperty(Scene.prototype, "onDispose", {
  16142. /** A function to be executed when this scene is disposed. */
  16143. set: function (callback) {
  16144. if (this._onDisposeObserver) {
  16145. this.onDisposeObservable.remove(this._onDisposeObserver);
  16146. }
  16147. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16148. },
  16149. enumerable: true,
  16150. configurable: true
  16151. });
  16152. Object.defineProperty(Scene.prototype, "beforeRender", {
  16153. /** A function to be executed before rendering this scene */
  16154. set: function (callback) {
  16155. if (this._onBeforeRenderObserver) {
  16156. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16157. }
  16158. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16159. },
  16160. enumerable: true,
  16161. configurable: true
  16162. });
  16163. Object.defineProperty(Scene.prototype, "afterRender", {
  16164. /** A function to be executed after rendering this scene */
  16165. set: function (callback) {
  16166. if (this._onAfterRenderObserver) {
  16167. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16168. }
  16169. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16170. },
  16171. enumerable: true,
  16172. configurable: true
  16173. });
  16174. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16175. set: function (callback) {
  16176. if (this._onBeforeCameraRenderObserver) {
  16177. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16178. }
  16179. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16180. },
  16181. enumerable: true,
  16182. configurable: true
  16183. });
  16184. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16185. set: function (callback) {
  16186. if (this._onAfterCameraRenderObserver) {
  16187. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16188. }
  16189. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16190. },
  16191. enumerable: true,
  16192. configurable: true
  16193. });
  16194. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16195. get: function () {
  16196. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16197. },
  16198. enumerable: true,
  16199. configurable: true
  16200. });
  16201. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16202. get: function () {
  16203. return this._useRightHandedSystem;
  16204. },
  16205. set: function (value) {
  16206. if (this._useRightHandedSystem === value) {
  16207. return;
  16208. }
  16209. this._useRightHandedSystem = value;
  16210. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16211. },
  16212. enumerable: true,
  16213. configurable: true
  16214. });
  16215. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16216. get: function () {
  16217. return this._fogEnabled;
  16218. },
  16219. /**
  16220. * is fog enabled on this scene.
  16221. */
  16222. set: function (value) {
  16223. if (this._fogEnabled === value) {
  16224. return;
  16225. }
  16226. this._fogEnabled = value;
  16227. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16228. },
  16229. enumerable: true,
  16230. configurable: true
  16231. });
  16232. Object.defineProperty(Scene.prototype, "fogMode", {
  16233. get: function () {
  16234. return this._fogMode;
  16235. },
  16236. set: function (value) {
  16237. if (this._fogMode === value) {
  16238. return;
  16239. }
  16240. this._fogMode = value;
  16241. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16242. },
  16243. enumerable: true,
  16244. configurable: true
  16245. });
  16246. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16247. get: function () {
  16248. return this._shadowsEnabled;
  16249. },
  16250. set: function (value) {
  16251. if (this._shadowsEnabled === value) {
  16252. return;
  16253. }
  16254. this._shadowsEnabled = value;
  16255. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16256. },
  16257. enumerable: true,
  16258. configurable: true
  16259. });
  16260. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16261. get: function () {
  16262. return this._lightsEnabled;
  16263. },
  16264. set: function (value) {
  16265. if (this._lightsEnabled === value) {
  16266. return;
  16267. }
  16268. this._lightsEnabled = value;
  16269. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16270. },
  16271. enumerable: true,
  16272. configurable: true
  16273. });
  16274. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16275. /** The default material used on meshes when no material is affected */
  16276. get: function () {
  16277. if (!this._defaultMaterial) {
  16278. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16279. }
  16280. return this._defaultMaterial;
  16281. },
  16282. /** The default material used on meshes when no material is affected */
  16283. set: function (value) {
  16284. this._defaultMaterial = value;
  16285. },
  16286. enumerable: true,
  16287. configurable: true
  16288. });
  16289. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16290. get: function () {
  16291. return this._texturesEnabled;
  16292. },
  16293. set: function (value) {
  16294. if (this._texturesEnabled === value) {
  16295. return;
  16296. }
  16297. this._texturesEnabled = value;
  16298. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16299. },
  16300. enumerable: true,
  16301. configurable: true
  16302. });
  16303. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16304. get: function () {
  16305. return this._skeletonsEnabled;
  16306. },
  16307. set: function (value) {
  16308. if (this._skeletonsEnabled === value) {
  16309. return;
  16310. }
  16311. this._skeletonsEnabled = value;
  16312. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16313. },
  16314. enumerable: true,
  16315. configurable: true
  16316. });
  16317. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16318. get: function () {
  16319. if (!this._postProcessRenderPipelineManager) {
  16320. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16321. }
  16322. return this._postProcessRenderPipelineManager;
  16323. },
  16324. enumerable: true,
  16325. configurable: true
  16326. });
  16327. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16328. get: function () {
  16329. return this._frustumPlanes;
  16330. },
  16331. enumerable: true,
  16332. configurable: true
  16333. });
  16334. Object.defineProperty(Scene.prototype, "debugLayer", {
  16335. // Properties
  16336. get: function () {
  16337. if (!this._debugLayer) {
  16338. this._debugLayer = new BABYLON.DebugLayer(this);
  16339. }
  16340. return this._debugLayer;
  16341. },
  16342. enumerable: true,
  16343. configurable: true
  16344. });
  16345. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16346. get: function () {
  16347. return this._workerCollisions;
  16348. },
  16349. set: function (enabled) {
  16350. if (!BABYLON.CollisionCoordinatorLegacy) {
  16351. return;
  16352. }
  16353. enabled = (enabled && !!Worker);
  16354. this._workerCollisions = enabled;
  16355. if (this.collisionCoordinator) {
  16356. this.collisionCoordinator.destroy();
  16357. }
  16358. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16359. this.collisionCoordinator.init(this);
  16360. },
  16361. enumerable: true,
  16362. configurable: true
  16363. });
  16364. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16365. get: function () {
  16366. return this._selectionOctree;
  16367. },
  16368. enumerable: true,
  16369. configurable: true
  16370. });
  16371. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16372. /**
  16373. * The mesh that is currently under the pointer.
  16374. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16375. */
  16376. get: function () {
  16377. return this._pointerOverMesh;
  16378. },
  16379. enumerable: true,
  16380. configurable: true
  16381. });
  16382. Object.defineProperty(Scene.prototype, "pointerX", {
  16383. /**
  16384. * Current on-screen X position of the pointer
  16385. * @return {number} X position of the pointer
  16386. */
  16387. get: function () {
  16388. return this._pointerX;
  16389. },
  16390. enumerable: true,
  16391. configurable: true
  16392. });
  16393. Object.defineProperty(Scene.prototype, "pointerY", {
  16394. /**
  16395. * Current on-screen Y position of the pointer
  16396. * @return {number} Y position of the pointer
  16397. */
  16398. get: function () {
  16399. return this._pointerY;
  16400. },
  16401. enumerable: true,
  16402. configurable: true
  16403. });
  16404. Scene.prototype.getCachedMaterial = function () {
  16405. return this._cachedMaterial;
  16406. };
  16407. Scene.prototype.getCachedEffect = function () {
  16408. return this._cachedEffect;
  16409. };
  16410. Scene.prototype.getCachedVisibility = function () {
  16411. return this._cachedVisibility;
  16412. };
  16413. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16414. if (visibility === void 0) { visibility = 0; }
  16415. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16416. };
  16417. Scene.prototype.getBoundingBoxRenderer = function () {
  16418. if (!this._boundingBoxRenderer) {
  16419. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16420. }
  16421. return this._boundingBoxRenderer;
  16422. };
  16423. Scene.prototype.getOutlineRenderer = function () {
  16424. return this._outlineRenderer;
  16425. };
  16426. Scene.prototype.getEngine = function () {
  16427. return this._engine;
  16428. };
  16429. Scene.prototype.getTotalVertices = function () {
  16430. return this._totalVertices.current;
  16431. };
  16432. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16433. get: function () {
  16434. return this._totalVertices;
  16435. },
  16436. enumerable: true,
  16437. configurable: true
  16438. });
  16439. Scene.prototype.getActiveIndices = function () {
  16440. return this._activeIndices.current;
  16441. };
  16442. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16443. get: function () {
  16444. return this._activeIndices;
  16445. },
  16446. enumerable: true,
  16447. configurable: true
  16448. });
  16449. Scene.prototype.getActiveParticles = function () {
  16450. return this._activeParticles.current;
  16451. };
  16452. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16453. get: function () {
  16454. return this._activeParticles;
  16455. },
  16456. enumerable: true,
  16457. configurable: true
  16458. });
  16459. Scene.prototype.getActiveBones = function () {
  16460. return this._activeBones.current;
  16461. };
  16462. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16463. get: function () {
  16464. return this._activeBones;
  16465. },
  16466. enumerable: true,
  16467. configurable: true
  16468. });
  16469. // Stats
  16470. Scene.prototype.getLastFrameDuration = function () {
  16471. return this._lastFrameDuration.current;
  16472. };
  16473. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16474. get: function () {
  16475. return this._lastFrameDuration;
  16476. },
  16477. enumerable: true,
  16478. configurable: true
  16479. });
  16480. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16481. return this._evaluateActiveMeshesDuration.current;
  16482. };
  16483. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16484. get: function () {
  16485. return this._evaluateActiveMeshesDuration;
  16486. },
  16487. enumerable: true,
  16488. configurable: true
  16489. });
  16490. Scene.prototype.getActiveMeshes = function () {
  16491. return this._activeMeshes;
  16492. };
  16493. Scene.prototype.getRenderTargetsDuration = function () {
  16494. return this._renderTargetsDuration.current;
  16495. };
  16496. Scene.prototype.getRenderDuration = function () {
  16497. return this._renderDuration.current;
  16498. };
  16499. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16500. get: function () {
  16501. return this._renderDuration;
  16502. },
  16503. enumerable: true,
  16504. configurable: true
  16505. });
  16506. Scene.prototype.getParticlesDuration = function () {
  16507. return this._particlesDuration.current;
  16508. };
  16509. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16510. get: function () {
  16511. return this._particlesDuration;
  16512. },
  16513. enumerable: true,
  16514. configurable: true
  16515. });
  16516. Scene.prototype.getSpritesDuration = function () {
  16517. return this._spritesDuration.current;
  16518. };
  16519. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16520. get: function () {
  16521. return this._spritesDuration;
  16522. },
  16523. enumerable: true,
  16524. configurable: true
  16525. });
  16526. Scene.prototype.getAnimationRatio = function () {
  16527. return this._animationRatio;
  16528. };
  16529. Scene.prototype.getRenderId = function () {
  16530. return this._renderId;
  16531. };
  16532. Scene.prototype.incrementRenderId = function () {
  16533. this._renderId++;
  16534. };
  16535. Scene.prototype._updatePointerPosition = function (evt) {
  16536. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16537. this._pointerX = evt.clientX - canvasRect.left;
  16538. this._pointerY = evt.clientY - canvasRect.top;
  16539. this._unTranslatedPointerX = this._pointerX;
  16540. this._unTranslatedPointerY = this._pointerY;
  16541. if (this.cameraToUseForPointers) {
  16542. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16543. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16544. }
  16545. };
  16546. Scene.prototype._createUbo = function () {
  16547. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16548. this._sceneUbo.addUniform("viewProjection", 16);
  16549. this._sceneUbo.addUniform("view", 16);
  16550. };
  16551. // Pointers handling
  16552. /**
  16553. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16554. * @param attachUp defines if you want to attach events to pointerup
  16555. * @param attachDown defines if you want to attach events to pointerdown
  16556. * @param attachMove defines if you want to attach events to pointermove
  16557. */
  16558. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16559. var _this = this;
  16560. if (attachUp === void 0) { attachUp = true; }
  16561. if (attachDown === void 0) { attachDown = true; }
  16562. if (attachMove === void 0) { attachMove = true; }
  16563. this._initActionManager = function (act, clickInfo) {
  16564. if (!_this._meshPickProceed) {
  16565. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16566. _this._currentPickResult = pickResult;
  16567. if (pickResult) {
  16568. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16569. }
  16570. _this._meshPickProceed = true;
  16571. }
  16572. return act;
  16573. };
  16574. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16575. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16576. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16577. btn !== _this._previousButtonPressed) {
  16578. _this._doubleClickOccured = false;
  16579. clickInfo.singleClick = true;
  16580. clickInfo.ignore = false;
  16581. cb(clickInfo, _this._currentPickResult);
  16582. }
  16583. };
  16584. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16585. var clickInfo = new ClickInfo();
  16586. _this._currentPickResult = null;
  16587. var act;
  16588. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16589. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16590. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16591. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16592. act = _this._initActionManager(act, clickInfo);
  16593. if (act)
  16594. checkPicking = act.hasPickTriggers;
  16595. }
  16596. if (checkPicking) {
  16597. var btn = evt.button;
  16598. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16599. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16600. if (!clickInfo.hasSwiped) {
  16601. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16602. if (!checkSingleClickImmediately) {
  16603. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16604. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16605. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16606. act = _this._initActionManager(act, clickInfo);
  16607. if (act)
  16608. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16609. }
  16610. }
  16611. if (checkSingleClickImmediately) {
  16612. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16613. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16614. btn !== _this._previousButtonPressed) {
  16615. clickInfo.singleClick = true;
  16616. cb(clickInfo, _this._currentPickResult);
  16617. }
  16618. }
  16619. else {
  16620. // wait that no double click has been raised during the double click delay
  16621. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16622. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16623. }
  16624. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16625. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16626. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16627. act = _this._initActionManager(act, clickInfo);
  16628. if (act)
  16629. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16630. }
  16631. if (checkDoubleClick) {
  16632. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16633. if (btn === _this._previousButtonPressed &&
  16634. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16635. !_this._doubleClickOccured) {
  16636. // pointer has not moved for 2 clicks, it's a double click
  16637. if (!clickInfo.hasSwiped &&
  16638. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16639. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16640. _this._previousStartingPointerTime = 0;
  16641. _this._doubleClickOccured = true;
  16642. clickInfo.doubleClick = true;
  16643. clickInfo.ignore = false;
  16644. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16645. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16646. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16647. cb(clickInfo, _this._currentPickResult);
  16648. }
  16649. else {
  16650. _this._doubleClickOccured = false;
  16651. _this._previousStartingPointerTime = _this._startingPointerTime;
  16652. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16653. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16654. _this._previousButtonPressed = btn;
  16655. _this._previousHasSwiped = clickInfo.hasSwiped;
  16656. if (Scene.ExclusiveDoubleClickMode) {
  16657. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16658. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16659. }
  16660. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16661. cb(clickInfo, _this._previousPickResult);
  16662. }
  16663. else {
  16664. cb(clickInfo, _this._currentPickResult);
  16665. }
  16666. }
  16667. }
  16668. else {
  16669. _this._doubleClickOccured = false;
  16670. _this._previousStartingPointerTime = _this._startingPointerTime;
  16671. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16672. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16673. _this._previousButtonPressed = btn;
  16674. _this._previousHasSwiped = clickInfo.hasSwiped;
  16675. }
  16676. }
  16677. }
  16678. }
  16679. clickInfo.ignore = true;
  16680. cb(clickInfo, _this._currentPickResult);
  16681. };
  16682. var spritePredicate = function (sprite) {
  16683. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16684. };
  16685. this._onPointerMove = function (evt) {
  16686. _this._updatePointerPosition(evt);
  16687. // PreObservable support
  16688. if (_this.onPrePointerObservable.hasObservers()) {
  16689. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16690. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16691. _this.onPrePointerObservable.notifyObservers(pi, type);
  16692. if (pi.skipOnPointerObservable) {
  16693. return;
  16694. }
  16695. }
  16696. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16697. return;
  16698. }
  16699. var canvas = _this._engine.getRenderingCanvas();
  16700. if (!_this.pointerMovePredicate) {
  16701. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16702. }
  16703. // Meshes
  16704. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16705. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16706. _this.setPointerOverSprite(null);
  16707. _this.setPointerOverMesh(pickResult.pickedMesh);
  16708. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16709. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16710. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16711. }
  16712. else {
  16713. canvas.style.cursor = _this.hoverCursor;
  16714. }
  16715. }
  16716. else {
  16717. canvas.style.cursor = "";
  16718. }
  16719. }
  16720. else {
  16721. _this.setPointerOverMesh(null);
  16722. // Sprites
  16723. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16724. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16725. _this.setPointerOverSprite(pickResult.pickedSprite);
  16726. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16727. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16728. }
  16729. else {
  16730. canvas.style.cursor = _this.hoverCursor;
  16731. }
  16732. }
  16733. else {
  16734. _this.setPointerOverSprite(null);
  16735. // Restore pointer
  16736. canvas.style.cursor = "";
  16737. }
  16738. }
  16739. if (_this.onPointerMove) {
  16740. _this.onPointerMove(evt, pickResult);
  16741. }
  16742. if (_this.onPointerObservable.hasObservers()) {
  16743. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16744. var pi = new PointerInfo(type, evt, pickResult);
  16745. _this.onPointerObservable.notifyObservers(pi, type);
  16746. }
  16747. };
  16748. this._onPointerDown = function (evt) {
  16749. _this._isButtonPressed = true;
  16750. _this._pickedDownMesh = null;
  16751. _this._meshPickProceed = false;
  16752. _this._updatePointerPosition(evt);
  16753. // PreObservable support
  16754. if (_this.onPrePointerObservable.hasObservers()) {
  16755. var type = PointerEventTypes.POINTERDOWN;
  16756. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16757. _this.onPrePointerObservable.notifyObservers(pi, type);
  16758. if (pi.skipOnPointerObservable) {
  16759. return;
  16760. }
  16761. }
  16762. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16763. return;
  16764. }
  16765. _this._startingPointerPosition.x = _this._pointerX;
  16766. _this._startingPointerPosition.y = _this._pointerY;
  16767. _this._startingPointerTime = new Date().getTime();
  16768. if (!_this.pointerDownPredicate) {
  16769. _this.pointerDownPredicate = function (mesh) {
  16770. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16771. };
  16772. }
  16773. // Meshes
  16774. _this._pickedDownMesh = null;
  16775. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16776. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16777. _this._pickedDownMesh = pickResult.pickedMesh;
  16778. var actionManager = pickResult.pickedMesh.actionManager;
  16779. if (actionManager) {
  16780. if (actionManager.hasPickTriggers) {
  16781. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16782. switch (evt.button) {
  16783. case 0:
  16784. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16785. break;
  16786. case 1:
  16787. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16788. break;
  16789. case 2:
  16790. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16791. break;
  16792. }
  16793. }
  16794. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16795. window.setTimeout((function () {
  16796. var _this = this;
  16797. 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);
  16798. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16799. if (this._isButtonPressed &&
  16800. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16801. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16802. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16803. this._startingPointerTime = 0;
  16804. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16805. }
  16806. }
  16807. }).bind(_this), Scene.LongPressDelay);
  16808. }
  16809. }
  16810. }
  16811. if (_this.onPointerDown) {
  16812. _this.onPointerDown(evt, pickResult);
  16813. }
  16814. if (_this.onPointerObservable.hasObservers()) {
  16815. var type = PointerEventTypes.POINTERDOWN;
  16816. var pi = new PointerInfo(type, evt, pickResult);
  16817. _this.onPointerObservable.notifyObservers(pi, type);
  16818. }
  16819. // Sprites
  16820. _this._pickedDownSprite = null;
  16821. if (_this.spriteManagers.length > 0) {
  16822. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16823. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16824. if (pickResult.pickedSprite.actionManager) {
  16825. _this._pickedDownSprite = pickResult.pickedSprite;
  16826. switch (evt.button) {
  16827. case 0:
  16828. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16829. break;
  16830. case 1:
  16831. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16832. break;
  16833. case 2:
  16834. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16835. break;
  16836. }
  16837. if (pickResult.pickedSprite.actionManager) {
  16838. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16839. }
  16840. }
  16841. }
  16842. }
  16843. };
  16844. this._onPointerUp = function (evt) {
  16845. _this._isButtonPressed = false;
  16846. _this._pickedUpMesh = null;
  16847. _this._meshPickProceed = false;
  16848. _this._updatePointerPosition(evt);
  16849. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16850. // PreObservable support
  16851. if (this.onPrePointerObservable.hasObservers()) {
  16852. if (!clickInfo.ignore) {
  16853. if (!clickInfo.hasSwiped) {
  16854. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16855. var type = PointerEventTypes.POINTERTAP;
  16856. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16857. this.onPrePointerObservable.notifyObservers(pi, type);
  16858. if (pi.skipOnPointerObservable) {
  16859. return;
  16860. }
  16861. }
  16862. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16863. var type = PointerEventTypes.POINTERDOUBLETAP;
  16864. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16865. this.onPrePointerObservable.notifyObservers(pi, type);
  16866. if (pi.skipOnPointerObservable) {
  16867. return;
  16868. }
  16869. }
  16870. }
  16871. }
  16872. else {
  16873. var type = PointerEventTypes.POINTERUP;
  16874. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16875. this.onPrePointerObservable.notifyObservers(pi, type);
  16876. if (pi.skipOnPointerObservable) {
  16877. return;
  16878. }
  16879. }
  16880. }
  16881. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16882. return;
  16883. }
  16884. if (!this.pointerUpPredicate) {
  16885. this.pointerUpPredicate = function (mesh) {
  16886. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16887. };
  16888. }
  16889. // Meshes
  16890. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16891. this._initActionManager(null, clickInfo);
  16892. }
  16893. if (!pickResult) {
  16894. pickResult = this._currentPickResult;
  16895. }
  16896. if (pickResult && pickResult && pickResult.pickedMesh) {
  16897. this._pickedUpMesh = pickResult.pickedMesh;
  16898. if (this._pickedDownMesh === this._pickedUpMesh) {
  16899. if (this.onPointerPick) {
  16900. this.onPointerPick(evt, pickResult);
  16901. }
  16902. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16903. var type = PointerEventTypes.POINTERPICK;
  16904. var pi = new PointerInfo(type, evt, pickResult);
  16905. this.onPointerObservable.notifyObservers(pi, type);
  16906. }
  16907. }
  16908. if (pickResult.pickedMesh.actionManager) {
  16909. if (clickInfo.ignore) {
  16910. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16911. }
  16912. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16913. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16914. }
  16915. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16916. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16917. }
  16918. }
  16919. }
  16920. if (this._pickedDownMesh &&
  16921. this._pickedDownMesh.actionManager &&
  16922. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16923. this._pickedDownMesh !== this._pickedUpMesh) {
  16924. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16925. }
  16926. if (this.onPointerUp) {
  16927. this.onPointerUp(evt, pickResult);
  16928. }
  16929. if (this.onPointerObservable.hasObservers()) {
  16930. if (!clickInfo.ignore) {
  16931. if (!clickInfo.hasSwiped) {
  16932. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16933. var type = PointerEventTypes.POINTERTAP;
  16934. var pi = new PointerInfo(type, evt, pickResult);
  16935. this.onPointerObservable.notifyObservers(pi, type);
  16936. }
  16937. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16938. var type = PointerEventTypes.POINTERDOUBLETAP;
  16939. var pi = new PointerInfo(type, evt, pickResult);
  16940. this.onPointerObservable.notifyObservers(pi, type);
  16941. }
  16942. }
  16943. }
  16944. else {
  16945. var type = PointerEventTypes.POINTERUP;
  16946. var pi = new PointerInfo(type, evt, pickResult);
  16947. this.onPointerObservable.notifyObservers(pi, type);
  16948. }
  16949. }
  16950. // Sprites
  16951. if (this.spriteManagers.length > 0) {
  16952. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16953. if (pickResult.hit && pickResult.pickedSprite) {
  16954. if (pickResult.pickedSprite.actionManager) {
  16955. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16956. if (pickResult.pickedSprite.actionManager) {
  16957. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16958. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16959. }
  16960. }
  16961. }
  16962. }
  16963. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16964. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16965. }
  16966. }
  16967. this._previousPickResult = this._currentPickResult;
  16968. }).bind(_this));
  16969. };
  16970. this._onKeyDown = function (evt) {
  16971. if (_this.actionManager) {
  16972. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16973. }
  16974. };
  16975. this._onKeyUp = function (evt) {
  16976. if (_this.actionManager) {
  16977. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16978. }
  16979. };
  16980. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16981. var canvas = this._engine.getRenderingCanvas();
  16982. if (attachMove) {
  16983. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16984. // Wheel
  16985. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16986. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16987. }
  16988. if (attachDown) {
  16989. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16990. }
  16991. if (attachUp) {
  16992. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16993. }
  16994. canvas.tabIndex = 1;
  16995. canvas.addEventListener("keydown", this._onKeyDown, false);
  16996. canvas.addEventListener("keyup", this._onKeyUp, false);
  16997. };
  16998. Scene.prototype.detachControl = function () {
  16999. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17000. var canvas = this._engine.getRenderingCanvas();
  17001. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17002. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17003. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17004. // Wheel
  17005. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17006. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17007. canvas.removeEventListener("keydown", this._onKeyDown);
  17008. canvas.removeEventListener("keyup", this._onKeyUp);
  17009. };
  17010. // Ready
  17011. Scene.prototype.isReady = function () {
  17012. if (this._pendingData.length > 0) {
  17013. return false;
  17014. }
  17015. var index;
  17016. // Geometries
  17017. for (index = 0; index < this._geometries.length; index++) {
  17018. var geometry = this._geometries[index];
  17019. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17020. return false;
  17021. }
  17022. }
  17023. // Meshes
  17024. for (index = 0; index < this.meshes.length; index++) {
  17025. var mesh = this.meshes[index];
  17026. if (!mesh.isEnabled()) {
  17027. continue;
  17028. }
  17029. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17030. continue;
  17031. }
  17032. if (!mesh.isReady()) {
  17033. return false;
  17034. }
  17035. var mat = mesh.material;
  17036. if (mat) {
  17037. if (!mat.isReady(mesh)) {
  17038. return false;
  17039. }
  17040. }
  17041. }
  17042. return true;
  17043. };
  17044. Scene.prototype.resetCachedMaterial = function () {
  17045. this._cachedMaterial = null;
  17046. this._cachedEffect = null;
  17047. this._cachedVisibility = null;
  17048. };
  17049. Scene.prototype.registerBeforeRender = function (func) {
  17050. this.onBeforeRenderObservable.add(func);
  17051. };
  17052. Scene.prototype.unregisterBeforeRender = function (func) {
  17053. this.onBeforeRenderObservable.removeCallback(func);
  17054. };
  17055. Scene.prototype.registerAfterRender = function (func) {
  17056. this.onAfterRenderObservable.add(func);
  17057. };
  17058. Scene.prototype.unregisterAfterRender = function (func) {
  17059. this.onAfterRenderObservable.removeCallback(func);
  17060. };
  17061. Scene.prototype._addPendingData = function (data) {
  17062. this._pendingData.push(data);
  17063. };
  17064. Scene.prototype._removePendingData = function (data) {
  17065. var index = this._pendingData.indexOf(data);
  17066. if (index !== -1) {
  17067. this._pendingData.splice(index, 1);
  17068. }
  17069. };
  17070. Scene.prototype.getWaitingItemsCount = function () {
  17071. return this._pendingData.length;
  17072. };
  17073. /**
  17074. * Registers a function to be executed when the scene is ready.
  17075. * @param {Function} func - the function to be executed.
  17076. */
  17077. Scene.prototype.executeWhenReady = function (func) {
  17078. var _this = this;
  17079. this.onReadyObservable.add(func);
  17080. if (this._executeWhenReadyTimeoutId !== -1) {
  17081. return;
  17082. }
  17083. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17084. _this._checkIsReady();
  17085. }, 150);
  17086. };
  17087. Scene.prototype._checkIsReady = function () {
  17088. var _this = this;
  17089. if (this.isReady()) {
  17090. this.onReadyObservable.notifyObservers(this);
  17091. this.onReadyObservable.clear();
  17092. this._executeWhenReadyTimeoutId = -1;
  17093. return;
  17094. }
  17095. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17096. _this._checkIsReady();
  17097. }, 150);
  17098. };
  17099. // Animations
  17100. /**
  17101. * Will start the animation sequence of a given target
  17102. * @param target - the target
  17103. * @param {number} from - from which frame should animation start
  17104. * @param {number} to - till which frame should animation run.
  17105. * @param {boolean} [loop] - should the animation loop
  17106. * @param {number} [speedRatio] - the speed in which to run the animation
  17107. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17108. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17109. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17110. * See BABYLON.Animatable
  17111. */
  17112. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17113. if (speedRatio === void 0) { speedRatio = 1.0; }
  17114. if (from > to && speedRatio > 0) {
  17115. speedRatio *= -1;
  17116. }
  17117. this.stopAnimation(target);
  17118. if (!animatable) {
  17119. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17120. }
  17121. // Local animations
  17122. if (target.animations) {
  17123. animatable.appendAnimations(target, target.animations);
  17124. }
  17125. // Children animations
  17126. if (target.getAnimatables) {
  17127. var animatables = target.getAnimatables();
  17128. for (var index = 0; index < animatables.length; index++) {
  17129. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17130. }
  17131. }
  17132. animatable.reset();
  17133. return animatable;
  17134. };
  17135. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17136. if (speedRatio === undefined) {
  17137. speedRatio = 1.0;
  17138. }
  17139. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17140. return animatable;
  17141. };
  17142. Scene.prototype.getAnimatableByTarget = function (target) {
  17143. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17144. if (this._activeAnimatables[index].target === target) {
  17145. return this._activeAnimatables[index];
  17146. }
  17147. }
  17148. return null;
  17149. };
  17150. Object.defineProperty(Scene.prototype, "Animatables", {
  17151. get: function () {
  17152. return this._activeAnimatables;
  17153. },
  17154. enumerable: true,
  17155. configurable: true
  17156. });
  17157. /**
  17158. * Will stop the animation of the given target
  17159. * @param target - the target
  17160. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17161. * @see beginAnimation
  17162. */
  17163. Scene.prototype.stopAnimation = function (target, animationName) {
  17164. var animatable = this.getAnimatableByTarget(target);
  17165. if (animatable) {
  17166. animatable.stop(animationName);
  17167. }
  17168. };
  17169. Scene.prototype._animate = function () {
  17170. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17171. return;
  17172. }
  17173. // Getting time
  17174. var now = BABYLON.Tools.Now;
  17175. if (!this._animationTimeLast) {
  17176. if (this._pendingData.length > 0) {
  17177. return;
  17178. }
  17179. this._animationTimeLast = now;
  17180. }
  17181. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17182. this._animationTime += deltaTime;
  17183. this._animationTimeLast = now;
  17184. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17185. this._activeAnimatables[index]._animate(this._animationTime);
  17186. }
  17187. };
  17188. // Matrix
  17189. Scene.prototype.getViewMatrix = function () {
  17190. return this._viewMatrix;
  17191. };
  17192. Scene.prototype.getProjectionMatrix = function () {
  17193. return this._projectionMatrix;
  17194. };
  17195. Scene.prototype.getTransformMatrix = function () {
  17196. return this._transformMatrix;
  17197. };
  17198. Scene.prototype.setTransformMatrix = function (view, projection) {
  17199. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17200. return;
  17201. }
  17202. this._viewUpdateFlag = view.updateFlag;
  17203. this._projectionUpdateFlag = projection.updateFlag;
  17204. this._viewMatrix = view;
  17205. this._projectionMatrix = projection;
  17206. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17207. // Update frustum
  17208. if (!this._frustumPlanes) {
  17209. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17210. }
  17211. else {
  17212. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17213. }
  17214. if (this._sceneUbo.useUbo) {
  17215. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17216. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17217. this._sceneUbo.update();
  17218. }
  17219. };
  17220. Scene.prototype.getSceneUniformBuffer = function () {
  17221. return this._sceneUbo;
  17222. };
  17223. // Methods
  17224. Scene.prototype.getUniqueId = function () {
  17225. var result = this._uniqueIdCounter;
  17226. this._uniqueIdCounter++;
  17227. return result;
  17228. };
  17229. Scene.prototype.addMesh = function (newMesh) {
  17230. newMesh.uniqueId = this.getUniqueId();
  17231. var position = this.meshes.push(newMesh);
  17232. //notify the collision coordinator
  17233. if (this.collisionCoordinator) {
  17234. this.collisionCoordinator.onMeshAdded(newMesh);
  17235. }
  17236. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17237. };
  17238. Scene.prototype.removeMesh = function (toRemove) {
  17239. var index = this.meshes.indexOf(toRemove);
  17240. if (index !== -1) {
  17241. // Remove from the scene if mesh found
  17242. this.meshes.splice(index, 1);
  17243. }
  17244. //notify the collision coordinator
  17245. if (this.collisionCoordinator) {
  17246. this.collisionCoordinator.onMeshRemoved(toRemove);
  17247. }
  17248. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17249. return index;
  17250. };
  17251. Scene.prototype.removeSkeleton = function (toRemove) {
  17252. var index = this.skeletons.indexOf(toRemove);
  17253. if (index !== -1) {
  17254. // Remove from the scene if found
  17255. this.skeletons.splice(index, 1);
  17256. }
  17257. return index;
  17258. };
  17259. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17260. var index = this.morphTargetManagers.indexOf(toRemove);
  17261. if (index !== -1) {
  17262. // Remove from the scene if found
  17263. this.morphTargetManagers.splice(index, 1);
  17264. }
  17265. return index;
  17266. };
  17267. Scene.prototype.removeLight = function (toRemove) {
  17268. var index = this.lights.indexOf(toRemove);
  17269. if (index !== -1) {
  17270. // Remove from the scene if mesh found
  17271. this.lights.splice(index, 1);
  17272. this.sortLightsByPriority();
  17273. }
  17274. this.onLightRemovedObservable.notifyObservers(toRemove);
  17275. return index;
  17276. };
  17277. Scene.prototype.removeCamera = function (toRemove) {
  17278. var index = this.cameras.indexOf(toRemove);
  17279. if (index !== -1) {
  17280. // Remove from the scene if mesh found
  17281. this.cameras.splice(index, 1);
  17282. }
  17283. // Remove from activeCameras
  17284. var index2 = this.activeCameras.indexOf(toRemove);
  17285. if (index2 !== -1) {
  17286. // Remove from the scene if mesh found
  17287. this.activeCameras.splice(index2, 1);
  17288. }
  17289. // Reset the activeCamera
  17290. if (this.activeCamera === toRemove) {
  17291. if (this.cameras.length > 0) {
  17292. this.activeCamera = this.cameras[0];
  17293. }
  17294. else {
  17295. this.activeCamera = null;
  17296. }
  17297. }
  17298. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17299. return index;
  17300. };
  17301. Scene.prototype.addLight = function (newLight) {
  17302. newLight.uniqueId = this.getUniqueId();
  17303. this.lights.push(newLight);
  17304. this.sortLightsByPriority();
  17305. this.onNewLightAddedObservable.notifyObservers(newLight);
  17306. };
  17307. Scene.prototype.sortLightsByPriority = function () {
  17308. if (this.requireLightSorting) {
  17309. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17310. }
  17311. };
  17312. Scene.prototype.addCamera = function (newCamera) {
  17313. newCamera.uniqueId = this.getUniqueId();
  17314. var position = this.cameras.push(newCamera);
  17315. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17316. };
  17317. /**
  17318. * Switch active camera
  17319. * @param {Camera} newCamera - new active camera
  17320. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17321. */
  17322. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17323. if (attachControl === void 0) { attachControl = true; }
  17324. var canvas = this._engine.getRenderingCanvas();
  17325. this.activeCamera.detachControl(canvas);
  17326. this.activeCamera = newCamera;
  17327. if (attachControl) {
  17328. newCamera.attachControl(canvas);
  17329. }
  17330. };
  17331. /**
  17332. * sets the active camera of the scene using its ID
  17333. * @param {string} id - the camera's ID
  17334. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17335. * @see activeCamera
  17336. */
  17337. Scene.prototype.setActiveCameraByID = function (id) {
  17338. var camera = this.getCameraByID(id);
  17339. if (camera) {
  17340. this.activeCamera = camera;
  17341. return camera;
  17342. }
  17343. return null;
  17344. };
  17345. /**
  17346. * sets the active camera of the scene using its name
  17347. * @param {string} name - the camera's name
  17348. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17349. * @see activeCamera
  17350. */
  17351. Scene.prototype.setActiveCameraByName = function (name) {
  17352. var camera = this.getCameraByName(name);
  17353. if (camera) {
  17354. this.activeCamera = camera;
  17355. return camera;
  17356. }
  17357. return null;
  17358. };
  17359. /**
  17360. * get a material using its id
  17361. * @param {string} the material's ID
  17362. * @return {BABYLON.Material|null} the material or null if none found.
  17363. */
  17364. Scene.prototype.getMaterialByID = function (id) {
  17365. for (var index = 0; index < this.materials.length; index++) {
  17366. if (this.materials[index].id === id) {
  17367. return this.materials[index];
  17368. }
  17369. }
  17370. return null;
  17371. };
  17372. /**
  17373. * get a material using its name
  17374. * @param {string} the material's name
  17375. * @return {BABYLON.Material|null} the material or null if none found.
  17376. */
  17377. Scene.prototype.getMaterialByName = function (name) {
  17378. for (var index = 0; index < this.materials.length; index++) {
  17379. if (this.materials[index].name === name) {
  17380. return this.materials[index];
  17381. }
  17382. }
  17383. return null;
  17384. };
  17385. Scene.prototype.getLensFlareSystemByName = function (name) {
  17386. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17387. if (this.lensFlareSystems[index].name === name) {
  17388. return this.lensFlareSystems[index];
  17389. }
  17390. }
  17391. return null;
  17392. };
  17393. Scene.prototype.getLensFlareSystemByID = function (id) {
  17394. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17395. if (this.lensFlareSystems[index].id === id) {
  17396. return this.lensFlareSystems[index];
  17397. }
  17398. }
  17399. return null;
  17400. };
  17401. Scene.prototype.getCameraByID = function (id) {
  17402. for (var index = 0; index < this.cameras.length; index++) {
  17403. if (this.cameras[index].id === id) {
  17404. return this.cameras[index];
  17405. }
  17406. }
  17407. return null;
  17408. };
  17409. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17410. for (var index = 0; index < this.cameras.length; index++) {
  17411. if (this.cameras[index].uniqueId === uniqueId) {
  17412. return this.cameras[index];
  17413. }
  17414. }
  17415. return null;
  17416. };
  17417. /**
  17418. * get a camera using its name
  17419. * @param {string} the camera's name
  17420. * @return {BABYLON.Camera|null} the camera or null if none found.
  17421. */
  17422. Scene.prototype.getCameraByName = function (name) {
  17423. for (var index = 0; index < this.cameras.length; index++) {
  17424. if (this.cameras[index].name === name) {
  17425. return this.cameras[index];
  17426. }
  17427. }
  17428. return null;
  17429. };
  17430. /**
  17431. * get a bone using its id
  17432. * @param {string} the bone's id
  17433. * @return {BABYLON.Bone|null} the bone or null if not found
  17434. */
  17435. Scene.prototype.getBoneByID = function (id) {
  17436. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17437. var skeleton = this.skeletons[skeletonIndex];
  17438. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17439. if (skeleton.bones[boneIndex].id === id) {
  17440. return skeleton.bones[boneIndex];
  17441. }
  17442. }
  17443. }
  17444. return null;
  17445. };
  17446. /**
  17447. * get a bone using its id
  17448. * @param {string} the bone's name
  17449. * @return {BABYLON.Bone|null} the bone or null if not found
  17450. */
  17451. Scene.prototype.getBoneByName = function (name) {
  17452. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17453. var skeleton = this.skeletons[skeletonIndex];
  17454. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17455. if (skeleton.bones[boneIndex].name === name) {
  17456. return skeleton.bones[boneIndex];
  17457. }
  17458. }
  17459. }
  17460. return null;
  17461. };
  17462. /**
  17463. * get a light node using its name
  17464. * @param {string} the light's name
  17465. * @return {BABYLON.Light|null} the light or null if none found.
  17466. */
  17467. Scene.prototype.getLightByName = function (name) {
  17468. for (var index = 0; index < this.lights.length; index++) {
  17469. if (this.lights[index].name === name) {
  17470. return this.lights[index];
  17471. }
  17472. }
  17473. return null;
  17474. };
  17475. /**
  17476. * get a light node using its ID
  17477. * @param {string} the light's id
  17478. * @return {BABYLON.Light|null} the light or null if none found.
  17479. */
  17480. Scene.prototype.getLightByID = function (id) {
  17481. for (var index = 0; index < this.lights.length; index++) {
  17482. if (this.lights[index].id === id) {
  17483. return this.lights[index];
  17484. }
  17485. }
  17486. return null;
  17487. };
  17488. /**
  17489. * get a light node using its scene-generated unique ID
  17490. * @param {number} the light's unique id
  17491. * @return {BABYLON.Light|null} the light or null if none found.
  17492. */
  17493. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17494. for (var index = 0; index < this.lights.length; index++) {
  17495. if (this.lights[index].uniqueId === uniqueId) {
  17496. return this.lights[index];
  17497. }
  17498. }
  17499. return null;
  17500. };
  17501. /**
  17502. * get a particle system by id
  17503. * @param id {number} the particle system id
  17504. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17505. */
  17506. Scene.prototype.getParticleSystemByID = function (id) {
  17507. for (var index = 0; index < this.particleSystems.length; index++) {
  17508. if (this.particleSystems[index].id === id) {
  17509. return this.particleSystems[index];
  17510. }
  17511. }
  17512. return null;
  17513. };
  17514. /**
  17515. * get a geometry using its ID
  17516. * @param {string} the geometry's id
  17517. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17518. */
  17519. Scene.prototype.getGeometryByID = function (id) {
  17520. for (var index = 0; index < this._geometries.length; index++) {
  17521. if (this._geometries[index].id === id) {
  17522. return this._geometries[index];
  17523. }
  17524. }
  17525. return null;
  17526. };
  17527. /**
  17528. * add a new geometry to this scene.
  17529. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17530. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17531. * @return {boolean} was the geometry added or not
  17532. */
  17533. Scene.prototype.pushGeometry = function (geometry, force) {
  17534. if (!force && this.getGeometryByID(geometry.id)) {
  17535. return false;
  17536. }
  17537. this._geometries.push(geometry);
  17538. //notify the collision coordinator
  17539. if (this.collisionCoordinator) {
  17540. this.collisionCoordinator.onGeometryAdded(geometry);
  17541. }
  17542. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17543. return true;
  17544. };
  17545. /**
  17546. * Removes an existing geometry
  17547. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17548. * @return {boolean} was the geometry removed or not
  17549. */
  17550. Scene.prototype.removeGeometry = function (geometry) {
  17551. var index = this._geometries.indexOf(geometry);
  17552. if (index > -1) {
  17553. this._geometries.splice(index, 1);
  17554. //notify the collision coordinator
  17555. if (this.collisionCoordinator) {
  17556. this.collisionCoordinator.onGeometryDeleted(geometry);
  17557. }
  17558. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17559. return true;
  17560. }
  17561. return false;
  17562. };
  17563. Scene.prototype.getGeometries = function () {
  17564. return this._geometries;
  17565. };
  17566. /**
  17567. * Get the first added mesh found of a given ID
  17568. * @param {string} id - the id to search for
  17569. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17570. */
  17571. Scene.prototype.getMeshByID = function (id) {
  17572. for (var index = 0; index < this.meshes.length; index++) {
  17573. if (this.meshes[index].id === id) {
  17574. return this.meshes[index];
  17575. }
  17576. }
  17577. return null;
  17578. };
  17579. Scene.prototype.getMeshesByID = function (id) {
  17580. return this.meshes.filter(function (m) {
  17581. return m.id === id;
  17582. });
  17583. };
  17584. /**
  17585. * Get a mesh with its auto-generated unique id
  17586. * @param {number} uniqueId - the unique id to search for
  17587. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17588. */
  17589. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17590. for (var index = 0; index < this.meshes.length; index++) {
  17591. if (this.meshes[index].uniqueId === uniqueId) {
  17592. return this.meshes[index];
  17593. }
  17594. }
  17595. return null;
  17596. };
  17597. /**
  17598. * Get a the last added mesh found of a given ID
  17599. * @param {string} id - the id to search for
  17600. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17601. */
  17602. Scene.prototype.getLastMeshByID = function (id) {
  17603. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17604. if (this.meshes[index].id === id) {
  17605. return this.meshes[index];
  17606. }
  17607. }
  17608. return null;
  17609. };
  17610. /**
  17611. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17612. * @param {string} id - the id to search for
  17613. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17614. */
  17615. Scene.prototype.getLastEntryByID = function (id) {
  17616. var index;
  17617. for (index = this.meshes.length - 1; index >= 0; index--) {
  17618. if (this.meshes[index].id === id) {
  17619. return this.meshes[index];
  17620. }
  17621. }
  17622. for (index = this.cameras.length - 1; index >= 0; index--) {
  17623. if (this.cameras[index].id === id) {
  17624. return this.cameras[index];
  17625. }
  17626. }
  17627. for (index = this.lights.length - 1; index >= 0; index--) {
  17628. if (this.lights[index].id === id) {
  17629. return this.lights[index];
  17630. }
  17631. }
  17632. return null;
  17633. };
  17634. Scene.prototype.getNodeByID = function (id) {
  17635. var mesh = this.getMeshByID(id);
  17636. if (mesh) {
  17637. return mesh;
  17638. }
  17639. var light = this.getLightByID(id);
  17640. if (light) {
  17641. return light;
  17642. }
  17643. var camera = this.getCameraByID(id);
  17644. if (camera) {
  17645. return camera;
  17646. }
  17647. var bone = this.getBoneByID(id);
  17648. return bone;
  17649. };
  17650. Scene.prototype.getNodeByName = function (name) {
  17651. var mesh = this.getMeshByName(name);
  17652. if (mesh) {
  17653. return mesh;
  17654. }
  17655. var light = this.getLightByName(name);
  17656. if (light) {
  17657. return light;
  17658. }
  17659. var camera = this.getCameraByName(name);
  17660. if (camera) {
  17661. return camera;
  17662. }
  17663. var bone = this.getBoneByName(name);
  17664. return bone;
  17665. };
  17666. Scene.prototype.getMeshByName = function (name) {
  17667. for (var index = 0; index < this.meshes.length; index++) {
  17668. if (this.meshes[index].name === name) {
  17669. return this.meshes[index];
  17670. }
  17671. }
  17672. return null;
  17673. };
  17674. Scene.prototype.getSoundByName = function (name) {
  17675. var index;
  17676. if (BABYLON.AudioEngine) {
  17677. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17678. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17679. return this.mainSoundTrack.soundCollection[index];
  17680. }
  17681. }
  17682. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17683. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17684. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17685. return this.soundTracks[sdIndex].soundCollection[index];
  17686. }
  17687. }
  17688. }
  17689. }
  17690. return null;
  17691. };
  17692. Scene.prototype.getLastSkeletonByID = function (id) {
  17693. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17694. if (this.skeletons[index].id === id) {
  17695. return this.skeletons[index];
  17696. }
  17697. }
  17698. return null;
  17699. };
  17700. Scene.prototype.getSkeletonById = function (id) {
  17701. for (var index = 0; index < this.skeletons.length; index++) {
  17702. if (this.skeletons[index].id === id) {
  17703. return this.skeletons[index];
  17704. }
  17705. }
  17706. return null;
  17707. };
  17708. Scene.prototype.getSkeletonByName = function (name) {
  17709. for (var index = 0; index < this.skeletons.length; index++) {
  17710. if (this.skeletons[index].name === name) {
  17711. return this.skeletons[index];
  17712. }
  17713. }
  17714. return null;
  17715. };
  17716. Scene.prototype.getMorphTargetManagerById = function (id) {
  17717. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17718. if (this.morphTargetManagers[index].uniqueId === id) {
  17719. return this.morphTargetManagers[index];
  17720. }
  17721. }
  17722. return null;
  17723. };
  17724. Scene.prototype.isActiveMesh = function (mesh) {
  17725. return (this._activeMeshes.indexOf(mesh) !== -1);
  17726. };
  17727. /**
  17728. * Return a the first highlight layer of the scene with a given name.
  17729. * @param name The name of the highlight layer to look for.
  17730. * @return The highlight layer if found otherwise null.
  17731. */
  17732. Scene.prototype.getHighlightLayerByName = function (name) {
  17733. for (var index = 0; index < this.highlightLayers.length; index++) {
  17734. if (this.highlightLayers[index].name === name) {
  17735. return this.highlightLayers[index];
  17736. }
  17737. }
  17738. return null;
  17739. };
  17740. Object.defineProperty(Scene.prototype, "uid", {
  17741. /**
  17742. * Return a unique id as a string which can serve as an identifier for the scene
  17743. */
  17744. get: function () {
  17745. if (!this._uid) {
  17746. this._uid = BABYLON.Tools.RandomId();
  17747. }
  17748. return this._uid;
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. /**
  17754. * Add an externaly attached data from its key.
  17755. * This method call will fail and return false, if such key already exists.
  17756. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17757. * @param key the unique key that identifies the data
  17758. * @param data the data object to associate to the key for this Engine instance
  17759. * @return true if no such key were already present and the data was added successfully, false otherwise
  17760. */
  17761. Scene.prototype.addExternalData = function (key, data) {
  17762. if (!this._externalData) {
  17763. this._externalData = new BABYLON.StringDictionary();
  17764. }
  17765. return this._externalData.add(key, data);
  17766. };
  17767. /**
  17768. * Get an externaly attached data from its key
  17769. * @param key the unique key that identifies the data
  17770. * @return the associated data, if present (can be null), or undefined if not present
  17771. */
  17772. Scene.prototype.getExternalData = function (key) {
  17773. if (!this._externalData) {
  17774. return null;
  17775. }
  17776. return this._externalData.get(key);
  17777. };
  17778. /**
  17779. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17780. * @param key the unique key that identifies the data
  17781. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17782. * @return the associated data, can be null if the factory returned null.
  17783. */
  17784. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17785. if (!this._externalData) {
  17786. this._externalData = new BABYLON.StringDictionary();
  17787. }
  17788. return this._externalData.getOrAddWithFactory(key, factory);
  17789. };
  17790. /**
  17791. * Remove an externaly attached data from the Engine instance
  17792. * @param key the unique key that identifies the data
  17793. * @return true if the data was successfully removed, false if it doesn't exist
  17794. */
  17795. Scene.prototype.removeExternalData = function (key) {
  17796. return this._externalData.remove(key);
  17797. };
  17798. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17799. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17800. var material = subMesh.getMaterial();
  17801. if (mesh.showSubMeshesBoundingBox) {
  17802. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17803. }
  17804. if (material) {
  17805. // Render targets
  17806. if (material.getRenderTargetTextures) {
  17807. if (this._processedMaterials.indexOf(material) === -1) {
  17808. this._processedMaterials.push(material);
  17809. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17810. }
  17811. }
  17812. // Dispatch
  17813. this._activeIndices.addCount(subMesh.indexCount, false);
  17814. this._renderingManager.dispatch(subMesh);
  17815. }
  17816. }
  17817. };
  17818. Scene.prototype._isInIntermediateRendering = function () {
  17819. return this._intermediateRendering;
  17820. };
  17821. Scene.prototype._evaluateActiveMeshes = function () {
  17822. this.activeCamera._activeMeshes.reset();
  17823. this._activeMeshes.reset();
  17824. this._renderingManager.reset();
  17825. this._processedMaterials.reset();
  17826. this._activeParticleSystems.reset();
  17827. this._activeSkeletons.reset();
  17828. this._softwareSkinnedMeshes.reset();
  17829. if (this._boundingBoxRenderer) {
  17830. this._boundingBoxRenderer.reset();
  17831. }
  17832. // Meshes
  17833. var meshes;
  17834. var len;
  17835. if (this._selectionOctree) {
  17836. var selection = this._selectionOctree.select(this._frustumPlanes);
  17837. meshes = selection.data;
  17838. len = selection.length;
  17839. }
  17840. else {
  17841. len = this.meshes.length;
  17842. meshes = this.meshes;
  17843. }
  17844. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17845. var mesh = meshes[meshIndex];
  17846. if (mesh.isBlocked) {
  17847. continue;
  17848. }
  17849. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17850. if (!mesh.isReady() || !mesh.isEnabled()) {
  17851. continue;
  17852. }
  17853. mesh.computeWorldMatrix();
  17854. // Intersections
  17855. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17856. this._meshesForIntersections.pushNoDuplicate(mesh);
  17857. }
  17858. // Switch to current LOD
  17859. var meshLOD = mesh.getLOD(this.activeCamera);
  17860. if (!meshLOD) {
  17861. continue;
  17862. }
  17863. mesh._preActivate();
  17864. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17865. this._activeMeshes.push(mesh);
  17866. this.activeCamera._activeMeshes.push(mesh);
  17867. mesh._activate(this._renderId);
  17868. this._activeMesh(mesh, meshLOD);
  17869. }
  17870. }
  17871. // Particle systems
  17872. this._particlesDuration.beginMonitoring();
  17873. var beforeParticlesDate = BABYLON.Tools.Now;
  17874. if (this.particlesEnabled) {
  17875. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17876. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17877. var particleSystem = this.particleSystems[particleIndex];
  17878. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  17879. continue;
  17880. }
  17881. var emitter = particleSystem.emitter;
  17882. if (!emitter.position || emitter.isEnabled()) {
  17883. this._activeParticleSystems.push(particleSystem);
  17884. particleSystem.animate();
  17885. this._renderingManager.dispatchParticles(particleSystem);
  17886. }
  17887. }
  17888. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17889. }
  17890. this._particlesDuration.endMonitoring(false);
  17891. };
  17892. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17893. if (mesh.skeleton && this.skeletonsEnabled) {
  17894. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17895. mesh.skeleton.prepare();
  17896. }
  17897. if (!mesh.computeBonesUsingShaders) {
  17898. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17899. }
  17900. }
  17901. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17902. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17903. }
  17904. if (mesh && mesh.subMeshes) {
  17905. // Submeshes Octrees
  17906. var len;
  17907. var subMeshes;
  17908. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17909. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17910. len = intersections.length;
  17911. subMeshes = intersections.data;
  17912. }
  17913. else {
  17914. subMeshes = mesh.subMeshes;
  17915. len = subMeshes.length;
  17916. }
  17917. for (var subIndex = 0; subIndex < len; subIndex++) {
  17918. var subMesh = subMeshes[subIndex];
  17919. this._evaluateSubMesh(subMesh, mesh);
  17920. }
  17921. }
  17922. };
  17923. Scene.prototype.updateTransformMatrix = function (force) {
  17924. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17925. };
  17926. Scene.prototype._renderForCamera = function (camera) {
  17927. var engine = this._engine;
  17928. var startTime = BABYLON.Tools.Now;
  17929. this.activeCamera = camera;
  17930. if (!this.activeCamera)
  17931. throw new Error("Active camera not set");
  17932. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17933. // Viewport
  17934. engine.setViewport(this.activeCamera.viewport);
  17935. // Camera
  17936. this.resetCachedMaterial();
  17937. this._renderId++;
  17938. this.updateTransformMatrix();
  17939. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17940. // Meshes
  17941. this._evaluateActiveMeshesDuration.beginMonitoring();
  17942. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17943. this._evaluateActiveMeshes();
  17944. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17945. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17946. // Software skinning
  17947. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17948. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17949. mesh.applySkeleton(mesh.skeleton);
  17950. }
  17951. // Render targets
  17952. this._renderTargetsDuration.beginMonitoring();
  17953. var needsRestoreFrameBuffer = false;
  17954. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17955. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17956. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17957. }
  17958. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17959. this._intermediateRendering = true;
  17960. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17961. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17962. var renderTarget = this._renderTargets.data[renderIndex];
  17963. if (renderTarget._shouldRender()) {
  17964. this._renderId++;
  17965. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17966. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17967. }
  17968. }
  17969. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17970. this._intermediateRendering = false;
  17971. this._renderId++;
  17972. needsRestoreFrameBuffer = true; // Restore back buffer
  17973. }
  17974. // Render HighlightLayer Texture
  17975. var stencilState = this._engine.getStencilBuffer();
  17976. var renderhighlights = false;
  17977. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17978. this._intermediateRendering = true;
  17979. for (var i = 0; i < this.highlightLayers.length; i++) {
  17980. var highlightLayer = this.highlightLayers[i];
  17981. if (highlightLayer.shouldRender() &&
  17982. (!highlightLayer.camera ||
  17983. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17984. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17985. renderhighlights = true;
  17986. var renderTarget = highlightLayer._mainTexture;
  17987. if (renderTarget._shouldRender()) {
  17988. this._renderId++;
  17989. renderTarget.render(false, false);
  17990. needsRestoreFrameBuffer = true;
  17991. }
  17992. }
  17993. }
  17994. this._intermediateRendering = false;
  17995. this._renderId++;
  17996. }
  17997. if (needsRestoreFrameBuffer) {
  17998. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17999. }
  18000. this._renderTargetsDuration.endMonitoring(false);
  18001. // Prepare Frame
  18002. this.postProcessManager._prepareFrame();
  18003. this._renderDuration.beginMonitoring();
  18004. // Backgrounds
  18005. var layerIndex;
  18006. var layer;
  18007. if (this.layers.length) {
  18008. engine.setDepthBuffer(false);
  18009. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18010. layer = this.layers[layerIndex];
  18011. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18012. layer.render();
  18013. }
  18014. }
  18015. engine.setDepthBuffer(true);
  18016. }
  18017. // Render
  18018. BABYLON.Tools.StartPerformanceCounter("Main render");
  18019. // Activate HighlightLayer stencil
  18020. if (renderhighlights) {
  18021. this._engine.setStencilBuffer(true);
  18022. }
  18023. this._renderingManager.render(null, null, true, true);
  18024. // Restore HighlightLayer stencil
  18025. if (renderhighlights) {
  18026. this._engine.setStencilBuffer(stencilState);
  18027. }
  18028. BABYLON.Tools.EndPerformanceCounter("Main render");
  18029. // Bounding boxes
  18030. if (this._boundingBoxRenderer) {
  18031. this._boundingBoxRenderer.render();
  18032. }
  18033. // Lens flares
  18034. if (this.lensFlaresEnabled) {
  18035. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18036. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18037. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18038. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18039. lensFlareSystem.render();
  18040. }
  18041. }
  18042. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18043. }
  18044. // Foregrounds
  18045. if (this.layers.length) {
  18046. engine.setDepthBuffer(false);
  18047. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18048. layer = this.layers[layerIndex];
  18049. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18050. layer.render();
  18051. }
  18052. }
  18053. engine.setDepthBuffer(true);
  18054. }
  18055. // Highlight Layer
  18056. if (renderhighlights) {
  18057. engine.setDepthBuffer(false);
  18058. for (var i = 0; i < this.highlightLayers.length; i++) {
  18059. if (this.highlightLayers[i].shouldRender()) {
  18060. this.highlightLayers[i].render();
  18061. }
  18062. }
  18063. engine.setDepthBuffer(true);
  18064. }
  18065. this._renderDuration.endMonitoring(false);
  18066. // Finalize frame
  18067. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18068. // Update camera
  18069. this.activeCamera._updateFromScene();
  18070. // Reset some special arrays
  18071. this._renderTargets.reset();
  18072. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18073. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18074. };
  18075. Scene.prototype._processSubCameras = function (camera) {
  18076. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18077. this._renderForCamera(camera);
  18078. return;
  18079. }
  18080. // rig cameras
  18081. for (var index = 0; index < camera._rigCameras.length; index++) {
  18082. this._renderForCamera(camera._rigCameras[index]);
  18083. }
  18084. this.activeCamera = camera;
  18085. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18086. // Update camera
  18087. this.activeCamera._updateFromScene();
  18088. };
  18089. Scene.prototype._checkIntersections = function () {
  18090. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18091. var sourceMesh = this._meshesForIntersections.data[index];
  18092. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18093. var action = sourceMesh.actionManager.actions[actionIndex];
  18094. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18095. var parameters = action.getTriggerParameter();
  18096. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18097. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18098. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18099. if (areIntersecting && currentIntersectionInProgress === -1) {
  18100. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18101. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18102. sourceMesh._intersectionsInProgress.push(otherMesh);
  18103. }
  18104. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18105. sourceMesh._intersectionsInProgress.push(otherMesh);
  18106. }
  18107. }
  18108. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18109. //They intersected, and now they don't.
  18110. //is this trigger an exit trigger? execute an event.
  18111. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18112. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18113. }
  18114. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18115. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18116. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18117. }
  18118. }
  18119. }
  18120. }
  18121. }
  18122. };
  18123. Scene.prototype.render = function () {
  18124. if (this.isDisposed) {
  18125. return;
  18126. }
  18127. this._lastFrameDuration.beginMonitoring();
  18128. this._particlesDuration.fetchNewFrame();
  18129. this._spritesDuration.fetchNewFrame();
  18130. this._activeParticles.fetchNewFrame();
  18131. this._renderDuration.fetchNewFrame();
  18132. this._renderTargetsDuration.fetchNewFrame();
  18133. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18134. this._totalVertices.fetchNewFrame();
  18135. this._activeIndices.fetchNewFrame();
  18136. this._activeBones.fetchNewFrame();
  18137. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18138. this._meshesForIntersections.reset();
  18139. this.resetCachedMaterial();
  18140. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18141. // Actions
  18142. if (this.actionManager) {
  18143. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18144. }
  18145. //Simplification Queue
  18146. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18147. this.simplificationQueue.executeNext();
  18148. }
  18149. // Animations
  18150. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18151. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18152. this._animate();
  18153. // Physics
  18154. if (this._physicsEngine) {
  18155. BABYLON.Tools.StartPerformanceCounter("Physics");
  18156. this._physicsEngine._step(deltaTime / 1000.0);
  18157. BABYLON.Tools.EndPerformanceCounter("Physics");
  18158. }
  18159. // Before render
  18160. this.onBeforeRenderObservable.notifyObservers(this);
  18161. // Customs render targets
  18162. this._renderTargetsDuration.beginMonitoring();
  18163. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18164. var engine = this.getEngine();
  18165. var currentActiveCamera = this.activeCamera;
  18166. if (this.renderTargetsEnabled) {
  18167. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18168. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18169. var renderTarget = this.customRenderTargets[customIndex];
  18170. if (renderTarget._shouldRender()) {
  18171. this._renderId++;
  18172. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18173. if (!this.activeCamera)
  18174. throw new Error("Active camera not set");
  18175. // Viewport
  18176. engine.setViewport(this.activeCamera.viewport);
  18177. // Camera
  18178. this.updateTransformMatrix();
  18179. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18180. }
  18181. }
  18182. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18183. this._renderId++;
  18184. }
  18185. // Restore back buffer
  18186. if (this.customRenderTargets.length > 0) {
  18187. engine.restoreDefaultFramebuffer();
  18188. }
  18189. this._renderTargetsDuration.endMonitoring();
  18190. this.activeCamera = currentActiveCamera;
  18191. // Procedural textures
  18192. if (this.proceduralTexturesEnabled) {
  18193. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18194. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18195. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18196. if (proceduralTexture._shouldRender()) {
  18197. proceduralTexture.render();
  18198. }
  18199. }
  18200. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18201. }
  18202. // Clear
  18203. if (this.autoClearDepthAndStencil || this.autoClear) {
  18204. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18205. }
  18206. // Shadows
  18207. if (this.shadowsEnabled) {
  18208. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18209. var light = this.lights[lightIndex];
  18210. var shadowGenerator = light.getShadowGenerator();
  18211. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18212. var shadowMap = shadowGenerator.getShadowMap();
  18213. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18214. this._renderTargets.push(shadowMap);
  18215. }
  18216. }
  18217. }
  18218. }
  18219. // Depth renderer
  18220. if (this._depthRenderer) {
  18221. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18222. }
  18223. // Geometry renderer
  18224. if (this._geometryBufferRenderer) {
  18225. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18226. }
  18227. // RenderPipeline
  18228. if (this._postProcessRenderPipelineManager) {
  18229. this._postProcessRenderPipelineManager.update();
  18230. }
  18231. // Multi-cameras?
  18232. if (this.activeCameras.length > 0) {
  18233. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18234. if (cameraIndex > 0) {
  18235. this._engine.clear(null, false, true, true);
  18236. }
  18237. this._processSubCameras(this.activeCameras[cameraIndex]);
  18238. }
  18239. }
  18240. else {
  18241. if (!this.activeCamera) {
  18242. throw new Error("No camera defined");
  18243. }
  18244. this._processSubCameras(this.activeCamera);
  18245. }
  18246. // Intersection checks
  18247. this._checkIntersections();
  18248. // Update the audio listener attached to the camera
  18249. if (BABYLON.AudioEngine) {
  18250. this._updateAudioParameters();
  18251. }
  18252. // After render
  18253. if (this.afterRender) {
  18254. this.afterRender();
  18255. }
  18256. this.onAfterRenderObservable.notifyObservers(this);
  18257. // Cleaning
  18258. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18259. this._toBeDisposed.data[index].dispose();
  18260. this._toBeDisposed[index] = null;
  18261. }
  18262. this._toBeDisposed.reset();
  18263. if (this.dumpNextRenderTargets) {
  18264. this.dumpNextRenderTargets = false;
  18265. }
  18266. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18267. this._lastFrameDuration.endMonitoring();
  18268. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18269. this._totalLightsCounter.addCount(this.lights.length, true);
  18270. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18271. this._totalTexturesCounter.addCount(this.textures.length, true);
  18272. this._activeBones.addCount(0, true);
  18273. this._activeIndices.addCount(0, true);
  18274. this._activeParticles.addCount(0, true);
  18275. };
  18276. Scene.prototype._updateAudioParameters = function () {
  18277. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18278. return;
  18279. }
  18280. var listeningCamera;
  18281. var audioEngine = BABYLON.Engine.audioEngine;
  18282. if (this.activeCameras.length > 0) {
  18283. listeningCamera = this.activeCameras[0];
  18284. }
  18285. else {
  18286. listeningCamera = this.activeCamera;
  18287. }
  18288. if (listeningCamera && audioEngine.canUseWebAudio) {
  18289. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18290. // for VR cameras
  18291. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18292. listeningCamera = listeningCamera.rigCameras[0];
  18293. }
  18294. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18295. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18296. cameraDirection.normalize();
  18297. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18298. var i;
  18299. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18300. var sound = this.mainSoundTrack.soundCollection[i];
  18301. if (sound.useCustomAttenuation) {
  18302. sound.updateDistanceFromListener();
  18303. }
  18304. }
  18305. for (i = 0; i < this.soundTracks.length; i++) {
  18306. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18307. sound = this.soundTracks[i].soundCollection[j];
  18308. if (sound.useCustomAttenuation) {
  18309. sound.updateDistanceFromListener();
  18310. }
  18311. }
  18312. }
  18313. }
  18314. };
  18315. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18316. // Audio
  18317. get: function () {
  18318. return this._audioEnabled;
  18319. },
  18320. set: function (value) {
  18321. this._audioEnabled = value;
  18322. if (BABYLON.AudioEngine) {
  18323. if (this._audioEnabled) {
  18324. this._enableAudio();
  18325. }
  18326. else {
  18327. this._disableAudio();
  18328. }
  18329. }
  18330. },
  18331. enumerable: true,
  18332. configurable: true
  18333. });
  18334. Scene.prototype._disableAudio = function () {
  18335. var i;
  18336. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18337. this.mainSoundTrack.soundCollection[i].pause();
  18338. }
  18339. for (i = 0; i < this.soundTracks.length; i++) {
  18340. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18341. this.soundTracks[i].soundCollection[j].pause();
  18342. }
  18343. }
  18344. };
  18345. Scene.prototype._enableAudio = function () {
  18346. var i;
  18347. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18348. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18349. this.mainSoundTrack.soundCollection[i].play();
  18350. }
  18351. }
  18352. for (i = 0; i < this.soundTracks.length; i++) {
  18353. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18354. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18355. this.soundTracks[i].soundCollection[j].play();
  18356. }
  18357. }
  18358. }
  18359. };
  18360. Object.defineProperty(Scene.prototype, "headphone", {
  18361. get: function () {
  18362. return this._headphone;
  18363. },
  18364. set: function (value) {
  18365. this._headphone = value;
  18366. if (BABYLON.AudioEngine) {
  18367. if (this._headphone) {
  18368. this._switchAudioModeForHeadphones();
  18369. }
  18370. else {
  18371. this._switchAudioModeForNormalSpeakers();
  18372. }
  18373. }
  18374. },
  18375. enumerable: true,
  18376. configurable: true
  18377. });
  18378. Scene.prototype._switchAudioModeForHeadphones = function () {
  18379. this.mainSoundTrack.switchPanningModelToHRTF();
  18380. for (var i = 0; i < this.soundTracks.length; i++) {
  18381. this.soundTracks[i].switchPanningModelToHRTF();
  18382. }
  18383. };
  18384. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18385. this.mainSoundTrack.switchPanningModelToEqualPower();
  18386. for (var i = 0; i < this.soundTracks.length; i++) {
  18387. this.soundTracks[i].switchPanningModelToEqualPower();
  18388. }
  18389. };
  18390. Scene.prototype.enableDepthRenderer = function () {
  18391. if (this._depthRenderer) {
  18392. return this._depthRenderer;
  18393. }
  18394. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18395. return this._depthRenderer;
  18396. };
  18397. Scene.prototype.disableDepthRenderer = function () {
  18398. if (!this._depthRenderer) {
  18399. return;
  18400. }
  18401. this._depthRenderer.dispose();
  18402. this._depthRenderer = null;
  18403. };
  18404. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18405. if (ratio === void 0) { ratio = 1; }
  18406. if (this._geometryBufferRenderer) {
  18407. return this._geometryBufferRenderer;
  18408. }
  18409. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18410. if (!this._geometryBufferRenderer.isSupported) {
  18411. this._geometryBufferRenderer = null;
  18412. }
  18413. return this._geometryBufferRenderer;
  18414. };
  18415. Scene.prototype.disableGeometryBufferRenderer = function () {
  18416. if (!this._geometryBufferRenderer) {
  18417. return;
  18418. }
  18419. this._geometryBufferRenderer.dispose();
  18420. this._geometryBufferRenderer = null;
  18421. };
  18422. Scene.prototype.freezeMaterials = function () {
  18423. for (var i = 0; i < this.materials.length; i++) {
  18424. this.materials[i].freeze();
  18425. }
  18426. };
  18427. Scene.prototype.unfreezeMaterials = function () {
  18428. for (var i = 0; i < this.materials.length; i++) {
  18429. this.materials[i].unfreeze();
  18430. }
  18431. };
  18432. Scene.prototype.dispose = function () {
  18433. this.beforeRender = null;
  18434. this.afterRender = null;
  18435. this.skeletons = [];
  18436. this.morphTargetManagers = [];
  18437. this.importedMeshesFiles = new Array();
  18438. this.resetCachedMaterial();
  18439. if (this._depthRenderer) {
  18440. this._depthRenderer.dispose();
  18441. }
  18442. // Smart arrays
  18443. if (this.activeCamera) {
  18444. this.activeCamera._activeMeshes.dispose();
  18445. this.activeCamera = null;
  18446. }
  18447. this._activeMeshes.dispose();
  18448. this._renderingManager.dispose();
  18449. this._processedMaterials.dispose();
  18450. this._activeParticleSystems.dispose();
  18451. this._activeSkeletons.dispose();
  18452. this._softwareSkinnedMeshes.dispose();
  18453. if (this._boundingBoxRenderer) {
  18454. this._boundingBoxRenderer.dispose();
  18455. }
  18456. this._meshesForIntersections.dispose();
  18457. this._toBeDisposed.dispose();
  18458. // Debug layer
  18459. if (this._debugLayer) {
  18460. this._debugLayer.hide();
  18461. }
  18462. // Events
  18463. this.onDisposeObservable.notifyObservers(this);
  18464. this.onDisposeObservable.clear();
  18465. this.onBeforeRenderObservable.clear();
  18466. this.onAfterRenderObservable.clear();
  18467. this.detachControl();
  18468. // Release sounds & sounds tracks
  18469. if (BABYLON.AudioEngine) {
  18470. this.disposeSounds();
  18471. }
  18472. // Detach cameras
  18473. var canvas = this._engine.getRenderingCanvas();
  18474. var index;
  18475. for (index = 0; index < this.cameras.length; index++) {
  18476. this.cameras[index].detachControl(canvas);
  18477. }
  18478. // Release lights
  18479. while (this.lights.length) {
  18480. this.lights[0].dispose();
  18481. }
  18482. // Release meshes
  18483. while (this.meshes.length) {
  18484. this.meshes[0].dispose(true);
  18485. }
  18486. // Release cameras
  18487. while (this.cameras.length) {
  18488. this.cameras[0].dispose();
  18489. }
  18490. // Release materials
  18491. while (this.materials.length) {
  18492. this.materials[0].dispose();
  18493. }
  18494. // Release particles
  18495. while (this.particleSystems.length) {
  18496. this.particleSystems[0].dispose();
  18497. }
  18498. // Release sprites
  18499. while (this.spriteManagers.length) {
  18500. this.spriteManagers[0].dispose();
  18501. }
  18502. // Release layers
  18503. while (this.layers.length) {
  18504. this.layers[0].dispose();
  18505. }
  18506. while (this.highlightLayers.length) {
  18507. this.highlightLayers[0].dispose();
  18508. }
  18509. // Release textures
  18510. while (this.textures.length) {
  18511. this.textures[0].dispose();
  18512. }
  18513. // Release UBO
  18514. this._sceneUbo.dispose();
  18515. // Post-processes
  18516. this.postProcessManager.dispose();
  18517. // Physics
  18518. if (this._physicsEngine) {
  18519. this.disablePhysicsEngine();
  18520. }
  18521. // Remove from engine
  18522. index = this._engine.scenes.indexOf(this);
  18523. if (index > -1) {
  18524. this._engine.scenes.splice(index, 1);
  18525. }
  18526. this._engine.wipeCaches();
  18527. this._engine = null;
  18528. };
  18529. Object.defineProperty(Scene.prototype, "isDisposed", {
  18530. get: function () {
  18531. return !this._engine;
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. // Release sounds & sounds tracks
  18537. Scene.prototype.disposeSounds = function () {
  18538. this.mainSoundTrack.dispose();
  18539. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18540. this.soundTracks[scIndex].dispose();
  18541. }
  18542. };
  18543. // Octrees
  18544. Scene.prototype.getWorldExtends = function () {
  18545. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18546. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18547. for (var index = 0; index < this.meshes.length; index++) {
  18548. var mesh = this.meshes[index];
  18549. mesh.computeWorldMatrix(true);
  18550. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18551. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18552. BABYLON.Tools.CheckExtends(minBox, min, max);
  18553. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18554. }
  18555. return {
  18556. min: min,
  18557. max: max
  18558. };
  18559. };
  18560. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18561. if (maxCapacity === void 0) { maxCapacity = 64; }
  18562. if (maxDepth === void 0) { maxDepth = 2; }
  18563. if (!this._selectionOctree) {
  18564. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18565. }
  18566. var worldExtends = this.getWorldExtends();
  18567. // Update octree
  18568. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18569. return this._selectionOctree;
  18570. };
  18571. // Picking
  18572. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18573. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18574. var engine = this._engine;
  18575. if (!camera) {
  18576. if (!this.activeCamera)
  18577. throw new Error("Active camera not set");
  18578. camera = this.activeCamera;
  18579. }
  18580. var cameraViewport = camera.viewport;
  18581. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18582. // Moving coordinates to local viewport world
  18583. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18584. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18585. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18586. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18587. };
  18588. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18589. if (!BABYLON.PickingInfo) {
  18590. return null;
  18591. }
  18592. var engine = this._engine;
  18593. if (!camera) {
  18594. if (!this.activeCamera)
  18595. throw new Error("Active camera not set");
  18596. camera = this.activeCamera;
  18597. }
  18598. var cameraViewport = camera.viewport;
  18599. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18600. var identity = BABYLON.Matrix.Identity();
  18601. // Moving coordinates to local viewport world
  18602. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18603. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18604. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18605. };
  18606. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18607. if (!BABYLON.PickingInfo) {
  18608. return null;
  18609. }
  18610. var pickingInfo = null;
  18611. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18612. var mesh = this.meshes[meshIndex];
  18613. if (predicate) {
  18614. if (!predicate(mesh)) {
  18615. continue;
  18616. }
  18617. }
  18618. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18619. continue;
  18620. }
  18621. var world = mesh.getWorldMatrix();
  18622. var ray = rayFunction(world);
  18623. var result = mesh.intersects(ray, fastCheck);
  18624. if (!result || !result.hit)
  18625. continue;
  18626. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18627. continue;
  18628. pickingInfo = result;
  18629. if (fastCheck) {
  18630. break;
  18631. }
  18632. }
  18633. return pickingInfo || new BABYLON.PickingInfo();
  18634. };
  18635. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18636. if (!BABYLON.PickingInfo) {
  18637. return null;
  18638. }
  18639. var pickingInfos = new Array();
  18640. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18641. var mesh = this.meshes[meshIndex];
  18642. if (predicate) {
  18643. if (!predicate(mesh)) {
  18644. continue;
  18645. }
  18646. }
  18647. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18648. continue;
  18649. }
  18650. var world = mesh.getWorldMatrix();
  18651. var ray = rayFunction(world);
  18652. var result = mesh.intersects(ray, false);
  18653. if (!result || !result.hit)
  18654. continue;
  18655. pickingInfos.push(result);
  18656. }
  18657. return pickingInfos;
  18658. };
  18659. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18660. if (!BABYLON.PickingInfo) {
  18661. return null;
  18662. }
  18663. var pickingInfo = null;
  18664. camera = camera || this.activeCamera;
  18665. if (this.spriteManagers.length > 0) {
  18666. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18667. var spriteManager = this.spriteManagers[spriteIndex];
  18668. if (!spriteManager.isPickable) {
  18669. continue;
  18670. }
  18671. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18672. if (!result || !result.hit)
  18673. continue;
  18674. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18675. continue;
  18676. pickingInfo = result;
  18677. if (fastCheck) {
  18678. break;
  18679. }
  18680. }
  18681. }
  18682. return pickingInfo || new BABYLON.PickingInfo();
  18683. };
  18684. /** Launch a ray to try to pick a mesh in the scene
  18685. * @param x position on screen
  18686. * @param y position on screen
  18687. * @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
  18688. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18689. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18690. */
  18691. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18692. var _this = this;
  18693. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18694. };
  18695. /** Launch a ray to try to pick a sprite in the scene
  18696. * @param x position on screen
  18697. * @param y position on screen
  18698. * @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
  18699. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18700. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18701. */
  18702. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18703. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18704. };
  18705. /** Use the given ray to pick a mesh in the scene
  18706. * @param ray The ray to use to pick meshes
  18707. * @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
  18708. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  18709. */
  18710. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18711. var _this = this;
  18712. return this._internalPick(function (world) {
  18713. if (!_this._pickWithRayInverseMatrix) {
  18714. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18715. }
  18716. world.invertToRef(_this._pickWithRayInverseMatrix);
  18717. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18718. }, predicate, fastCheck);
  18719. };
  18720. /**
  18721. * Launch a ray to try to pick a mesh in the scene
  18722. * @param x X position on screen
  18723. * @param y Y position on screen
  18724. * @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
  18725. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  18726. */
  18727. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18728. var _this = this;
  18729. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18730. };
  18731. /**
  18732. * Launch a ray to try to pick a mesh in the scene
  18733. * @param ray Ray to use
  18734. * @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
  18735. */
  18736. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18737. var _this = this;
  18738. return this._internalMultiPick(function (world) {
  18739. if (!_this._pickWithRayInverseMatrix) {
  18740. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18741. }
  18742. world.invertToRef(_this._pickWithRayInverseMatrix);
  18743. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18744. }, predicate);
  18745. };
  18746. Scene.prototype.setPointerOverMesh = function (mesh) {
  18747. if (this._pointerOverMesh === mesh) {
  18748. return;
  18749. }
  18750. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18751. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18752. }
  18753. this._pointerOverMesh = mesh;
  18754. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18755. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18756. }
  18757. };
  18758. Scene.prototype.getPointerOverMesh = function () {
  18759. return this._pointerOverMesh;
  18760. };
  18761. Scene.prototype.setPointerOverSprite = function (sprite) {
  18762. if (this._pointerOverSprite === sprite) {
  18763. return;
  18764. }
  18765. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18766. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18767. }
  18768. this._pointerOverSprite = sprite;
  18769. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18770. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18771. }
  18772. };
  18773. Scene.prototype.getPointerOverSprite = function () {
  18774. return this._pointerOverSprite;
  18775. };
  18776. // Physics
  18777. Scene.prototype.getPhysicsEngine = function () {
  18778. return this._physicsEngine;
  18779. };
  18780. /**
  18781. * Enables physics to the current scene
  18782. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18783. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18784. * @return {boolean} was the physics engine initialized
  18785. */
  18786. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18787. if (this._physicsEngine) {
  18788. return true;
  18789. }
  18790. try {
  18791. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18792. return true;
  18793. }
  18794. catch (e) {
  18795. BABYLON.Tools.Error(e.message);
  18796. return false;
  18797. }
  18798. };
  18799. Scene.prototype.disablePhysicsEngine = function () {
  18800. if (!this._physicsEngine) {
  18801. return;
  18802. }
  18803. this._physicsEngine.dispose();
  18804. this._physicsEngine = undefined;
  18805. };
  18806. Scene.prototype.isPhysicsEnabled = function () {
  18807. return this._physicsEngine !== undefined;
  18808. };
  18809. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18810. var mesh = compound.parts[0].mesh;
  18811. mesh.physicsImpostor.dispose();
  18812. mesh.physicsImpostor = null;
  18813. };
  18814. // Misc.
  18815. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  18816. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18817. if (replace === void 0) { replace = false; }
  18818. if (attachCameraControls === void 0) { attachCameraControls = false; }
  18819. // Dispose existing camera or light in replace mode.
  18820. if (replace) {
  18821. if (this.activeCamera) {
  18822. this.activeCamera.dispose();
  18823. this.activeCamera = null;
  18824. }
  18825. if (this.lights) {
  18826. for (var i = 0; i < this.lights.length; i++) {
  18827. this.lights[i].dispose();
  18828. }
  18829. }
  18830. }
  18831. // Light
  18832. if (this.lights.length === 0) {
  18833. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18834. }
  18835. // Camera
  18836. if (!this.activeCamera) {
  18837. var worldExtends = this.getWorldExtends();
  18838. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18839. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18840. var camera;
  18841. var radius = worldSize.length() * 1.5;
  18842. if (createArcRotateCamera) {
  18843. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  18844. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18845. arcRotateCamera.wheelPrecision = 100 / radius;
  18846. camera = arcRotateCamera;
  18847. }
  18848. else {
  18849. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  18850. freeCamera.setTarget(worldCenter);
  18851. camera = freeCamera;
  18852. }
  18853. camera.minZ = radius * 0.01;
  18854. camera.maxZ = radius * 100;
  18855. camera.speed = radius * 0.2;
  18856. this.activeCamera = camera;
  18857. if (attachCameraControls) {
  18858. camera.attachControl(this.getEngine().getRenderingCanvas());
  18859. }
  18860. }
  18861. };
  18862. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  18863. if (pbr === void 0) { pbr = false; }
  18864. if (scale === void 0) { scale = 1000; }
  18865. if (blur === void 0) { blur = 0; }
  18866. if (environmentTexture) {
  18867. this.environmentTexture = environmentTexture;
  18868. }
  18869. if (!this.environmentTexture) {
  18870. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18871. return;
  18872. }
  18873. // Skybox
  18874. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  18875. if (pbr) {
  18876. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18877. hdrSkyboxMaterial.backFaceCulling = false;
  18878. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  18879. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18880. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  18881. hdrSkyboxMaterial.disableLighting = true;
  18882. hdrSkyboxMaterial.twoSidedLighting = true;
  18883. hdrSkybox.infiniteDistance = true;
  18884. hdrSkybox.material = hdrSkyboxMaterial;
  18885. }
  18886. else {
  18887. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18888. skyboxMaterial.backFaceCulling = false;
  18889. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  18890. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18891. skyboxMaterial.disableLighting = true;
  18892. hdrSkybox.infiniteDistance = true;
  18893. hdrSkybox.material = skyboxMaterial;
  18894. }
  18895. return hdrSkybox;
  18896. };
  18897. // Tags
  18898. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18899. if (tagsQuery === undefined) {
  18900. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18901. return list;
  18902. }
  18903. var listByTags = [];
  18904. forEach = forEach || (function (item) { return; });
  18905. for (var i in list) {
  18906. var item = list[i];
  18907. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18908. listByTags.push(item);
  18909. forEach(item);
  18910. }
  18911. }
  18912. return listByTags;
  18913. };
  18914. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18915. return this._getByTags(this.meshes, tagsQuery, forEach);
  18916. };
  18917. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18918. return this._getByTags(this.cameras, tagsQuery, forEach);
  18919. };
  18920. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18921. return this._getByTags(this.lights, tagsQuery, forEach);
  18922. };
  18923. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18924. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18925. };
  18926. /**
  18927. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18928. * This allowed control for front to back rendering or reversly depending of the special needs.
  18929. *
  18930. * @param renderingGroupId The rendering group id corresponding to its index
  18931. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18932. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18933. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18934. */
  18935. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18936. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18937. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18938. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18939. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18940. };
  18941. /**
  18942. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18943. *
  18944. * @param renderingGroupId The rendering group id corresponding to its index
  18945. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18946. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18947. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18948. */
  18949. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18950. if (depth === void 0) { depth = true; }
  18951. if (stencil === void 0) { stencil = true; }
  18952. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18953. };
  18954. /**
  18955. * Will flag all materials as dirty to trigger new shader compilation
  18956. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18957. */
  18958. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18959. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18960. var material = _a[_i];
  18961. if (predicate && !predicate(material)) {
  18962. continue;
  18963. }
  18964. material.markAsDirty(flag);
  18965. }
  18966. };
  18967. return Scene;
  18968. }());
  18969. // Statics
  18970. Scene._FOGMODE_NONE = 0;
  18971. Scene._FOGMODE_EXP = 1;
  18972. Scene._FOGMODE_EXP2 = 2;
  18973. Scene._FOGMODE_LINEAR = 3;
  18974. Scene.MinDeltaTime = 1.0;
  18975. Scene.MaxDeltaTime = 1000.0;
  18976. /** The distance in pixel that you have to move to prevent some events */
  18977. Scene.DragMovementThreshold = 10; // in pixels
  18978. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  18979. Scene.LongPressDelay = 500; // in milliseconds
  18980. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  18981. Scene.DoubleClickDelay = 300; // in milliseconds
  18982. /** If you need to check double click without raising a single click at first click, enable this flag */
  18983. Scene.ExclusiveDoubleClickMode = false;
  18984. BABYLON.Scene = Scene;
  18985. })(BABYLON || (BABYLON = {}));
  18986. //# sourceMappingURL=babylon.scene.js.map
  18987. var BABYLON;
  18988. (function (BABYLON) {
  18989. var Buffer = (function () {
  18990. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18991. if (engine instanceof BABYLON.Mesh) {
  18992. this._engine = engine.getScene().getEngine();
  18993. }
  18994. else {
  18995. this._engine = engine;
  18996. }
  18997. this._updatable = updatable;
  18998. this._data = data;
  18999. this._strideSize = stride;
  19000. if (!postponeInternalCreation) {
  19001. this.create();
  19002. }
  19003. this._instanced = instanced;
  19004. this._instanceDivisor = instanced ? 1 : 0;
  19005. }
  19006. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19007. // a lot of these parameters are ignored as they are overriden by the buffer
  19008. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19009. };
  19010. // Properties
  19011. Buffer.prototype.isUpdatable = function () {
  19012. return this._updatable;
  19013. };
  19014. Buffer.prototype.getData = function () {
  19015. return this._data;
  19016. };
  19017. Buffer.prototype.getBuffer = function () {
  19018. return this._buffer;
  19019. };
  19020. Buffer.prototype.getStrideSize = function () {
  19021. return this._strideSize;
  19022. };
  19023. Buffer.prototype.getIsInstanced = function () {
  19024. return this._instanced;
  19025. };
  19026. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19027. get: function () {
  19028. return this._instanceDivisor;
  19029. },
  19030. set: function (value) {
  19031. this._instanceDivisor = value;
  19032. if (value == 0) {
  19033. this._instanced = false;
  19034. }
  19035. else {
  19036. this._instanced = true;
  19037. }
  19038. },
  19039. enumerable: true,
  19040. configurable: true
  19041. });
  19042. // Methods
  19043. Buffer.prototype.create = function (data) {
  19044. if (!data && this._buffer) {
  19045. return; // nothing to do
  19046. }
  19047. data = data || this._data;
  19048. if (!this._buffer) {
  19049. if (this._updatable) {
  19050. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19051. this._data = data;
  19052. }
  19053. else {
  19054. this._buffer = this._engine.createVertexBuffer(data);
  19055. }
  19056. }
  19057. else if (this._updatable) {
  19058. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19059. this._data = data;
  19060. }
  19061. };
  19062. Buffer.prototype.update = function (data) {
  19063. this.create(data);
  19064. };
  19065. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19066. if (!this._buffer) {
  19067. return;
  19068. }
  19069. if (this._updatable) {
  19070. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19071. this._data = null;
  19072. }
  19073. };
  19074. Buffer.prototype.dispose = function () {
  19075. if (!this._buffer) {
  19076. return;
  19077. }
  19078. if (this._engine._releaseBuffer(this._buffer)) {
  19079. this._buffer = null;
  19080. }
  19081. };
  19082. return Buffer;
  19083. }());
  19084. BABYLON.Buffer = Buffer;
  19085. })(BABYLON || (BABYLON = {}));
  19086. //# sourceMappingURL=babylon.buffer.js.map
  19087. var BABYLON;
  19088. (function (BABYLON) {
  19089. var VertexBuffer = (function () {
  19090. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19091. if (!stride) {
  19092. // Deduce stride from kind
  19093. switch (kind) {
  19094. case VertexBuffer.PositionKind:
  19095. stride = 3;
  19096. break;
  19097. case VertexBuffer.NormalKind:
  19098. stride = 3;
  19099. break;
  19100. case VertexBuffer.UVKind:
  19101. case VertexBuffer.UV2Kind:
  19102. case VertexBuffer.UV3Kind:
  19103. case VertexBuffer.UV4Kind:
  19104. case VertexBuffer.UV5Kind:
  19105. case VertexBuffer.UV6Kind:
  19106. stride = 2;
  19107. break;
  19108. case VertexBuffer.TangentKind:
  19109. case VertexBuffer.ColorKind:
  19110. stride = 4;
  19111. break;
  19112. case VertexBuffer.MatricesIndicesKind:
  19113. case VertexBuffer.MatricesIndicesExtraKind:
  19114. stride = 4;
  19115. break;
  19116. case VertexBuffer.MatricesWeightsKind:
  19117. case VertexBuffer.MatricesWeightsExtraKind:
  19118. stride = 4;
  19119. break;
  19120. }
  19121. }
  19122. if (data instanceof BABYLON.Buffer) {
  19123. if (!stride) {
  19124. stride = data.getStrideSize();
  19125. }
  19126. this._buffer = data;
  19127. this._ownsBuffer = false;
  19128. }
  19129. else {
  19130. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19131. this._ownsBuffer = true;
  19132. }
  19133. this._stride = stride;
  19134. this._offset = offset ? offset : 0;
  19135. this._size = size ? size : stride;
  19136. this._kind = kind;
  19137. }
  19138. /**
  19139. * Returns the kind of the VertexBuffer (string).
  19140. */
  19141. VertexBuffer.prototype.getKind = function () {
  19142. return this._kind;
  19143. };
  19144. // Properties
  19145. /**
  19146. * Boolean : is the VertexBuffer updatable ?
  19147. */
  19148. VertexBuffer.prototype.isUpdatable = function () {
  19149. return this._buffer.isUpdatable();
  19150. };
  19151. /**
  19152. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19153. */
  19154. VertexBuffer.prototype.getData = function () {
  19155. return this._buffer.getData();
  19156. };
  19157. /**
  19158. * Returns the WebGLBuffer associated to the VertexBuffer.
  19159. */
  19160. VertexBuffer.prototype.getBuffer = function () {
  19161. return this._buffer.getBuffer();
  19162. };
  19163. /**
  19164. * Returns the stride of the VertexBuffer (integer).
  19165. */
  19166. VertexBuffer.prototype.getStrideSize = function () {
  19167. return this._stride;
  19168. };
  19169. /**
  19170. * Returns the offset (integer).
  19171. */
  19172. VertexBuffer.prototype.getOffset = function () {
  19173. return this._offset;
  19174. };
  19175. /**
  19176. * Returns the VertexBuffer total size (integer).
  19177. */
  19178. VertexBuffer.prototype.getSize = function () {
  19179. return this._size;
  19180. };
  19181. /**
  19182. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19183. */
  19184. VertexBuffer.prototype.getIsInstanced = function () {
  19185. return this._buffer.getIsInstanced();
  19186. };
  19187. /**
  19188. * Returns the instancing divisor, zero for non-instanced (integer).
  19189. */
  19190. VertexBuffer.prototype.getInstanceDivisor = function () {
  19191. return this._buffer.instanceDivisor;
  19192. };
  19193. // Methods
  19194. /**
  19195. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19196. * Returns the created WebGLBuffer.
  19197. */
  19198. VertexBuffer.prototype.create = function (data) {
  19199. return this._buffer.create(data);
  19200. };
  19201. /**
  19202. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19203. * Returns the updated WebGLBuffer.
  19204. */
  19205. VertexBuffer.prototype.update = function (data) {
  19206. return this._buffer.update(data);
  19207. };
  19208. /**
  19209. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19210. * Returns the directly updated WebGLBuffer.
  19211. */
  19212. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19213. return this._buffer.updateDirectly(data, offset);
  19214. };
  19215. /**
  19216. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19217. */
  19218. VertexBuffer.prototype.dispose = function () {
  19219. if (this._ownsBuffer) {
  19220. this._buffer.dispose();
  19221. }
  19222. };
  19223. Object.defineProperty(VertexBuffer, "PositionKind", {
  19224. get: function () {
  19225. return VertexBuffer._PositionKind;
  19226. },
  19227. enumerable: true,
  19228. configurable: true
  19229. });
  19230. Object.defineProperty(VertexBuffer, "NormalKind", {
  19231. get: function () {
  19232. return VertexBuffer._NormalKind;
  19233. },
  19234. enumerable: true,
  19235. configurable: true
  19236. });
  19237. Object.defineProperty(VertexBuffer, "TangentKind", {
  19238. get: function () {
  19239. return VertexBuffer._TangentKind;
  19240. },
  19241. enumerable: true,
  19242. configurable: true
  19243. });
  19244. Object.defineProperty(VertexBuffer, "UVKind", {
  19245. get: function () {
  19246. return VertexBuffer._UVKind;
  19247. },
  19248. enumerable: true,
  19249. configurable: true
  19250. });
  19251. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19252. get: function () {
  19253. return VertexBuffer._UV2Kind;
  19254. },
  19255. enumerable: true,
  19256. configurable: true
  19257. });
  19258. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19259. get: function () {
  19260. return VertexBuffer._UV3Kind;
  19261. },
  19262. enumerable: true,
  19263. configurable: true
  19264. });
  19265. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19266. get: function () {
  19267. return VertexBuffer._UV4Kind;
  19268. },
  19269. enumerable: true,
  19270. configurable: true
  19271. });
  19272. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19273. get: function () {
  19274. return VertexBuffer._UV5Kind;
  19275. },
  19276. enumerable: true,
  19277. configurable: true
  19278. });
  19279. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19280. get: function () {
  19281. return VertexBuffer._UV6Kind;
  19282. },
  19283. enumerable: true,
  19284. configurable: true
  19285. });
  19286. Object.defineProperty(VertexBuffer, "ColorKind", {
  19287. get: function () {
  19288. return VertexBuffer._ColorKind;
  19289. },
  19290. enumerable: true,
  19291. configurable: true
  19292. });
  19293. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19294. get: function () {
  19295. return VertexBuffer._MatricesIndicesKind;
  19296. },
  19297. enumerable: true,
  19298. configurable: true
  19299. });
  19300. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19301. get: function () {
  19302. return VertexBuffer._MatricesWeightsKind;
  19303. },
  19304. enumerable: true,
  19305. configurable: true
  19306. });
  19307. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19308. get: function () {
  19309. return VertexBuffer._MatricesIndicesExtraKind;
  19310. },
  19311. enumerable: true,
  19312. configurable: true
  19313. });
  19314. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19315. get: function () {
  19316. return VertexBuffer._MatricesWeightsExtraKind;
  19317. },
  19318. enumerable: true,
  19319. configurable: true
  19320. });
  19321. return VertexBuffer;
  19322. }());
  19323. // Enums
  19324. VertexBuffer._PositionKind = "position";
  19325. VertexBuffer._NormalKind = "normal";
  19326. VertexBuffer._TangentKind = "tangent";
  19327. VertexBuffer._UVKind = "uv";
  19328. VertexBuffer._UV2Kind = "uv2";
  19329. VertexBuffer._UV3Kind = "uv3";
  19330. VertexBuffer._UV4Kind = "uv4";
  19331. VertexBuffer._UV5Kind = "uv5";
  19332. VertexBuffer._UV6Kind = "uv6";
  19333. VertexBuffer._ColorKind = "color";
  19334. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19335. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19336. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19337. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19338. BABYLON.VertexBuffer = VertexBuffer;
  19339. })(BABYLON || (BABYLON = {}));
  19340. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19341. var BABYLON;
  19342. (function (BABYLON) {
  19343. var BaseTexture = (function () {
  19344. function BaseTexture(scene) {
  19345. this._hasAlpha = false;
  19346. this.getAlphaFromRGB = false;
  19347. this.level = 1;
  19348. this.coordinatesIndex = 0;
  19349. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  19350. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19351. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19352. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  19353. this.isCube = false;
  19354. this.gammaSpace = true;
  19355. this.invertZ = false;
  19356. this.lodLevelInAlpha = false;
  19357. this.lodGenerationOffset = 0.0;
  19358. this.lodGenerationScale = 0.8;
  19359. this.isRenderTarget = false;
  19360. this.animations = new Array();
  19361. /**
  19362. * An event triggered when the texture is disposed.
  19363. * @type {BABYLON.Observable}
  19364. */
  19365. this.onDisposeObservable = new BABYLON.Observable();
  19366. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19367. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  19368. this._scene.textures.push(this);
  19369. this._uid = null;
  19370. }
  19371. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  19372. get: function () {
  19373. return this._hasAlpha;
  19374. },
  19375. set: function (value) {
  19376. if (this._hasAlpha === value) {
  19377. return;
  19378. }
  19379. this._hasAlpha = value;
  19380. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19381. },
  19382. enumerable: true,
  19383. configurable: true
  19384. });
  19385. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  19386. get: function () {
  19387. return this._coordinatesMode;
  19388. },
  19389. set: function (value) {
  19390. if (this._coordinatesMode === value) {
  19391. return;
  19392. }
  19393. this._coordinatesMode = value;
  19394. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. Object.defineProperty(BaseTexture.prototype, "uid", {
  19400. get: function () {
  19401. if (!this._uid) {
  19402. this._uid = BABYLON.Tools.RandomId();
  19403. }
  19404. return this._uid;
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. BaseTexture.prototype.toString = function () {
  19410. return this.name;
  19411. };
  19412. BaseTexture.prototype.getClassName = function () {
  19413. return "BaseTexture";
  19414. };
  19415. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  19416. set: function (callback) {
  19417. if (this._onDisposeObserver) {
  19418. this.onDisposeObservable.remove(this._onDisposeObserver);
  19419. }
  19420. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19421. },
  19422. enumerable: true,
  19423. configurable: true
  19424. });
  19425. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  19426. get: function () {
  19427. return true;
  19428. },
  19429. enumerable: true,
  19430. configurable: true
  19431. });
  19432. BaseTexture.prototype.getScene = function () {
  19433. return this._scene;
  19434. };
  19435. BaseTexture.prototype.getTextureMatrix = function () {
  19436. return null;
  19437. };
  19438. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  19439. return null;
  19440. };
  19441. BaseTexture.prototype.getInternalTexture = function () {
  19442. return this._texture;
  19443. };
  19444. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  19445. return !this.isBlocking || this.isReady();
  19446. };
  19447. BaseTexture.prototype.isReady = function () {
  19448. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19449. this.delayLoad();
  19450. return false;
  19451. }
  19452. if (this._texture) {
  19453. return this._texture.isReady;
  19454. }
  19455. return false;
  19456. };
  19457. BaseTexture.prototype.getSize = function () {
  19458. if (this._texture._width) {
  19459. return new BABYLON.Size(this._texture._width, this._texture._height);
  19460. }
  19461. if (this._texture._size) {
  19462. return new BABYLON.Size(this._texture._size, this._texture._size);
  19463. }
  19464. return BABYLON.Size.Zero();
  19465. };
  19466. BaseTexture.prototype.getBaseSize = function () {
  19467. if (!this.isReady() || !this._texture)
  19468. return BABYLON.Size.Zero();
  19469. if (this._texture._size) {
  19470. return new BABYLON.Size(this._texture._size, this._texture._size);
  19471. }
  19472. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19473. };
  19474. BaseTexture.prototype.scale = function (ratio) {
  19475. };
  19476. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19477. get: function () {
  19478. return false;
  19479. },
  19480. enumerable: true,
  19481. configurable: true
  19482. });
  19483. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19484. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19485. for (var index = 0; index < texturesCache.length; index++) {
  19486. var texturesCacheEntry = texturesCache[index];
  19487. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19488. texturesCache.splice(index, 1);
  19489. return;
  19490. }
  19491. }
  19492. };
  19493. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19494. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19495. for (var index = 0; index < texturesCache.length; index++) {
  19496. var texturesCacheEntry = texturesCache[index];
  19497. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19498. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19499. texturesCacheEntry.references++;
  19500. return texturesCacheEntry;
  19501. }
  19502. }
  19503. }
  19504. return null;
  19505. };
  19506. BaseTexture.prototype.delayLoad = function () {
  19507. };
  19508. BaseTexture.prototype.clone = function () {
  19509. return null;
  19510. };
  19511. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19512. get: function () {
  19513. if (!this._texture) {
  19514. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19515. }
  19516. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19517. },
  19518. enumerable: true,
  19519. configurable: true
  19520. });
  19521. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  19522. get: function () {
  19523. if (!this._texture) {
  19524. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19525. }
  19526. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. BaseTexture.prototype.readPixels = function (faceIndex) {
  19532. if (faceIndex === void 0) { faceIndex = 0; }
  19533. if (!this._texture) {
  19534. return null;
  19535. }
  19536. var size = this.getSize();
  19537. var engine = this.getScene().getEngine();
  19538. if (this._texture.isCube) {
  19539. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19540. }
  19541. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  19542. };
  19543. BaseTexture.prototype.releaseInternalTexture = function () {
  19544. if (this._texture) {
  19545. this._scene.getEngine().releaseInternalTexture(this._texture);
  19546. delete this._texture;
  19547. }
  19548. };
  19549. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  19550. get: function () {
  19551. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  19552. return null;
  19553. }
  19554. if (!this._texture._sphericalPolynomial) {
  19555. this._texture._sphericalPolynomial =
  19556. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  19557. }
  19558. return this._texture._sphericalPolynomial;
  19559. },
  19560. set: function (value) {
  19561. if (this._texture) {
  19562. this._texture._sphericalPolynomial = value;
  19563. }
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  19569. get: function () {
  19570. if (this._texture) {
  19571. return this._texture._lodTextureHigh;
  19572. }
  19573. return null;
  19574. },
  19575. enumerable: true,
  19576. configurable: true
  19577. });
  19578. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  19579. get: function () {
  19580. if (this._texture) {
  19581. return this._texture._lodTextureMid;
  19582. }
  19583. return null;
  19584. },
  19585. enumerable: true,
  19586. configurable: true
  19587. });
  19588. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  19589. get: function () {
  19590. if (this._texture) {
  19591. return this._texture._lodTextureLow;
  19592. }
  19593. return null;
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. BaseTexture.prototype.dispose = function () {
  19599. // Animations
  19600. this.getScene().stopAnimation(this);
  19601. // Remove from scene
  19602. this._scene._removePendingData(this);
  19603. var index = this._scene.textures.indexOf(this);
  19604. if (index >= 0) {
  19605. this._scene.textures.splice(index, 1);
  19606. }
  19607. if (this._texture === undefined) {
  19608. return;
  19609. }
  19610. // Release
  19611. this.releaseInternalTexture();
  19612. // Callback
  19613. this.onDisposeObservable.notifyObservers(this);
  19614. this.onDisposeObservable.clear();
  19615. };
  19616. BaseTexture.prototype.serialize = function () {
  19617. if (!this.name) {
  19618. return null;
  19619. }
  19620. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19621. // Animations
  19622. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19623. return serializationObject;
  19624. };
  19625. BaseTexture.WhenAllReady = function (textures, callback) {
  19626. var numRemaining = textures.length;
  19627. if (numRemaining === 0) {
  19628. callback();
  19629. return;
  19630. }
  19631. var _loop_1 = function () {
  19632. texture = textures[i];
  19633. if (texture.isReady()) {
  19634. if (--numRemaining === 0) {
  19635. callback();
  19636. }
  19637. }
  19638. else {
  19639. onLoadObservable = texture.onLoadObservable;
  19640. var onLoadCallback_1 = function () {
  19641. onLoadObservable.removeCallback(onLoadCallback_1);
  19642. if (--numRemaining === 0) {
  19643. callback();
  19644. }
  19645. };
  19646. onLoadObservable.add(onLoadCallback_1);
  19647. }
  19648. };
  19649. var texture, onLoadObservable;
  19650. for (var i = 0; i < textures.length; i++) {
  19651. _loop_1();
  19652. }
  19653. };
  19654. return BaseTexture;
  19655. }());
  19656. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19657. __decorate([
  19658. BABYLON.serialize()
  19659. ], BaseTexture.prototype, "name", void 0);
  19660. __decorate([
  19661. BABYLON.serialize("hasAlpha")
  19662. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19663. __decorate([
  19664. BABYLON.serialize()
  19665. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19666. __decorate([
  19667. BABYLON.serialize()
  19668. ], BaseTexture.prototype, "level", void 0);
  19669. __decorate([
  19670. BABYLON.serialize()
  19671. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19672. __decorate([
  19673. BABYLON.serialize("coordinatesMode")
  19674. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19675. __decorate([
  19676. BABYLON.serialize()
  19677. ], BaseTexture.prototype, "wrapU", void 0);
  19678. __decorate([
  19679. BABYLON.serialize()
  19680. ], BaseTexture.prototype, "wrapV", void 0);
  19681. __decorate([
  19682. BABYLON.serialize()
  19683. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19684. __decorate([
  19685. BABYLON.serialize()
  19686. ], BaseTexture.prototype, "isCube", void 0);
  19687. __decorate([
  19688. BABYLON.serialize()
  19689. ], BaseTexture.prototype, "gammaSpace", void 0);
  19690. __decorate([
  19691. BABYLON.serialize()
  19692. ], BaseTexture.prototype, "invertZ", void 0);
  19693. __decorate([
  19694. BABYLON.serialize()
  19695. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  19696. __decorate([
  19697. BABYLON.serialize()
  19698. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  19699. __decorate([
  19700. BABYLON.serialize()
  19701. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  19702. __decorate([
  19703. BABYLON.serialize()
  19704. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19705. BABYLON.BaseTexture = BaseTexture;
  19706. })(BABYLON || (BABYLON = {}));
  19707. //# sourceMappingURL=babylon.baseTexture.js.map
  19708. var BABYLON;
  19709. (function (BABYLON) {
  19710. var Texture = (function (_super) {
  19711. __extends(Texture, _super);
  19712. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19713. if (noMipmap === void 0) { noMipmap = false; }
  19714. if (invertY === void 0) { invertY = true; }
  19715. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19716. if (onLoad === void 0) { onLoad = null; }
  19717. if (onError === void 0) { onError = null; }
  19718. if (buffer === void 0) { buffer = null; }
  19719. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19720. var _this = _super.call(this, scene) || this;
  19721. _this.uOffset = 0;
  19722. _this.vOffset = 0;
  19723. _this.uScale = 1.0;
  19724. _this.vScale = 1.0;
  19725. _this.uAng = 0;
  19726. _this.vAng = 0;
  19727. _this.wAng = 0;
  19728. _this._isBlocking = true;
  19729. _this.name = url;
  19730. _this.url = url;
  19731. _this._noMipmap = noMipmap;
  19732. _this._invertY = invertY;
  19733. _this._samplingMode = samplingMode;
  19734. _this._buffer = buffer;
  19735. _this._deleteBuffer = deleteBuffer;
  19736. _this._format = format;
  19737. scene = _this.getScene();
  19738. var load = function () {
  19739. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19740. _this.onLoadObservable.notifyObservers(_this);
  19741. }
  19742. if (onLoad) {
  19743. onLoad();
  19744. }
  19745. if (!_this.isBlocking) {
  19746. scene.resetCachedMaterial();
  19747. }
  19748. };
  19749. if (!url) {
  19750. _this._delayedOnLoad = load;
  19751. _this._delayedOnError = onError;
  19752. return _this;
  19753. }
  19754. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19755. if (!_this._texture) {
  19756. if (!scene.useDelayedTextureLoading) {
  19757. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19758. if (deleteBuffer) {
  19759. delete _this._buffer;
  19760. }
  19761. }
  19762. else {
  19763. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19764. _this._delayedOnLoad = load;
  19765. _this._delayedOnError = onError;
  19766. }
  19767. }
  19768. else {
  19769. if (_this._texture.isReady) {
  19770. BABYLON.Tools.SetImmediate(function () { return load(); });
  19771. }
  19772. else {
  19773. _this._texture.onLoadedCallbacks.push(load);
  19774. }
  19775. }
  19776. return _this;
  19777. }
  19778. Object.defineProperty(Texture.prototype, "noMipmap", {
  19779. get: function () {
  19780. return this._noMipmap;
  19781. },
  19782. enumerable: true,
  19783. configurable: true
  19784. });
  19785. Object.defineProperty(Texture.prototype, "isBlocking", {
  19786. get: function () {
  19787. return this._isBlocking;
  19788. },
  19789. set: function (value) {
  19790. this._isBlocking = value;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(Texture.prototype, "samplingMode", {
  19796. get: function () {
  19797. return this._samplingMode;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Texture.prototype.updateURL = function (url) {
  19803. this.url = url;
  19804. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19805. this.delayLoad();
  19806. };
  19807. Texture.prototype.delayLoad = function () {
  19808. var _this = this;
  19809. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19810. return;
  19811. }
  19812. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19813. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19814. if (!this._texture) {
  19815. 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);
  19816. if (this._deleteBuffer) {
  19817. delete this._buffer;
  19818. }
  19819. }
  19820. else {
  19821. if (this._texture.isReady) {
  19822. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19823. }
  19824. else {
  19825. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19826. }
  19827. }
  19828. };
  19829. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19830. if (!this._texture) {
  19831. return;
  19832. }
  19833. this._samplingMode = samplingMode;
  19834. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19835. };
  19836. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19837. x *= this.uScale;
  19838. y *= this.vScale;
  19839. x -= 0.5 * this.uScale;
  19840. y -= 0.5 * this.vScale;
  19841. z -= 0.5;
  19842. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19843. t.x += 0.5 * this.uScale + this.uOffset;
  19844. t.y += 0.5 * this.vScale + this.vOffset;
  19845. t.z += 0.5;
  19846. };
  19847. Texture.prototype.getTextureMatrix = function () {
  19848. var _this = this;
  19849. if (this.uOffset === this._cachedUOffset &&
  19850. this.vOffset === this._cachedVOffset &&
  19851. this.uScale === this._cachedUScale &&
  19852. this.vScale === this._cachedVScale &&
  19853. this.uAng === this._cachedUAng &&
  19854. this.vAng === this._cachedVAng &&
  19855. this.wAng === this._cachedWAng) {
  19856. return this._cachedTextureMatrix;
  19857. }
  19858. this._cachedUOffset = this.uOffset;
  19859. this._cachedVOffset = this.vOffset;
  19860. this._cachedUScale = this.uScale;
  19861. this._cachedVScale = this.vScale;
  19862. this._cachedUAng = this.uAng;
  19863. this._cachedVAng = this.vAng;
  19864. this._cachedWAng = this.wAng;
  19865. if (!this._cachedTextureMatrix) {
  19866. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19867. this._rowGenerationMatrix = new BABYLON.Matrix();
  19868. this._t0 = BABYLON.Vector3.Zero();
  19869. this._t1 = BABYLON.Vector3.Zero();
  19870. this._t2 = BABYLON.Vector3.Zero();
  19871. }
  19872. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19873. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19874. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19875. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19876. this._t1.subtractInPlace(this._t0);
  19877. this._t2.subtractInPlace(this._t0);
  19878. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19879. this._cachedTextureMatrix.m[0] = this._t1.x;
  19880. this._cachedTextureMatrix.m[1] = this._t1.y;
  19881. this._cachedTextureMatrix.m[2] = this._t1.z;
  19882. this._cachedTextureMatrix.m[4] = this._t2.x;
  19883. this._cachedTextureMatrix.m[5] = this._t2.y;
  19884. this._cachedTextureMatrix.m[6] = this._t2.z;
  19885. this._cachedTextureMatrix.m[8] = this._t0.x;
  19886. this._cachedTextureMatrix.m[9] = this._t0.y;
  19887. this._cachedTextureMatrix.m[10] = this._t0.z;
  19888. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  19889. return mat.hasTexture(_this);
  19890. });
  19891. return this._cachedTextureMatrix;
  19892. };
  19893. Texture.prototype.getReflectionTextureMatrix = function () {
  19894. var _this = this;
  19895. if (this.uOffset === this._cachedUOffset &&
  19896. this.vOffset === this._cachedVOffset &&
  19897. this.uScale === this._cachedUScale &&
  19898. this.vScale === this._cachedVScale &&
  19899. this.coordinatesMode === this._cachedCoordinatesMode) {
  19900. return this._cachedTextureMatrix;
  19901. }
  19902. if (!this._cachedTextureMatrix) {
  19903. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19904. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19905. }
  19906. this._cachedUOffset = this.uOffset;
  19907. this._cachedVOffset = this.vOffset;
  19908. this._cachedUScale = this.uScale;
  19909. this._cachedVScale = this.vScale;
  19910. this._cachedCoordinatesMode = this.coordinatesMode;
  19911. switch (this.coordinatesMode) {
  19912. case Texture.PLANAR_MODE:
  19913. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19914. this._cachedTextureMatrix[0] = this.uScale;
  19915. this._cachedTextureMatrix[5] = this.vScale;
  19916. this._cachedTextureMatrix[12] = this.uOffset;
  19917. this._cachedTextureMatrix[13] = this.vOffset;
  19918. break;
  19919. case Texture.PROJECTION_MODE:
  19920. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19921. this._projectionModeMatrix.m[0] = 0.5;
  19922. this._projectionModeMatrix.m[5] = -0.5;
  19923. this._projectionModeMatrix.m[10] = 0.0;
  19924. this._projectionModeMatrix.m[12] = 0.5;
  19925. this._projectionModeMatrix.m[13] = 0.5;
  19926. this._projectionModeMatrix.m[14] = 1.0;
  19927. this._projectionModeMatrix.m[15] = 1.0;
  19928. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19929. break;
  19930. default:
  19931. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19932. break;
  19933. }
  19934. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  19935. return (mat.getActiveTextures().indexOf(_this) !== -1);
  19936. });
  19937. return this._cachedTextureMatrix;
  19938. };
  19939. Texture.prototype.clone = function () {
  19940. var _this = this;
  19941. return BABYLON.SerializationHelper.Clone(function () {
  19942. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19943. }, this);
  19944. };
  19945. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19946. get: function () {
  19947. if (!this._onLoadObservable) {
  19948. this._onLoadObservable = new BABYLON.Observable();
  19949. }
  19950. return this._onLoadObservable;
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Texture.prototype.serialize = function () {
  19956. var serializationObject = _super.prototype.serialize.call(this);
  19957. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  19958. serializationObject.base64String = this._buffer;
  19959. serializationObject.name = serializationObject.name.replace("data:", "");
  19960. }
  19961. return serializationObject;
  19962. };
  19963. Texture.prototype.getClassName = function () {
  19964. return "Texture";
  19965. };
  19966. // Statics
  19967. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19968. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19969. if (onLoad === void 0) { onLoad = null; }
  19970. if (onError === void 0) { onError = null; }
  19971. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19972. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19973. };
  19974. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19975. if (parsedTexture.customType) {
  19976. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19977. // Update Sampling Mode
  19978. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19979. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19980. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19981. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19982. }
  19983. }
  19984. return parsedCustomTexture;
  19985. }
  19986. if (parsedTexture.isCube) {
  19987. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19988. }
  19989. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19990. return null;
  19991. }
  19992. var texture = BABYLON.SerializationHelper.Parse(function () {
  19993. if (parsedTexture.mirrorPlane) {
  19994. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19995. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19996. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19997. return mirrorTexture;
  19998. }
  19999. else if (parsedTexture.isRenderTarget) {
  20000. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20001. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20002. return renderTargetTexture;
  20003. }
  20004. else {
  20005. var texture;
  20006. if (parsedTexture.base64String) {
  20007. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20008. }
  20009. else {
  20010. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20011. }
  20012. return texture;
  20013. }
  20014. }, parsedTexture, scene);
  20015. // Update Sampling Mode
  20016. if (parsedTexture.samplingMode) {
  20017. var sampling = parsedTexture.samplingMode;
  20018. if (texture._samplingMode !== sampling) {
  20019. texture.updateSamplingMode(sampling);
  20020. }
  20021. }
  20022. // Animations
  20023. if (parsedTexture.animations) {
  20024. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20025. var parsedAnimation = parsedTexture.animations[animationIndex];
  20026. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20027. }
  20028. }
  20029. return texture;
  20030. };
  20031. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20032. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20033. if (noMipmap === void 0) { noMipmap = false; }
  20034. if (invertY === void 0) { invertY = true; }
  20035. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20036. if (onLoad === void 0) { onLoad = null; }
  20037. if (onError === void 0) { onError = null; }
  20038. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20039. if (name.substr(0, 5) !== "data:") {
  20040. name = "data:" + name;
  20041. }
  20042. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20043. };
  20044. return Texture;
  20045. }(BABYLON.BaseTexture));
  20046. // Constants
  20047. Texture.NEAREST_SAMPLINGMODE = 1;
  20048. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20049. Texture.BILINEAR_SAMPLINGMODE = 2;
  20050. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20051. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20052. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20053. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20054. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20055. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20056. Texture.NEAREST_LINEAR = 7;
  20057. Texture.NEAREST_NEAREST = 8;
  20058. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20059. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20060. Texture.LINEAR_LINEAR = 11;
  20061. Texture.LINEAR_NEAREST = 12;
  20062. Texture.EXPLICIT_MODE = 0;
  20063. Texture.SPHERICAL_MODE = 1;
  20064. Texture.PLANAR_MODE = 2;
  20065. Texture.CUBIC_MODE = 3;
  20066. Texture.PROJECTION_MODE = 4;
  20067. Texture.SKYBOX_MODE = 5;
  20068. Texture.INVCUBIC_MODE = 6;
  20069. Texture.EQUIRECTANGULAR_MODE = 7;
  20070. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20071. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20072. Texture.CLAMP_ADDRESSMODE = 0;
  20073. Texture.WRAP_ADDRESSMODE = 1;
  20074. Texture.MIRROR_ADDRESSMODE = 2;
  20075. __decorate([
  20076. BABYLON.serialize()
  20077. ], Texture.prototype, "url", void 0);
  20078. __decorate([
  20079. BABYLON.serialize()
  20080. ], Texture.prototype, "uOffset", void 0);
  20081. __decorate([
  20082. BABYLON.serialize()
  20083. ], Texture.prototype, "vOffset", void 0);
  20084. __decorate([
  20085. BABYLON.serialize()
  20086. ], Texture.prototype, "uScale", void 0);
  20087. __decorate([
  20088. BABYLON.serialize()
  20089. ], Texture.prototype, "vScale", void 0);
  20090. __decorate([
  20091. BABYLON.serialize()
  20092. ], Texture.prototype, "uAng", void 0);
  20093. __decorate([
  20094. BABYLON.serialize()
  20095. ], Texture.prototype, "vAng", void 0);
  20096. __decorate([
  20097. BABYLON.serialize()
  20098. ], Texture.prototype, "wAng", void 0);
  20099. __decorate([
  20100. BABYLON.serialize()
  20101. ], Texture.prototype, "isBlocking", null);
  20102. BABYLON.Texture = Texture;
  20103. })(BABYLON || (BABYLON = {}));
  20104. //# sourceMappingURL=babylon.texture.js.map
  20105. var BABYLON;
  20106. (function (BABYLON) {
  20107. var _InstancesBatch = (function () {
  20108. function _InstancesBatch() {
  20109. this.mustReturn = false;
  20110. this.visibleInstances = new Array();
  20111. this.renderSelf = new Array();
  20112. }
  20113. return _InstancesBatch;
  20114. }());
  20115. BABYLON._InstancesBatch = _InstancesBatch;
  20116. var Mesh = (function (_super) {
  20117. __extends(Mesh, _super);
  20118. /**
  20119. * @constructor
  20120. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20121. * @param {Scene} scene The scene to add this mesh to.
  20122. * @param {Node} parent The parent of this mesh, if it has one
  20123. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20124. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20125. * When false, achieved by calling a clone(), also passing False.
  20126. * This will make creation of children, recursive.
  20127. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20128. */
  20129. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20130. if (parent === void 0) { parent = null; }
  20131. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20132. var _this = _super.call(this, name, scene) || this;
  20133. // Events
  20134. /**
  20135. * An event triggered before rendering the mesh
  20136. * @type {BABYLON.Observable}
  20137. */
  20138. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20139. /**
  20140. * An event triggered after rendering the mesh
  20141. * @type {BABYLON.Observable}
  20142. */
  20143. _this.onAfterRenderObservable = new BABYLON.Observable();
  20144. /**
  20145. * An event triggered before drawing the mesh
  20146. * @type {BABYLON.Observable}
  20147. */
  20148. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20149. // Members
  20150. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20151. _this.instances = new Array();
  20152. _this._LODLevels = new Array();
  20153. _this._visibleInstances = {};
  20154. _this._renderIdForInstances = new Array();
  20155. _this._batchCache = new _InstancesBatch();
  20156. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20157. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20158. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20159. // Will be used to save a source mesh reference, If any
  20160. _this._source = null;
  20161. if (source) {
  20162. // Source mesh
  20163. _this._source = source;
  20164. // Geometry
  20165. if (source._geometry) {
  20166. source._geometry.applyToMesh(_this);
  20167. }
  20168. // Deep copy
  20169. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20170. // Parent
  20171. _this.parent = source.parent;
  20172. // Pivot
  20173. _this.setPivotMatrix(source.getPivotMatrix());
  20174. _this.id = name + "." + source.id;
  20175. // Material
  20176. _this.material = source.material;
  20177. var index;
  20178. if (!doNotCloneChildren) {
  20179. // Children
  20180. for (index = 0; index < scene.meshes.length; index++) {
  20181. var mesh = scene.meshes[index];
  20182. if (mesh.parent === source) {
  20183. // doNotCloneChildren is always going to be False
  20184. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20185. }
  20186. }
  20187. }
  20188. // Physics clone
  20189. var physicsEngine = _this.getScene().getPhysicsEngine();
  20190. if (clonePhysicsImpostor && physicsEngine) {
  20191. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20192. if (impostor) {
  20193. _this.physicsImpostor = impostor.clone(_this);
  20194. }
  20195. }
  20196. // Particles
  20197. for (index = 0; index < scene.particleSystems.length; index++) {
  20198. var system = scene.particleSystems[index];
  20199. if (system.emitter === source) {
  20200. system.clone(system.name, _this);
  20201. }
  20202. }
  20203. _this.computeWorldMatrix(true);
  20204. }
  20205. // Parent
  20206. if (parent !== null) {
  20207. _this.parent = parent;
  20208. }
  20209. return _this;
  20210. }
  20211. Object.defineProperty(Mesh, "FRONTSIDE", {
  20212. /**
  20213. * Mesh side orientation : usually the external or front surface
  20214. */
  20215. get: function () {
  20216. return Mesh._FRONTSIDE;
  20217. },
  20218. enumerable: true,
  20219. configurable: true
  20220. });
  20221. Object.defineProperty(Mesh, "BACKSIDE", {
  20222. /**
  20223. * Mesh side orientation : usually the internal or back surface
  20224. */
  20225. get: function () {
  20226. return Mesh._BACKSIDE;
  20227. },
  20228. enumerable: true,
  20229. configurable: true
  20230. });
  20231. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20232. /**
  20233. * Mesh side orientation : both internal and external or front and back surfaces
  20234. */
  20235. get: function () {
  20236. return Mesh._DOUBLESIDE;
  20237. },
  20238. enumerable: true,
  20239. configurable: true
  20240. });
  20241. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20242. /**
  20243. * Mesh side orientation : by default, `FRONTSIDE`
  20244. */
  20245. get: function () {
  20246. return Mesh._DEFAULTSIDE;
  20247. },
  20248. enumerable: true,
  20249. configurable: true
  20250. });
  20251. Object.defineProperty(Mesh, "NO_CAP", {
  20252. /**
  20253. * Mesh cap setting : no cap
  20254. */
  20255. get: function () {
  20256. return Mesh._NO_CAP;
  20257. },
  20258. enumerable: true,
  20259. configurable: true
  20260. });
  20261. Object.defineProperty(Mesh, "CAP_START", {
  20262. /**
  20263. * Mesh cap setting : one cap at the beginning of the mesh
  20264. */
  20265. get: function () {
  20266. return Mesh._CAP_START;
  20267. },
  20268. enumerable: true,
  20269. configurable: true
  20270. });
  20271. Object.defineProperty(Mesh, "CAP_END", {
  20272. /**
  20273. * Mesh cap setting : one cap at the end of the mesh
  20274. */
  20275. get: function () {
  20276. return Mesh._CAP_END;
  20277. },
  20278. enumerable: true,
  20279. configurable: true
  20280. });
  20281. Object.defineProperty(Mesh, "CAP_ALL", {
  20282. /**
  20283. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20284. */
  20285. get: function () {
  20286. return Mesh._CAP_ALL;
  20287. },
  20288. enumerable: true,
  20289. configurable: true
  20290. });
  20291. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20292. set: function (callback) {
  20293. if (this._onBeforeDrawObserver) {
  20294. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20295. }
  20296. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  20302. get: function () {
  20303. return this._morphTargetManager;
  20304. },
  20305. set: function (value) {
  20306. if (this._morphTargetManager === value) {
  20307. return;
  20308. }
  20309. this._morphTargetManager = value;
  20310. this._syncGeometryWithMorphTargetManager();
  20311. },
  20312. enumerable: true,
  20313. configurable: true
  20314. });
  20315. Object.defineProperty(Mesh.prototype, "source", {
  20316. get: function () {
  20317. return this._source;
  20318. },
  20319. enumerable: true,
  20320. configurable: true
  20321. });
  20322. // Methods
  20323. /**
  20324. * Returns the string "Mesh".
  20325. */
  20326. Mesh.prototype.getClassName = function () {
  20327. return "Mesh";
  20328. };
  20329. /**
  20330. * Returns a string.
  20331. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20332. */
  20333. Mesh.prototype.toString = function (fullDetails) {
  20334. var ret = _super.prototype.toString.call(this, fullDetails);
  20335. ret += ", n vertices: " + this.getTotalVertices();
  20336. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20337. if (this.animations) {
  20338. for (var i = 0; i < this.animations.length; i++) {
  20339. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20340. }
  20341. }
  20342. if (fullDetails) {
  20343. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20344. }
  20345. return ret;
  20346. };
  20347. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20348. /**
  20349. * True if the mesh has some Levels Of Details (LOD).
  20350. * Returns a boolean.
  20351. */
  20352. get: function () {
  20353. return this._LODLevels.length > 0;
  20354. },
  20355. enumerable: true,
  20356. configurable: true
  20357. });
  20358. Mesh.prototype._sortLODLevels = function () {
  20359. this._LODLevels.sort(function (a, b) {
  20360. if (a.distance < b.distance) {
  20361. return 1;
  20362. }
  20363. if (a.distance > b.distance) {
  20364. return -1;
  20365. }
  20366. return 0;
  20367. });
  20368. };
  20369. /**
  20370. * Add a mesh as LOD level triggered at the given distance.
  20371. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20372. * @param {number} distance The distance from the center of the object to show this level
  20373. * @param {Mesh} mesh The mesh to be added as LOD level
  20374. * @return {Mesh} This mesh (for chaining)
  20375. */
  20376. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20377. if (mesh && mesh._masterMesh) {
  20378. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20379. return this;
  20380. }
  20381. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20382. this._LODLevels.push(level);
  20383. if (mesh) {
  20384. mesh._masterMesh = this;
  20385. }
  20386. this._sortLODLevels();
  20387. return this;
  20388. };
  20389. /**
  20390. * Returns the LOD level mesh at the passed distance or null if not found.
  20391. * It is related to the method `addLODLevel(distance, mesh)`.
  20392. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20393. * Returns an object Mesh or `null`.
  20394. */
  20395. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20396. for (var index = 0; index < this._LODLevels.length; index++) {
  20397. var level = this._LODLevels[index];
  20398. if (level.distance === distance) {
  20399. return level.mesh;
  20400. }
  20401. }
  20402. return null;
  20403. };
  20404. /**
  20405. * Remove a mesh from the LOD array
  20406. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20407. * @param {Mesh} mesh The mesh to be removed.
  20408. * @return {Mesh} This mesh (for chaining)
  20409. */
  20410. Mesh.prototype.removeLODLevel = function (mesh) {
  20411. for (var index = 0; index < this._LODLevels.length; index++) {
  20412. if (this._LODLevels[index].mesh === mesh) {
  20413. this._LODLevels.splice(index, 1);
  20414. if (mesh) {
  20415. mesh._masterMesh = null;
  20416. }
  20417. }
  20418. }
  20419. this._sortLODLevels();
  20420. return this;
  20421. };
  20422. /**
  20423. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20424. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20425. */
  20426. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20427. if (!this._LODLevels || this._LODLevels.length === 0) {
  20428. return this;
  20429. }
  20430. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20431. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20432. if (this.onLODLevelSelection) {
  20433. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20434. }
  20435. return this;
  20436. }
  20437. for (var index = 0; index < this._LODLevels.length; index++) {
  20438. var level = this._LODLevels[index];
  20439. if (level.distance < distanceToCamera) {
  20440. if (level.mesh) {
  20441. level.mesh._preActivate();
  20442. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20443. }
  20444. if (this.onLODLevelSelection) {
  20445. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20446. }
  20447. return level.mesh;
  20448. }
  20449. }
  20450. if (this.onLODLevelSelection) {
  20451. this.onLODLevelSelection(distanceToCamera, this, this);
  20452. }
  20453. return this;
  20454. };
  20455. Object.defineProperty(Mesh.prototype, "geometry", {
  20456. /**
  20457. * Returns the mesh internal Geometry object.
  20458. */
  20459. get: function () {
  20460. return this._geometry;
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. /**
  20466. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20467. */
  20468. Mesh.prototype.getTotalVertices = function () {
  20469. if (!this._geometry) {
  20470. return 0;
  20471. }
  20472. return this._geometry.getTotalVertices();
  20473. };
  20474. /**
  20475. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20476. * 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.
  20477. * You can force the copy with forceCopy === true
  20478. * Returns null if the mesh has no geometry or no vertex buffer.
  20479. * Possible `kind` values :
  20480. * - BABYLON.VertexBuffer.PositionKind
  20481. * - BABYLON.VertexBuffer.UVKind
  20482. * - BABYLON.VertexBuffer.UV2Kind
  20483. * - BABYLON.VertexBuffer.UV3Kind
  20484. * - BABYLON.VertexBuffer.UV4Kind
  20485. * - BABYLON.VertexBuffer.UV5Kind
  20486. * - BABYLON.VertexBuffer.UV6Kind
  20487. * - BABYLON.VertexBuffer.ColorKind
  20488. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20489. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20490. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20491. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20492. */
  20493. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  20494. if (!this._geometry) {
  20495. return null;
  20496. }
  20497. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  20498. };
  20499. /**
  20500. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20501. * Returns `undefined` if the mesh has no geometry.
  20502. * Possible `kind` values :
  20503. * - BABYLON.VertexBuffer.PositionKind
  20504. * - BABYLON.VertexBuffer.UVKind
  20505. * - BABYLON.VertexBuffer.UV2Kind
  20506. * - BABYLON.VertexBuffer.UV3Kind
  20507. * - BABYLON.VertexBuffer.UV4Kind
  20508. * - BABYLON.VertexBuffer.UV5Kind
  20509. * - BABYLON.VertexBuffer.UV6Kind
  20510. * - BABYLON.VertexBuffer.ColorKind
  20511. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20512. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20513. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20514. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20515. */
  20516. Mesh.prototype.getVertexBuffer = function (kind) {
  20517. if (!this._geometry) {
  20518. return undefined;
  20519. }
  20520. return this._geometry.getVertexBuffer(kind);
  20521. };
  20522. /**
  20523. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20524. * Possible `kind` values :
  20525. * - BABYLON.VertexBuffer.PositionKind
  20526. * - BABYLON.VertexBuffer.UVKind
  20527. * - BABYLON.VertexBuffer.UV2Kind
  20528. * - BABYLON.VertexBuffer.UV3Kind
  20529. * - BABYLON.VertexBuffer.UV4Kind
  20530. * - BABYLON.VertexBuffer.UV5Kind
  20531. * - BABYLON.VertexBuffer.UV6Kind
  20532. * - BABYLON.VertexBuffer.ColorKind
  20533. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20534. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20535. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20536. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20537. */
  20538. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20539. if (!this._geometry) {
  20540. if (this._delayInfo) {
  20541. return this._delayInfo.indexOf(kind) !== -1;
  20542. }
  20543. return false;
  20544. }
  20545. return this._geometry.isVerticesDataPresent(kind);
  20546. };
  20547. /**
  20548. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20549. * Possible `kind` values :
  20550. * - BABYLON.VertexBuffer.PositionKind
  20551. * - BABYLON.VertexBuffer.UVKind
  20552. * - BABYLON.VertexBuffer.UV2Kind
  20553. * - BABYLON.VertexBuffer.UV3Kind
  20554. * - BABYLON.VertexBuffer.UV4Kind
  20555. * - BABYLON.VertexBuffer.UV5Kind
  20556. * - BABYLON.VertexBuffer.UV6Kind
  20557. * - BABYLON.VertexBuffer.ColorKind
  20558. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20559. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20560. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20561. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20562. */
  20563. Mesh.prototype.getVerticesDataKinds = function () {
  20564. if (!this._geometry) {
  20565. var result = [];
  20566. if (this._delayInfo) {
  20567. this._delayInfo.forEach(function (kind, index, array) {
  20568. result.push(kind);
  20569. });
  20570. }
  20571. return result;
  20572. }
  20573. return this._geometry.getVerticesDataKinds();
  20574. };
  20575. /**
  20576. * Returns a positive integer : the total number of indices in this mesh geometry.
  20577. * Returns zero if the mesh has no geometry.
  20578. */
  20579. Mesh.prototype.getTotalIndices = function () {
  20580. if (!this._geometry) {
  20581. return 0;
  20582. }
  20583. return this._geometry.getTotalIndices();
  20584. };
  20585. /**
  20586. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20587. * 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.
  20588. * Returns an empty array if the mesh has no geometry.
  20589. */
  20590. Mesh.prototype.getIndices = function (copyWhenShared) {
  20591. if (!this._geometry) {
  20592. return [];
  20593. }
  20594. return this._geometry.getIndices(copyWhenShared);
  20595. };
  20596. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20597. get: function () {
  20598. return this._masterMesh !== null && this._masterMesh !== undefined;
  20599. },
  20600. enumerable: true,
  20601. configurable: true
  20602. });
  20603. /**
  20604. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20605. */
  20606. Mesh.prototype.isReady = function () {
  20607. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20608. return false;
  20609. }
  20610. return _super.prototype.isReady.call(this);
  20611. };
  20612. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20613. get: function () {
  20614. return this._sideOrientation;
  20615. },
  20616. /**
  20617. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20618. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20619. */
  20620. set: function (sideO) {
  20621. this._sideOrientation = sideO;
  20622. },
  20623. enumerable: true,
  20624. configurable: true
  20625. });
  20626. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20627. /**
  20628. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20629. * This property is pertinent only for updatable parametric shapes.
  20630. */
  20631. get: function () {
  20632. return this._areNormalsFrozen;
  20633. },
  20634. enumerable: true,
  20635. configurable: true
  20636. });
  20637. /**
  20638. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20639. * It has no effect at all on other shapes.
  20640. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20641. * Returns the Mesh.
  20642. */
  20643. Mesh.prototype.freezeNormals = function () {
  20644. this._areNormalsFrozen = true;
  20645. return this;
  20646. };
  20647. /**
  20648. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20649. * It has no effect at all on other shapes.
  20650. * It reactivates the mesh normals computation if it was previously frozen.
  20651. * Returns the Mesh.
  20652. */
  20653. Mesh.prototype.unfreezeNormals = function () {
  20654. this._areNormalsFrozen = false;
  20655. return this;
  20656. };
  20657. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20658. /**
  20659. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20660. */
  20661. set: function (count) {
  20662. this._overridenInstanceCount = count;
  20663. },
  20664. enumerable: true,
  20665. configurable: true
  20666. });
  20667. // Methods
  20668. Mesh.prototype._preActivate = function () {
  20669. var sceneRenderId = this.getScene().getRenderId();
  20670. if (this._preActivateId === sceneRenderId) {
  20671. return this;
  20672. }
  20673. this._preActivateId = sceneRenderId;
  20674. this._visibleInstances = null;
  20675. return this;
  20676. };
  20677. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20678. if (this._visibleInstances) {
  20679. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20680. }
  20681. return this;
  20682. };
  20683. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20684. if (!this._visibleInstances) {
  20685. this._visibleInstances = {};
  20686. this._visibleInstances.defaultRenderId = renderId;
  20687. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20688. }
  20689. if (!this._visibleInstances[renderId]) {
  20690. this._visibleInstances[renderId] = new Array();
  20691. }
  20692. this._visibleInstances[renderId].push(instance);
  20693. return this;
  20694. };
  20695. /**
  20696. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20697. * This means the mesh underlying bounding box and sphere are recomputed.
  20698. * Returns the Mesh.
  20699. */
  20700. Mesh.prototype.refreshBoundingInfo = function () {
  20701. if (this._boundingInfo.isLocked) {
  20702. return;
  20703. }
  20704. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20705. if (data) {
  20706. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20707. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20708. }
  20709. if (this.subMeshes) {
  20710. for (var index = 0; index < this.subMeshes.length; index++) {
  20711. this.subMeshes[index].refreshBoundingInfo();
  20712. }
  20713. }
  20714. this._updateBoundingInfo();
  20715. return this;
  20716. };
  20717. Mesh.prototype._createGlobalSubMesh = function (force) {
  20718. var totalVertices = this.getTotalVertices();
  20719. if (!totalVertices || !this.getIndices()) {
  20720. return null;
  20721. }
  20722. // Check if we need to recreate the submeshes
  20723. if (this.subMeshes && this.subMeshes.length > 0) {
  20724. var totalIndices = this.getIndices().length;
  20725. var needToRecreate = false;
  20726. if (force) {
  20727. needToRecreate = true;
  20728. }
  20729. else {
  20730. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20731. var submesh = _a[_i];
  20732. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  20733. needToRecreate = true;
  20734. break;
  20735. }
  20736. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  20737. needToRecreate = true;
  20738. break;
  20739. }
  20740. }
  20741. }
  20742. if (!needToRecreate) {
  20743. return;
  20744. }
  20745. }
  20746. this.releaseSubMeshes();
  20747. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20748. };
  20749. Mesh.prototype.subdivide = function (count) {
  20750. if (count < 1) {
  20751. return;
  20752. }
  20753. var totalIndices = this.getTotalIndices();
  20754. var subdivisionSize = (totalIndices / count) | 0;
  20755. var offset = 0;
  20756. // Ensure that subdivisionSize is a multiple of 3
  20757. while (subdivisionSize % 3 !== 0) {
  20758. subdivisionSize++;
  20759. }
  20760. this.releaseSubMeshes();
  20761. for (var index = 0; index < count; index++) {
  20762. if (offset >= totalIndices) {
  20763. break;
  20764. }
  20765. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20766. offset += subdivisionSize;
  20767. }
  20768. this.synchronizeInstances();
  20769. };
  20770. /**
  20771. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20772. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20773. * The `data` are either a numeric array either a Float32Array.
  20774. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20775. * 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).
  20776. * Note that a new underlying VertexBuffer object is created each call.
  20777. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20778. *
  20779. * Possible `kind` values :
  20780. * - BABYLON.VertexBuffer.PositionKind
  20781. * - BABYLON.VertexBuffer.UVKind
  20782. * - BABYLON.VertexBuffer.UV2Kind
  20783. * - BABYLON.VertexBuffer.UV3Kind
  20784. * - BABYLON.VertexBuffer.UV4Kind
  20785. * - BABYLON.VertexBuffer.UV5Kind
  20786. * - BABYLON.VertexBuffer.UV6Kind
  20787. * - BABYLON.VertexBuffer.ColorKind
  20788. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20789. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20790. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20791. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20792. *
  20793. * Returns the Mesh.
  20794. */
  20795. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20796. if (!this._geometry) {
  20797. var vertexData = new BABYLON.VertexData();
  20798. vertexData.set(data, kind);
  20799. var scene = this.getScene();
  20800. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20801. }
  20802. else {
  20803. this._geometry.setVerticesData(kind, data, updatable, stride);
  20804. }
  20805. return this;
  20806. };
  20807. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20808. if (updatable === void 0) { updatable = true; }
  20809. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20810. return;
  20811. }
  20812. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20813. };
  20814. /**
  20815. * Sets the mesh VertexBuffer.
  20816. * Returns the Mesh.
  20817. */
  20818. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20819. if (!this._geometry) {
  20820. var scene = this.getScene();
  20821. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20822. }
  20823. this._geometry.setVerticesBuffer(buffer);
  20824. return this;
  20825. };
  20826. /**
  20827. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20828. * If the mesh has no geometry, it is simply returned as it is.
  20829. * The `data` are either a numeric array either a Float32Array.
  20830. * No new underlying VertexBuffer object is created.
  20831. * 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.
  20832. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20833. *
  20834. * Possible `kind` values :
  20835. * - BABYLON.VertexBuffer.PositionKind
  20836. * - BABYLON.VertexBuffer.UVKind
  20837. * - BABYLON.VertexBuffer.UV2Kind
  20838. * - BABYLON.VertexBuffer.UV3Kind
  20839. * - BABYLON.VertexBuffer.UV4Kind
  20840. * - BABYLON.VertexBuffer.UV5Kind
  20841. * - BABYLON.VertexBuffer.UV6Kind
  20842. * - BABYLON.VertexBuffer.ColorKind
  20843. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20844. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20845. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20846. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20847. *
  20848. * Returns the Mesh.
  20849. */
  20850. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20851. if (!this._geometry) {
  20852. return;
  20853. }
  20854. if (!makeItUnique) {
  20855. this._geometry.updateVerticesData(kind, data, updateExtends);
  20856. }
  20857. else {
  20858. this.makeGeometryUnique();
  20859. this.updateVerticesData(kind, data, updateExtends, false);
  20860. }
  20861. return this;
  20862. };
  20863. /**
  20864. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20865. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20866. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20867. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20868. * Returns the Mesh.
  20869. */
  20870. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20871. if (computeNormals === void 0) { computeNormals = true; }
  20872. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20873. positionFunction(positions);
  20874. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20875. if (computeNormals) {
  20876. var indices = this.getIndices();
  20877. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20878. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20879. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20880. }
  20881. return this;
  20882. };
  20883. /**
  20884. * Creates a un-shared specific occurence of the geometry for the mesh.
  20885. * Returns the Mesh.
  20886. */
  20887. Mesh.prototype.makeGeometryUnique = function () {
  20888. if (!this._geometry) {
  20889. return;
  20890. }
  20891. var oldGeometry = this._geometry;
  20892. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20893. oldGeometry.releaseForMesh(this, true);
  20894. geometry.applyToMesh(this);
  20895. return this;
  20896. };
  20897. /**
  20898. * Sets the mesh indices.
  20899. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20900. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20901. * This method creates a new index buffer each call.
  20902. * Returns the Mesh.
  20903. */
  20904. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20905. if (!this._geometry) {
  20906. var vertexData = new BABYLON.VertexData();
  20907. vertexData.indices = indices;
  20908. var scene = this.getScene();
  20909. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20910. }
  20911. else {
  20912. this._geometry.setIndices(indices, totalVertices);
  20913. }
  20914. return this;
  20915. };
  20916. /**
  20917. * Invert the geometry to move from a right handed system to a left handed one.
  20918. * Returns the Mesh.
  20919. */
  20920. Mesh.prototype.toLeftHanded = function () {
  20921. if (!this._geometry) {
  20922. return;
  20923. }
  20924. this._geometry.toLeftHanded();
  20925. return this;
  20926. };
  20927. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20928. var engine = this.getScene().getEngine();
  20929. // Wireframe
  20930. var indexToBind;
  20931. if (this._unIndexed) {
  20932. indexToBind = null;
  20933. }
  20934. else {
  20935. switch (fillMode) {
  20936. case BABYLON.Material.PointFillMode:
  20937. indexToBind = null;
  20938. break;
  20939. case BABYLON.Material.WireFrameFillMode:
  20940. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20941. break;
  20942. default:
  20943. case BABYLON.Material.TriangleFillMode:
  20944. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20945. break;
  20946. }
  20947. }
  20948. // VBOs
  20949. this._geometry._bind(effect, indexToBind);
  20950. return this;
  20951. };
  20952. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20953. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20954. return this;
  20955. }
  20956. this.onBeforeDrawObservable.notifyObservers(this);
  20957. var engine = this.getScene().getEngine();
  20958. // Draw order
  20959. switch (fillMode) {
  20960. case BABYLON.Material.PointFillMode:
  20961. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20962. break;
  20963. case BABYLON.Material.WireFrameFillMode:
  20964. if (this._unIndexed) {
  20965. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20966. }
  20967. else {
  20968. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20969. }
  20970. break;
  20971. default:
  20972. if (this._unIndexed) {
  20973. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20974. }
  20975. else {
  20976. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20977. }
  20978. }
  20979. return this;
  20980. };
  20981. /**
  20982. * Registers for this mesh a javascript function called just before the rendering process.
  20983. * This function is passed the current mesh.
  20984. * Return the Mesh.
  20985. */
  20986. Mesh.prototype.registerBeforeRender = function (func) {
  20987. this.onBeforeRenderObservable.add(func);
  20988. return this;
  20989. };
  20990. /**
  20991. * Disposes a previously registered javascript function called before the rendering.
  20992. * This function is passed the current mesh.
  20993. * Returns the Mesh.
  20994. */
  20995. Mesh.prototype.unregisterBeforeRender = function (func) {
  20996. this.onBeforeRenderObservable.removeCallback(func);
  20997. return this;
  20998. };
  20999. /**
  21000. * Registers for this mesh a javascript function called just after the rendering is complete.
  21001. * This function is passed the current mesh.
  21002. * Returns the Mesh.
  21003. */
  21004. Mesh.prototype.registerAfterRender = function (func) {
  21005. this.onAfterRenderObservable.add(func);
  21006. return this;
  21007. };
  21008. /**
  21009. * Disposes a previously registered javascript function called after the rendering.
  21010. * This function is passed the current mesh.
  21011. * Return the Mesh.
  21012. */
  21013. Mesh.prototype.unregisterAfterRender = function (func) {
  21014. this.onAfterRenderObservable.removeCallback(func);
  21015. return this;
  21016. };
  21017. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21018. var scene = this.getScene();
  21019. this._batchCache.mustReturn = false;
  21020. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21021. this._batchCache.visibleInstances[subMeshId] = null;
  21022. if (this._visibleInstances) {
  21023. var currentRenderId = scene.getRenderId();
  21024. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21025. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21026. var selfRenderId = this._renderId;
  21027. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21028. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21029. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21030. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21031. }
  21032. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21033. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21034. this._batchCache.mustReturn = true;
  21035. return this._batchCache;
  21036. }
  21037. if (currentRenderId !== selfRenderId) {
  21038. this._batchCache.renderSelf[subMeshId] = false;
  21039. }
  21040. }
  21041. this._renderIdForInstances[subMeshId] = currentRenderId;
  21042. }
  21043. return this._batchCache;
  21044. };
  21045. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21046. var visibleInstances = batch.visibleInstances[subMesh._id];
  21047. var matricesCount = visibleInstances.length + 1;
  21048. var bufferSize = matricesCount * 16 * 4;
  21049. var currentInstancesBufferSize = this._instancesBufferSize;
  21050. var instancesBuffer = this._instancesBuffer;
  21051. while (this._instancesBufferSize < bufferSize) {
  21052. this._instancesBufferSize *= 2;
  21053. }
  21054. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21055. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21056. }
  21057. var offset = 0;
  21058. var instancesCount = 0;
  21059. var world = this.getWorldMatrix();
  21060. if (batch.renderSelf[subMesh._id]) {
  21061. world.copyToArray(this._instancesData, offset);
  21062. offset += 16;
  21063. instancesCount++;
  21064. }
  21065. if (visibleInstances) {
  21066. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21067. var instance = visibleInstances[instanceIndex];
  21068. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21069. offset += 16;
  21070. instancesCount++;
  21071. }
  21072. }
  21073. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21074. if (instancesBuffer) {
  21075. instancesBuffer.dispose();
  21076. }
  21077. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21078. this._instancesBuffer = instancesBuffer;
  21079. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21080. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21081. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21082. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21083. }
  21084. else {
  21085. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21086. }
  21087. this.geometry._bind(effect);
  21088. this._draw(subMesh, fillMode, instancesCount);
  21089. engine.unbindInstanceAttributes();
  21090. return this;
  21091. };
  21092. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21093. var scene = this.getScene();
  21094. var engine = scene.getEngine();
  21095. if (hardwareInstancedRendering) {
  21096. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21097. }
  21098. else {
  21099. if (batch.renderSelf[subMesh._id]) {
  21100. // Draw
  21101. if (onBeforeDraw) {
  21102. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21103. }
  21104. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21105. }
  21106. if (batch.visibleInstances[subMesh._id]) {
  21107. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21108. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21109. // World
  21110. var world = instance.getWorldMatrix();
  21111. if (onBeforeDraw) {
  21112. onBeforeDraw(true, world, effectiveMaterial);
  21113. }
  21114. // Draw
  21115. this._draw(subMesh, fillMode);
  21116. }
  21117. }
  21118. }
  21119. return this;
  21120. };
  21121. /**
  21122. * Triggers the draw call for the mesh.
  21123. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21124. * Returns the Mesh.
  21125. */
  21126. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21127. var scene = this.getScene();
  21128. // Managing instances
  21129. var batch = this._getInstancesRenderList(subMesh._id);
  21130. if (batch.mustReturn) {
  21131. return this;
  21132. }
  21133. // Checking geometry state
  21134. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21135. return this;
  21136. }
  21137. var callbackIndex;
  21138. this.onBeforeRenderObservable.notifyObservers(this);
  21139. var engine = scene.getEngine();
  21140. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21141. // Material
  21142. var effectiveMaterial = subMesh.getMaterial();
  21143. if (!effectiveMaterial) {
  21144. return this;
  21145. }
  21146. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21147. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21148. return this;
  21149. }
  21150. }
  21151. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21152. return this;
  21153. }
  21154. // Alpha mode
  21155. if (enableAlphaMode) {
  21156. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21157. }
  21158. // Outline - step 1
  21159. var savedDepthWrite = engine.getDepthWrite();
  21160. if (this.renderOutline) {
  21161. engine.setDepthWrite(false);
  21162. scene.getOutlineRenderer().render(subMesh, batch);
  21163. engine.setDepthWrite(savedDepthWrite);
  21164. }
  21165. var effect;
  21166. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21167. effect = subMesh.effect;
  21168. }
  21169. else {
  21170. effect = effectiveMaterial.getEffect();
  21171. }
  21172. effectiveMaterial._preBind(effect);
  21173. // Bind
  21174. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21175. this._bind(subMesh, effect, fillMode);
  21176. var world = this.getWorldMatrix();
  21177. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21178. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21179. }
  21180. else {
  21181. effectiveMaterial.bind(world, this);
  21182. }
  21183. // Draw
  21184. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21185. // Unbind
  21186. effectiveMaterial.unbind();
  21187. // Outline - step 2
  21188. if (this.renderOutline && savedDepthWrite) {
  21189. engine.setDepthWrite(true);
  21190. engine.setColorWrite(false);
  21191. scene.getOutlineRenderer().render(subMesh, batch);
  21192. engine.setColorWrite(true);
  21193. }
  21194. // Overlay
  21195. if (this.renderOverlay) {
  21196. var currentMode = engine.getAlphaMode();
  21197. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21198. scene.getOutlineRenderer().render(subMesh, batch, true);
  21199. engine.setAlphaMode(currentMode);
  21200. }
  21201. this.onAfterRenderObservable.notifyObservers(this);
  21202. return this;
  21203. };
  21204. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21205. if (isInstance) {
  21206. effectiveMaterial.bindOnlyWorldMatrix(world);
  21207. }
  21208. return this;
  21209. };
  21210. /**
  21211. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21212. */
  21213. Mesh.prototype.getEmittedParticleSystems = function () {
  21214. var results = new Array();
  21215. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21216. var particleSystem = this.getScene().particleSystems[index];
  21217. if (particleSystem.emitter === this) {
  21218. results.push(particleSystem);
  21219. }
  21220. }
  21221. return results;
  21222. };
  21223. /**
  21224. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21225. */
  21226. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21227. var results = new Array();
  21228. var descendants = this.getDescendants();
  21229. descendants.push(this);
  21230. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21231. var particleSystem = this.getScene().particleSystems[index];
  21232. var emitter = particleSystem.emitter;
  21233. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21234. results.push(particleSystem);
  21235. }
  21236. }
  21237. return results;
  21238. };
  21239. Mesh.prototype._checkDelayState = function () {
  21240. var scene = this.getScene();
  21241. if (this._geometry) {
  21242. this._geometry.load(scene);
  21243. }
  21244. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21245. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21246. this._queueLoad(this, scene);
  21247. }
  21248. return this;
  21249. };
  21250. Mesh.prototype._queueLoad = function (mesh, scene) {
  21251. var _this = this;
  21252. scene._addPendingData(mesh);
  21253. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21254. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21255. if (data instanceof ArrayBuffer) {
  21256. _this._delayLoadingFunction(data, _this);
  21257. }
  21258. else {
  21259. _this._delayLoadingFunction(JSON.parse(data), _this);
  21260. }
  21261. _this.instances.forEach(function (instance) {
  21262. instance._syncSubMeshes();
  21263. });
  21264. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21265. scene._removePendingData(_this);
  21266. }, function () { }, scene.database, getBinaryData);
  21267. return this;
  21268. };
  21269. /**
  21270. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21271. */
  21272. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21273. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21274. return false;
  21275. }
  21276. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21277. return false;
  21278. }
  21279. this._checkDelayState();
  21280. return true;
  21281. };
  21282. /**
  21283. * Sets the mesh material by the material or multiMaterial `id` property.
  21284. * The material `id` is a string identifying the material or the multiMaterial.
  21285. * This method returns the Mesh.
  21286. */
  21287. Mesh.prototype.setMaterialByID = function (id) {
  21288. var materials = this.getScene().materials;
  21289. var index;
  21290. for (index = materials.length - 1; index > -1; index--) {
  21291. if (materials[index].id === id) {
  21292. this.material = materials[index];
  21293. return this;
  21294. }
  21295. }
  21296. // Multi
  21297. var multiMaterials = this.getScene().multiMaterials;
  21298. for (index = multiMaterials.length - 1; index > -1; index--) {
  21299. if (multiMaterials[index].id === id) {
  21300. this.material = multiMaterials[index];
  21301. return this;
  21302. }
  21303. }
  21304. return this;
  21305. };
  21306. /**
  21307. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21308. */
  21309. Mesh.prototype.getAnimatables = function () {
  21310. var results = [];
  21311. if (this.material) {
  21312. results.push(this.material);
  21313. }
  21314. if (this.skeleton) {
  21315. results.push(this.skeleton);
  21316. }
  21317. return results;
  21318. };
  21319. /**
  21320. * Modifies the mesh geometry according to the passed transformation matrix.
  21321. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21322. * The mesh normals are modified accordingly the same transformation.
  21323. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21324. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21325. * Returns the Mesh.
  21326. */
  21327. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21328. // Position
  21329. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21330. return this;
  21331. }
  21332. var submeshes = this.subMeshes.splice(0);
  21333. this._resetPointsArrayCache();
  21334. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21335. var temp = [];
  21336. var index;
  21337. for (index = 0; index < data.length; index += 3) {
  21338. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21339. }
  21340. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21341. // Normals
  21342. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21343. return this;
  21344. }
  21345. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21346. temp = [];
  21347. for (index = 0; index < data.length; index += 3) {
  21348. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21349. }
  21350. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21351. // flip faces?
  21352. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21353. this.flipFaces();
  21354. }
  21355. // Restore submeshes
  21356. this.releaseSubMeshes();
  21357. this.subMeshes = submeshes;
  21358. return this;
  21359. };
  21360. /**
  21361. * Modifies the mesh geometry according to its own current World Matrix.
  21362. * The mesh World Matrix is then reset.
  21363. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21364. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21365. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21366. * Returns the Mesh.
  21367. */
  21368. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21369. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21370. this.scaling.copyFromFloats(1, 1, 1);
  21371. this.position.copyFromFloats(0, 0, 0);
  21372. this.rotation.copyFromFloats(0, 0, 0);
  21373. //only if quaternion is already set
  21374. if (this.rotationQuaternion) {
  21375. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21376. }
  21377. this._worldMatrix = BABYLON.Matrix.Identity();
  21378. return this;
  21379. };
  21380. Object.defineProperty(Mesh.prototype, "_positions", {
  21381. // Cache
  21382. get: function () {
  21383. if (this._geometry) {
  21384. return this._geometry._positions;
  21385. }
  21386. return null;
  21387. },
  21388. enumerable: true,
  21389. configurable: true
  21390. });
  21391. Mesh.prototype._resetPointsArrayCache = function () {
  21392. if (this._geometry) {
  21393. this._geometry._resetPointsArrayCache();
  21394. }
  21395. return this;
  21396. };
  21397. Mesh.prototype._generatePointsArray = function () {
  21398. if (this._geometry) {
  21399. return this._geometry._generatePointsArray();
  21400. }
  21401. return false;
  21402. };
  21403. /**
  21404. * Returns a new Mesh object generated from the current mesh properties.
  21405. * This method must not get confused with createInstance().
  21406. * The parameter `name` is a string, the name given to the new mesh.
  21407. * The optional parameter `newParent` can be any Node object (default `null`).
  21408. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21409. * 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.
  21410. */
  21411. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21412. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21413. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21414. };
  21415. /**
  21416. * Disposes the mesh.
  21417. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21418. */
  21419. Mesh.prototype.dispose = function (doNotRecurse) {
  21420. var _this = this;
  21421. this.morphTargetManager = undefined;
  21422. if (this._geometry) {
  21423. this._geometry.releaseForMesh(this, true);
  21424. }
  21425. // Sources
  21426. var meshes = this.getScene().meshes;
  21427. meshes.forEach(function (mesh) {
  21428. if (mesh._source && mesh._source === _this) {
  21429. mesh._source = null;
  21430. }
  21431. });
  21432. this._source = null;
  21433. // Instances
  21434. if (this._instancesBuffer) {
  21435. this._instancesBuffer.dispose();
  21436. this._instancesBuffer = null;
  21437. }
  21438. while (this.instances.length) {
  21439. this.instances[0].dispose();
  21440. }
  21441. // Highlight layers.
  21442. var highlightLayers = this.getScene().highlightLayers;
  21443. for (var i = 0; i < highlightLayers.length; i++) {
  21444. var highlightLayer = highlightLayers[i];
  21445. if (highlightLayer) {
  21446. highlightLayer.removeMesh(this);
  21447. highlightLayer.removeExcludedMesh(this);
  21448. }
  21449. }
  21450. _super.prototype.dispose.call(this, doNotRecurse);
  21451. };
  21452. /**
  21453. * Modifies the mesh geometry according to a displacement map.
  21454. * 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.
  21455. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21456. * This method returns nothing.
  21457. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21458. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21459. * 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.
  21460. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21461. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21462. *
  21463. * Returns the Mesh.
  21464. */
  21465. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21466. var _this = this;
  21467. var scene = this.getScene();
  21468. var onload = function (img) {
  21469. // Getting height map data
  21470. var canvas = document.createElement("canvas");
  21471. var context = canvas.getContext("2d");
  21472. var heightMapWidth = img.width;
  21473. var heightMapHeight = img.height;
  21474. canvas.width = heightMapWidth;
  21475. canvas.height = heightMapHeight;
  21476. context.drawImage(img, 0, 0);
  21477. // Create VertexData from map data
  21478. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21479. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21480. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21481. //execute success callback, if set
  21482. if (onSuccess) {
  21483. onSuccess(_this);
  21484. }
  21485. };
  21486. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21487. return this;
  21488. };
  21489. /**
  21490. * Modifies the mesh geometry according to a displacementMap buffer.
  21491. * 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.
  21492. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21493. * This method returns nothing.
  21494. * 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.
  21495. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21496. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21497. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21498. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21499. *
  21500. * Returns the Mesh.
  21501. */
  21502. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21503. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21504. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21505. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21506. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21507. return this;
  21508. }
  21509. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21510. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21511. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21512. var position = BABYLON.Vector3.Zero();
  21513. var normal = BABYLON.Vector3.Zero();
  21514. var uv = BABYLON.Vector2.Zero();
  21515. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21516. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21517. for (var index = 0; index < positions.length; index += 3) {
  21518. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21519. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21520. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21521. // Compute height
  21522. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21523. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21524. var pos = (u + v * heightMapWidth) * 4;
  21525. var r = buffer[pos] / 255.0;
  21526. var g = buffer[pos + 1] / 255.0;
  21527. var b = buffer[pos + 2] / 255.0;
  21528. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21529. normal.normalize();
  21530. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21531. position = position.add(normal);
  21532. position.toArray(positions, index);
  21533. }
  21534. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21535. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21536. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21537. return this;
  21538. };
  21539. /**
  21540. * Modify the mesh to get a flat shading rendering.
  21541. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21542. * This method returns the Mesh.
  21543. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21544. */
  21545. Mesh.prototype.convertToFlatShadedMesh = function () {
  21546. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21547. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21548. var kinds = this.getVerticesDataKinds();
  21549. var vbs = [];
  21550. var data = [];
  21551. var newdata = [];
  21552. var updatableNormals = false;
  21553. var kindIndex;
  21554. var kind;
  21555. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21556. kind = kinds[kindIndex];
  21557. var vertexBuffer = this.getVertexBuffer(kind);
  21558. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21559. updatableNormals = vertexBuffer.isUpdatable();
  21560. kinds.splice(kindIndex, 1);
  21561. kindIndex--;
  21562. continue;
  21563. }
  21564. vbs[kind] = vertexBuffer;
  21565. data[kind] = vbs[kind].getData();
  21566. newdata[kind] = [];
  21567. }
  21568. // Save previous submeshes
  21569. var previousSubmeshes = this.subMeshes.slice(0);
  21570. var indices = this.getIndices();
  21571. var totalIndices = this.getTotalIndices();
  21572. // Generating unique vertices per face
  21573. var index;
  21574. for (index = 0; index < totalIndices; index++) {
  21575. var vertexIndex = indices[index];
  21576. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21577. kind = kinds[kindIndex];
  21578. var stride = vbs[kind].getStrideSize();
  21579. for (var offset = 0; offset < stride; offset++) {
  21580. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21581. }
  21582. }
  21583. }
  21584. // Updating faces & normal
  21585. var normals = [];
  21586. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21587. for (index = 0; index < totalIndices; index += 3) {
  21588. indices[index] = index;
  21589. indices[index + 1] = index + 1;
  21590. indices[index + 2] = index + 2;
  21591. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21592. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21593. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21594. var p1p2 = p1.subtract(p2);
  21595. var p3p2 = p3.subtract(p2);
  21596. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21597. // Store same normals for every vertex
  21598. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21599. normals.push(normal.x);
  21600. normals.push(normal.y);
  21601. normals.push(normal.z);
  21602. }
  21603. }
  21604. this.setIndices(indices);
  21605. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21606. // Updating vertex buffers
  21607. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21608. kind = kinds[kindIndex];
  21609. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21610. }
  21611. // Updating submeshes
  21612. this.releaseSubMeshes();
  21613. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21614. var previousOne = previousSubmeshes[submeshIndex];
  21615. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21616. }
  21617. this.synchronizeInstances();
  21618. return this;
  21619. };
  21620. /**
  21621. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21622. * In other words, more vertices, no more indices and a single bigger VBO.
  21623. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21624. * Returns the Mesh.
  21625. */
  21626. Mesh.prototype.convertToUnIndexedMesh = function () {
  21627. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21628. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21629. var kinds = this.getVerticesDataKinds();
  21630. var vbs = [];
  21631. var data = [];
  21632. var newdata = [];
  21633. var updatableNormals = false;
  21634. var kindIndex;
  21635. var kind;
  21636. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21637. kind = kinds[kindIndex];
  21638. var vertexBuffer = this.getVertexBuffer(kind);
  21639. vbs[kind] = vertexBuffer;
  21640. data[kind] = vbs[kind].getData();
  21641. newdata[kind] = [];
  21642. }
  21643. // Save previous submeshes
  21644. var previousSubmeshes = this.subMeshes.slice(0);
  21645. var indices = this.getIndices();
  21646. var totalIndices = this.getTotalIndices();
  21647. // Generating unique vertices per face
  21648. var index;
  21649. for (index = 0; index < totalIndices; index++) {
  21650. var vertexIndex = indices[index];
  21651. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21652. kind = kinds[kindIndex];
  21653. var stride = vbs[kind].getStrideSize();
  21654. for (var offset = 0; offset < stride; offset++) {
  21655. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21656. }
  21657. }
  21658. }
  21659. // Updating indices
  21660. for (index = 0; index < totalIndices; index += 3) {
  21661. indices[index] = index;
  21662. indices[index + 1] = index + 1;
  21663. indices[index + 2] = index + 2;
  21664. }
  21665. this.setIndices(indices);
  21666. // Updating vertex buffers
  21667. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21668. kind = kinds[kindIndex];
  21669. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21670. }
  21671. // Updating submeshes
  21672. this.releaseSubMeshes();
  21673. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21674. var previousOne = previousSubmeshes[submeshIndex];
  21675. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21676. }
  21677. this._unIndexed = true;
  21678. this.synchronizeInstances();
  21679. return this;
  21680. };
  21681. /**
  21682. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21683. * This method returns the Mesh.
  21684. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21685. */
  21686. Mesh.prototype.flipFaces = function (flipNormals) {
  21687. if (flipNormals === void 0) { flipNormals = false; }
  21688. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21689. var i;
  21690. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21691. for (i = 0; i < vertex_data.normals.length; i++) {
  21692. vertex_data.normals[i] *= -1;
  21693. }
  21694. }
  21695. var temp;
  21696. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21697. // reassign indices
  21698. temp = vertex_data.indices[i + 1];
  21699. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21700. vertex_data.indices[i + 2] = temp;
  21701. }
  21702. vertex_data.applyToMesh(this);
  21703. return this;
  21704. };
  21705. // Instances
  21706. /**
  21707. * Creates a new InstancedMesh object from the mesh model.
  21708. * An instance shares the same properties and the same material than its model.
  21709. * Only these properties of each instance can then be set individually :
  21710. * - position
  21711. * - rotation
  21712. * - rotationQuaternion
  21713. * - setPivotMatrix
  21714. * - scaling
  21715. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21716. * Warning : this method is not supported for Line mesh and LineSystem
  21717. */
  21718. Mesh.prototype.createInstance = function (name) {
  21719. return new BABYLON.InstancedMesh(name, this);
  21720. };
  21721. /**
  21722. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21723. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21724. * This method returns the Mesh.
  21725. */
  21726. Mesh.prototype.synchronizeInstances = function () {
  21727. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21728. var instance = this.instances[instanceIndex];
  21729. instance._syncSubMeshes();
  21730. }
  21731. return this;
  21732. };
  21733. /**
  21734. * Simplify the mesh according to the given array of settings.
  21735. * Function will return immediately and will simplify async. It returns the Mesh.
  21736. * @param settings a collection of simplification settings.
  21737. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21738. * @param type the type of simplification to run.
  21739. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21740. */
  21741. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21742. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21743. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21744. this.getScene().simplificationQueue.addTask({
  21745. settings: settings,
  21746. parallelProcessing: parallelProcessing,
  21747. mesh: this,
  21748. simplificationType: simplificationType,
  21749. successCallback: successCallback
  21750. });
  21751. return this;
  21752. };
  21753. /**
  21754. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21755. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21756. * This should be used together with the simplification to avoid disappearing triangles.
  21757. * Returns the Mesh.
  21758. * @param successCallback an optional success callback to be called after the optimization finished.
  21759. */
  21760. Mesh.prototype.optimizeIndices = function (successCallback) {
  21761. var _this = this;
  21762. var indices = this.getIndices();
  21763. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21764. var vectorPositions = [];
  21765. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21766. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21767. }
  21768. var dupes = [];
  21769. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21770. var realPos = vectorPositions.length - 1 - iteration;
  21771. var testedPosition = vectorPositions[realPos];
  21772. for (var j = 0; j < realPos; ++j) {
  21773. var againstPosition = vectorPositions[j];
  21774. if (testedPosition.equals(againstPosition)) {
  21775. dupes[realPos] = j;
  21776. break;
  21777. }
  21778. }
  21779. }, function () {
  21780. for (var i = 0; i < indices.length; ++i) {
  21781. indices[i] = dupes[indices[i]] || indices[i];
  21782. }
  21783. //indices are now reordered
  21784. var originalSubMeshes = _this.subMeshes.slice(0);
  21785. _this.setIndices(indices);
  21786. _this.subMeshes = originalSubMeshes;
  21787. if (successCallback) {
  21788. successCallback(_this);
  21789. }
  21790. });
  21791. return this;
  21792. };
  21793. Mesh.prototype.serialize = function (serializationObject) {
  21794. serializationObject.name = this.name;
  21795. serializationObject.id = this.id;
  21796. serializationObject.type = this.getClassName();
  21797. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21798. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21799. }
  21800. serializationObject.position = this.position.asArray();
  21801. if (this.rotationQuaternion) {
  21802. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21803. }
  21804. else if (this.rotation) {
  21805. serializationObject.rotation = this.rotation.asArray();
  21806. }
  21807. serializationObject.scaling = this.scaling.asArray();
  21808. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21809. serializationObject.isEnabled = this.isEnabled();
  21810. serializationObject.isVisible = this.isVisible;
  21811. serializationObject.infiniteDistance = this.infiniteDistance;
  21812. serializationObject.pickable = this.isPickable;
  21813. serializationObject.receiveShadows = this.receiveShadows;
  21814. serializationObject.billboardMode = this.billboardMode;
  21815. serializationObject.visibility = this.visibility;
  21816. serializationObject.checkCollisions = this.checkCollisions;
  21817. serializationObject.isBlocker = this.isBlocker;
  21818. // Parent
  21819. if (this.parent) {
  21820. serializationObject.parentId = this.parent.id;
  21821. }
  21822. // Geometry
  21823. var geometry = this._geometry;
  21824. if (geometry) {
  21825. var geometryId = geometry.id;
  21826. serializationObject.geometryId = geometryId;
  21827. // SubMeshes
  21828. serializationObject.subMeshes = [];
  21829. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21830. var subMesh = this.subMeshes[subIndex];
  21831. serializationObject.subMeshes.push({
  21832. materialIndex: subMesh.materialIndex,
  21833. verticesStart: subMesh.verticesStart,
  21834. verticesCount: subMesh.verticesCount,
  21835. indexStart: subMesh.indexStart,
  21836. indexCount: subMesh.indexCount
  21837. });
  21838. }
  21839. }
  21840. // Material
  21841. if (this.material) {
  21842. serializationObject.materialId = this.material.id;
  21843. }
  21844. else {
  21845. this.material = null;
  21846. }
  21847. // Morph targets
  21848. if (this.morphTargetManager) {
  21849. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21850. }
  21851. // Skeleton
  21852. if (this.skeleton) {
  21853. serializationObject.skeletonId = this.skeleton.id;
  21854. }
  21855. // Physics
  21856. //TODO implement correct serialization for physics impostors.
  21857. if (this.getPhysicsImpostor()) {
  21858. var impostor = this.getPhysicsImpostor();
  21859. serializationObject.physicsMass = impostor.getParam("mass");
  21860. serializationObject.physicsFriction = impostor.getParam("friction");
  21861. serializationObject.physicsRestitution = impostor.getParam("mass");
  21862. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21863. }
  21864. // Metadata
  21865. if (this.metadata) {
  21866. serializationObject.metadata = this.metadata;
  21867. }
  21868. // Instances
  21869. serializationObject.instances = [];
  21870. for (var index = 0; index < this.instances.length; index++) {
  21871. var instance = this.instances[index];
  21872. var serializationInstance = {
  21873. name: instance.name,
  21874. position: instance.position.asArray(),
  21875. scaling: instance.scaling.asArray()
  21876. };
  21877. if (instance.rotationQuaternion) {
  21878. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21879. }
  21880. else if (instance.rotation) {
  21881. serializationInstance.rotation = instance.rotation.asArray();
  21882. }
  21883. serializationObject.instances.push(serializationInstance);
  21884. // Animations
  21885. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21886. serializationInstance.ranges = instance.serializeAnimationRanges();
  21887. }
  21888. //
  21889. // Animations
  21890. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21891. serializationObject.ranges = this.serializeAnimationRanges();
  21892. // Layer mask
  21893. serializationObject.layerMask = this.layerMask;
  21894. // Alpha
  21895. serializationObject.alphaIndex = this.alphaIndex;
  21896. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21897. // Overlay
  21898. serializationObject.overlayAlpha = this.overlayAlpha;
  21899. serializationObject.overlayColor = this.overlayColor.asArray();
  21900. serializationObject.renderOverlay = this.renderOverlay;
  21901. // Fog
  21902. serializationObject.applyFog = this.applyFog;
  21903. // Action Manager
  21904. if (this.actionManager) {
  21905. serializationObject.actions = this.actionManager.serialize(this.name);
  21906. }
  21907. };
  21908. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21909. if (!this.geometry) {
  21910. return;
  21911. }
  21912. this._markSubMeshesAsAttributesDirty();
  21913. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21914. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21915. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21916. this.morphTargetManager = undefined;
  21917. return;
  21918. }
  21919. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21920. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21921. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21922. if (morphTarget.hasNormals) {
  21923. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21924. }
  21925. if (morphTarget.hasTangents) {
  21926. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21927. }
  21928. }
  21929. }
  21930. else {
  21931. var index = 0;
  21932. // Positions
  21933. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21934. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21935. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21936. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21937. }
  21938. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21939. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21940. }
  21941. index++;
  21942. }
  21943. }
  21944. };
  21945. // Statics
  21946. /**
  21947. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21948. * The parameter `parsedMesh` is the mesh to be copied.
  21949. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21950. */
  21951. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21952. var mesh;
  21953. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21954. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21955. }
  21956. else {
  21957. mesh = new Mesh(parsedMesh.name, scene);
  21958. }
  21959. mesh.id = parsedMesh.id;
  21960. if (BABYLON.Tags) {
  21961. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21962. }
  21963. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21964. if (parsedMesh.metadata !== undefined) {
  21965. mesh.metadata = parsedMesh.metadata;
  21966. }
  21967. if (parsedMesh.rotationQuaternion) {
  21968. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21969. }
  21970. else if (parsedMesh.rotation) {
  21971. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21972. }
  21973. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21974. if (parsedMesh.localMatrix) {
  21975. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21976. }
  21977. else if (parsedMesh.pivotMatrix) {
  21978. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21979. }
  21980. mesh.setEnabled(parsedMesh.isEnabled);
  21981. mesh.isVisible = parsedMesh.isVisible;
  21982. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21983. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21984. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21985. if (parsedMesh.applyFog !== undefined) {
  21986. mesh.applyFog = parsedMesh.applyFog;
  21987. }
  21988. if (parsedMesh.pickable !== undefined) {
  21989. mesh.isPickable = parsedMesh.pickable;
  21990. }
  21991. if (parsedMesh.alphaIndex !== undefined) {
  21992. mesh.alphaIndex = parsedMesh.alphaIndex;
  21993. }
  21994. mesh.receiveShadows = parsedMesh.receiveShadows;
  21995. mesh.billboardMode = parsedMesh.billboardMode;
  21996. if (parsedMesh.visibility !== undefined) {
  21997. mesh.visibility = parsedMesh.visibility;
  21998. }
  21999. mesh.checkCollisions = parsedMesh.checkCollisions;
  22000. if (parsedMesh.isBlocker !== undefined) {
  22001. mesh.isBlocker = parsedMesh.isBlocker;
  22002. }
  22003. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22004. // freezeWorldMatrix
  22005. if (parsedMesh.freezeWorldMatrix) {
  22006. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22007. }
  22008. // Parent
  22009. if (parsedMesh.parentId) {
  22010. mesh._waitingParentId = parsedMesh.parentId;
  22011. }
  22012. // Actions
  22013. if (parsedMesh.actions !== undefined) {
  22014. mesh._waitingActions = parsedMesh.actions;
  22015. }
  22016. // Overlay
  22017. if (parsedMesh.overlayAlpha !== undefined) {
  22018. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22019. }
  22020. if (parsedMesh.overlayColor !== undefined) {
  22021. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22022. }
  22023. if (parsedMesh.renderOverlay !== undefined) {
  22024. mesh.renderOverlay = parsedMesh.renderOverlay;
  22025. }
  22026. // Geometry
  22027. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22028. if (parsedMesh.delayLoadingFile) {
  22029. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22030. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22031. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22032. if (parsedMesh._binaryInfo) {
  22033. mesh._binaryInfo = parsedMesh._binaryInfo;
  22034. }
  22035. mesh._delayInfo = [];
  22036. if (parsedMesh.hasUVs) {
  22037. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22038. }
  22039. if (parsedMesh.hasUVs2) {
  22040. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22041. }
  22042. if (parsedMesh.hasUVs3) {
  22043. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22044. }
  22045. if (parsedMesh.hasUVs4) {
  22046. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22047. }
  22048. if (parsedMesh.hasUVs5) {
  22049. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22050. }
  22051. if (parsedMesh.hasUVs6) {
  22052. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22053. }
  22054. if (parsedMesh.hasColors) {
  22055. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22056. }
  22057. if (parsedMesh.hasMatricesIndices) {
  22058. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22059. }
  22060. if (parsedMesh.hasMatricesWeights) {
  22061. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22062. }
  22063. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22064. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22065. mesh._checkDelayState();
  22066. }
  22067. }
  22068. else {
  22069. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22070. }
  22071. // Material
  22072. if (parsedMesh.materialId) {
  22073. mesh.setMaterialByID(parsedMesh.materialId);
  22074. }
  22075. else {
  22076. mesh.material = null;
  22077. }
  22078. // Morph targets
  22079. if (parsedMesh.morphTargetManagerId > -1) {
  22080. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22081. }
  22082. // Skeleton
  22083. if (parsedMesh.skeletonId > -1) {
  22084. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22085. if (parsedMesh.numBoneInfluencers) {
  22086. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22087. }
  22088. }
  22089. // Animations
  22090. if (parsedMesh.animations) {
  22091. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22092. var parsedAnimation = parsedMesh.animations[animationIndex];
  22093. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22094. }
  22095. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22096. }
  22097. if (parsedMesh.autoAnimate) {
  22098. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22099. }
  22100. // Layer Mask
  22101. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22102. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22103. }
  22104. else {
  22105. mesh.layerMask = 0x0FFFFFFF;
  22106. }
  22107. // Physics
  22108. if (parsedMesh.physicsImpostor) {
  22109. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22110. mass: parsedMesh.physicsMass,
  22111. friction: parsedMesh.physicsFriction,
  22112. restitution: parsedMesh.physicsRestitution
  22113. }, scene);
  22114. }
  22115. // Instances
  22116. if (parsedMesh.instances) {
  22117. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22118. var parsedInstance = parsedMesh.instances[index];
  22119. var instance = mesh.createInstance(parsedInstance.name);
  22120. if (BABYLON.Tags) {
  22121. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22122. }
  22123. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22124. if (parsedInstance.parentId) {
  22125. instance._waitingParentId = parsedInstance.parentId;
  22126. }
  22127. if (parsedInstance.rotationQuaternion) {
  22128. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22129. }
  22130. else if (parsedInstance.rotation) {
  22131. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22132. }
  22133. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22134. instance.checkCollisions = mesh.checkCollisions;
  22135. if (parsedMesh.animations) {
  22136. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22137. parsedAnimation = parsedMesh.animations[animationIndex];
  22138. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22139. }
  22140. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22141. }
  22142. }
  22143. }
  22144. return mesh;
  22145. };
  22146. /**
  22147. * Creates a ribbon mesh.
  22148. * Please consider using the same method from the MeshBuilder class instead.
  22149. * 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.
  22150. *
  22151. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22152. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22153. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22154. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22155. * 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.
  22156. * 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.
  22157. * 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
  22158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22161. */
  22162. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22163. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22164. pathArray: pathArray,
  22165. closeArray: closeArray,
  22166. closePath: closePath,
  22167. offset: offset,
  22168. updatable: updatable,
  22169. sideOrientation: sideOrientation,
  22170. instance: instance
  22171. }, scene);
  22172. };
  22173. /**
  22174. * Creates a plane polygonal mesh. By default, this is a disc.
  22175. * Please consider using the same method from the MeshBuilder class instead.
  22176. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22177. * 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.
  22178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22179. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22181. */
  22182. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22183. var options = {
  22184. radius: radius,
  22185. tessellation: tessellation,
  22186. sideOrientation: sideOrientation,
  22187. updatable: updatable
  22188. };
  22189. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22190. };
  22191. /**
  22192. * Creates a box mesh.
  22193. * Please consider using the same method from the MeshBuilder class instead.
  22194. * The parameter `size` sets the size (float) of each box side (default 1).
  22195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22196. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22198. */
  22199. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22200. var options = {
  22201. size: size,
  22202. sideOrientation: sideOrientation,
  22203. updatable: updatable
  22204. };
  22205. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22206. };
  22207. /**
  22208. * Creates a sphere mesh.
  22209. * Please consider using the same method from the MeshBuilder class instead.
  22210. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22211. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22213. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22215. */
  22216. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22217. var options = {
  22218. segments: segments,
  22219. diameterX: diameter,
  22220. diameterY: diameter,
  22221. diameterZ: diameter,
  22222. sideOrientation: sideOrientation,
  22223. updatable: updatable
  22224. };
  22225. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22226. };
  22227. /**
  22228. * Creates a cylinder or a cone mesh.
  22229. * Please consider using the same method from the MeshBuilder class instead.
  22230. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22231. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22232. * 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.
  22233. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22234. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22235. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22236. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22238. */
  22239. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22240. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22241. if (scene !== undefined) {
  22242. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22243. updatable = scene;
  22244. }
  22245. scene = subdivisions;
  22246. subdivisions = 1;
  22247. }
  22248. var options = {
  22249. height: height,
  22250. diameterTop: diameterTop,
  22251. diameterBottom: diameterBottom,
  22252. tessellation: tessellation,
  22253. subdivisions: subdivisions,
  22254. sideOrientation: sideOrientation,
  22255. updatable: updatable
  22256. };
  22257. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22258. };
  22259. // Torus (Code from SharpDX.org)
  22260. /**
  22261. * Creates a torus mesh.
  22262. * Please consider using the same method from the MeshBuilder class instead.
  22263. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22264. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22265. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22266. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22267. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22269. */
  22270. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22271. var options = {
  22272. diameter: diameter,
  22273. thickness: thickness,
  22274. tessellation: tessellation,
  22275. sideOrientation: sideOrientation,
  22276. updatable: updatable
  22277. };
  22278. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22279. };
  22280. /**
  22281. * Creates a torus knot mesh.
  22282. * Please consider using the same method from the MeshBuilder class instead.
  22283. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22284. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22285. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22286. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22287. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22290. */
  22291. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22292. var options = {
  22293. radius: radius,
  22294. tube: tube,
  22295. radialSegments: radialSegments,
  22296. tubularSegments: tubularSegments,
  22297. p: p,
  22298. q: q,
  22299. sideOrientation: sideOrientation,
  22300. updatable: updatable
  22301. };
  22302. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22303. };
  22304. /**
  22305. * Creates a line mesh.
  22306. * Please consider using the same method from the MeshBuilder class instead.
  22307. * 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.
  22308. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22309. * The parameter `points` is an array successive Vector3.
  22310. * 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
  22311. * When updating an instance, remember that only point positions can change, not the number of points.
  22312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22313. */
  22314. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22315. var options = {
  22316. points: points,
  22317. updatable: updatable,
  22318. instance: instance
  22319. };
  22320. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22321. };
  22322. /**
  22323. * Creates a dashed line mesh.
  22324. * Please consider using the same method from the MeshBuilder class instead.
  22325. * 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.
  22326. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22327. * The parameter `points` is an array successive Vector3.
  22328. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22329. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22330. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22331. * 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
  22332. * When updating an instance, remember that only point positions can change, not the number of points.
  22333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22334. */
  22335. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22336. var options = {
  22337. points: points,
  22338. dashSize: dashSize,
  22339. gapSize: gapSize,
  22340. dashNb: dashNb,
  22341. updatable: updatable,
  22342. instance: instance
  22343. };
  22344. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22345. };
  22346. /**
  22347. * Creates a polygon mesh.
  22348. * Please consider using the same method from the MeshBuilder class instead.
  22349. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  22350. * 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.
  22351. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22352. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22353. * Remember you can only change the shape positions, not their number when updating a polygon.
  22354. */
  22355. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  22356. var options = {
  22357. shape: shape,
  22358. holes: holes,
  22359. updatable: updatable,
  22360. sideOrientation: sideOrientation
  22361. };
  22362. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  22363. };
  22364. /**
  22365. * Creates an extruded polygon mesh, with depth in the Y direction.
  22366. * Please consider using the same method from the MeshBuilder class instead.
  22367. */
  22368. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  22369. var options = {
  22370. shape: shape,
  22371. holes: holes,
  22372. depth: depth,
  22373. updatable: updatable,
  22374. sideOrientation: sideOrientation
  22375. };
  22376. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  22377. };
  22378. /**
  22379. * Creates an extruded shape mesh.
  22380. * 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.
  22381. * Please consider using the same method from the MeshBuilder class instead.
  22382. *
  22383. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22384. * 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
  22385. * extruded along the Z axis.
  22386. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22387. * 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.
  22388. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22389. * 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
  22390. * 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
  22391. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22392. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22393. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22394. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22395. */
  22396. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22397. var options = {
  22398. shape: shape,
  22399. path: path,
  22400. scale: scale,
  22401. rotation: rotation,
  22402. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22403. sideOrientation: sideOrientation,
  22404. instance: instance,
  22405. updatable: updatable
  22406. };
  22407. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22408. };
  22409. /**
  22410. * Creates an custom extruded shape mesh.
  22411. * 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.
  22412. * Please consider using the same method from the MeshBuilder class instead.
  22413. *
  22414. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22415. * 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
  22416. * extruded along the Z axis.
  22417. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22418. * 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
  22419. * and the distance of this point from the begining of the path :
  22420. * ```javascript
  22421. * var rotationFunction = function(i, distance) {
  22422. * // do things
  22423. * return rotationValue; }
  22424. * ```
  22425. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22426. * 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
  22427. * and the distance of this point from the begining of the path :
  22428. * ```javascript
  22429. * var scaleFunction = function(i, distance) {
  22430. * // do things
  22431. * return scaleValue;}
  22432. * ```
  22433. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22434. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22435. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22436. * 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
  22437. * 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
  22438. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22442. */
  22443. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22444. var options = {
  22445. shape: shape,
  22446. path: path,
  22447. scaleFunction: scaleFunction,
  22448. rotationFunction: rotationFunction,
  22449. ribbonCloseArray: ribbonCloseArray,
  22450. ribbonClosePath: ribbonClosePath,
  22451. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22452. sideOrientation: sideOrientation,
  22453. instance: instance,
  22454. updatable: updatable
  22455. };
  22456. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22457. };
  22458. /**
  22459. * Creates lathe mesh.
  22460. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22461. * Please consider using the same method from the MeshBuilder class instead.
  22462. * 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
  22463. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22464. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22465. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22467. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22469. */
  22470. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22471. var options = {
  22472. shape: shape,
  22473. radius: radius,
  22474. tessellation: tessellation,
  22475. sideOrientation: sideOrientation,
  22476. updatable: updatable
  22477. };
  22478. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22479. };
  22480. /**
  22481. * Creates a plane mesh.
  22482. * Please consider using the same method from the MeshBuilder class instead.
  22483. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22484. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22485. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22487. */
  22488. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22489. var options = {
  22490. size: size,
  22491. width: size,
  22492. height: size,
  22493. sideOrientation: sideOrientation,
  22494. updatable: updatable
  22495. };
  22496. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22497. };
  22498. /**
  22499. * Creates a ground mesh.
  22500. * Please consider using the same method from the MeshBuilder class instead.
  22501. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22502. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22504. */
  22505. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22506. var options = {
  22507. width: width,
  22508. height: height,
  22509. subdivisions: subdivisions,
  22510. updatable: updatable
  22511. };
  22512. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22513. };
  22514. /**
  22515. * Creates a tiled ground mesh.
  22516. * Please consider using the same method from the MeshBuilder class instead.
  22517. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22518. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22519. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22520. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22521. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22522. * numbers of subdivisions on the ground width and height of each tile.
  22523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22524. */
  22525. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22526. var options = {
  22527. xmin: xmin,
  22528. zmin: zmin,
  22529. xmax: xmax,
  22530. zmax: zmax,
  22531. subdivisions: subdivisions,
  22532. precision: precision,
  22533. updatable: updatable
  22534. };
  22535. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22536. };
  22537. /**
  22538. * Creates a ground mesh from a height map.
  22539. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22540. * Please consider using the same method from the MeshBuilder class instead.
  22541. * The parameter `url` sets the URL of the height map image resource.
  22542. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22543. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22544. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22545. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22546. * 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).
  22547. * This function is passed the newly built mesh :
  22548. * ```javascript
  22549. * function(mesh) { // do things
  22550. * return; }
  22551. * ```
  22552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22553. */
  22554. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22555. var options = {
  22556. width: width,
  22557. height: height,
  22558. subdivisions: subdivisions,
  22559. minHeight: minHeight,
  22560. maxHeight: maxHeight,
  22561. updatable: updatable,
  22562. onReady: onReady
  22563. };
  22564. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22565. };
  22566. /**
  22567. * Creates a tube mesh.
  22568. * 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.
  22569. * Please consider using the same method from the MeshBuilder class instead.
  22570. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22571. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22572. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22573. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22574. * 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.
  22575. * It must return a radius value (positive float) :
  22576. * ```javascript
  22577. * var radiusFunction = function(i, distance) {
  22578. * // do things
  22579. * return radius; }
  22580. * ```
  22581. * 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
  22582. * 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
  22583. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22586. */
  22587. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22588. var options = {
  22589. path: path,
  22590. radius: radius,
  22591. tessellation: tessellation,
  22592. radiusFunction: radiusFunction,
  22593. arc: 1,
  22594. cap: cap,
  22595. updatable: updatable,
  22596. sideOrientation: sideOrientation,
  22597. instance: instance
  22598. };
  22599. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22600. };
  22601. /**
  22602. * Creates a polyhedron mesh.
  22603. * Please consider using the same method from the MeshBuilder class instead.
  22604. * 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
  22605. * to choose the wanted type.
  22606. * The parameter `size` (positive float, default 1) sets the polygon size.
  22607. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22608. * 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`.
  22609. * 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
  22610. * 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)`).
  22611. * 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
  22612. * 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.
  22613. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22614. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22616. */
  22617. Mesh.CreatePolyhedron = function (name, options, scene) {
  22618. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22619. };
  22620. /**
  22621. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22622. * Please consider using the same method from the MeshBuilder class instead.
  22623. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22624. * 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`).
  22625. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22626. * 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.
  22627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22630. */
  22631. Mesh.CreateIcoSphere = function (name, options, scene) {
  22632. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22633. };
  22634. /**
  22635. * Creates a decal mesh.
  22636. * Please consider using the same method from the MeshBuilder class instead.
  22637. * 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.
  22638. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22639. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22640. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22641. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22642. */
  22643. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22644. var options = {
  22645. position: position,
  22646. normal: normal,
  22647. size: size,
  22648. angle: angle
  22649. };
  22650. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22651. };
  22652. // Skeletons
  22653. /**
  22654. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22655. */
  22656. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22657. var source;
  22658. if (!this._sourcePositions) {
  22659. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22660. this._sourcePositions = new Float32Array(source);
  22661. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22662. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22663. }
  22664. }
  22665. return this._sourcePositions;
  22666. };
  22667. /**
  22668. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22669. */
  22670. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22671. var source;
  22672. if (!this._sourceNormals) {
  22673. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22674. this._sourceNormals = new Float32Array(source);
  22675. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22676. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22677. }
  22678. }
  22679. return this._sourceNormals;
  22680. };
  22681. /**
  22682. * Updates the vertex buffer by applying transformation from the bones.
  22683. * Returns the Mesh.
  22684. *
  22685. * @param {skeleton} skeleton to apply
  22686. */
  22687. Mesh.prototype.applySkeleton = function (skeleton) {
  22688. if (!this.geometry) {
  22689. return this;
  22690. }
  22691. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22692. return this;
  22693. }
  22694. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22695. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22696. return this;
  22697. }
  22698. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22699. return this;
  22700. }
  22701. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22702. return this;
  22703. }
  22704. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22705. return this;
  22706. }
  22707. if (!this._sourcePositions) {
  22708. var submeshes = this.subMeshes.slice();
  22709. this.setPositionsForCPUSkinning();
  22710. this.subMeshes = submeshes;
  22711. }
  22712. if (!this._sourceNormals) {
  22713. this.setNormalsForCPUSkinning();
  22714. }
  22715. // positionsData checks for not being Float32Array will only pass at most once
  22716. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22717. if (!(positionsData instanceof Float32Array)) {
  22718. positionsData = new Float32Array(positionsData);
  22719. }
  22720. // normalsData checks for not being Float32Array will only pass at most once
  22721. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22722. if (!(normalsData instanceof Float32Array)) {
  22723. normalsData = new Float32Array(normalsData);
  22724. }
  22725. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22726. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22727. var needExtras = this.numBoneInfluencers > 4;
  22728. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22729. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22730. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22731. var tempVector3 = BABYLON.Vector3.Zero();
  22732. var finalMatrix = new BABYLON.Matrix();
  22733. var tempMatrix = new BABYLON.Matrix();
  22734. var matWeightIdx = 0;
  22735. var inf;
  22736. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22737. var weight;
  22738. for (inf = 0; inf < 4; inf++) {
  22739. weight = matricesWeightsData[matWeightIdx + inf];
  22740. if (weight > 0) {
  22741. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22742. finalMatrix.addToSelf(tempMatrix);
  22743. }
  22744. else
  22745. break;
  22746. }
  22747. if (needExtras) {
  22748. for (inf = 0; inf < 4; inf++) {
  22749. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22750. if (weight > 0) {
  22751. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22752. finalMatrix.addToSelf(tempMatrix);
  22753. }
  22754. else
  22755. break;
  22756. }
  22757. }
  22758. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22759. tempVector3.toArray(positionsData, index);
  22760. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22761. tempVector3.toArray(normalsData, index);
  22762. finalMatrix.reset();
  22763. }
  22764. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22765. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22766. return this;
  22767. };
  22768. // Tools
  22769. /**
  22770. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22771. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22772. */
  22773. Mesh.MinMax = function (meshes) {
  22774. var minVector = null;
  22775. var maxVector = null;
  22776. meshes.forEach(function (mesh, index, array) {
  22777. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22778. if (!minVector) {
  22779. minVector = boundingBox.minimumWorld;
  22780. maxVector = boundingBox.maximumWorld;
  22781. }
  22782. else {
  22783. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22784. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22785. }
  22786. });
  22787. return {
  22788. min: minVector,
  22789. max: maxVector
  22790. };
  22791. };
  22792. /**
  22793. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22794. */
  22795. Mesh.Center = function (meshesOrMinMaxVector) {
  22796. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22797. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22798. };
  22799. /**
  22800. * Merge the array of meshes into a single mesh for performance reasons.
  22801. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22802. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22803. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22804. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22805. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22806. */
  22807. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22808. if (disposeSource === void 0) { disposeSource = true; }
  22809. var index;
  22810. if (!allow32BitsIndices) {
  22811. var totalVertices = 0;
  22812. // Counting vertices
  22813. for (index = 0; index < meshes.length; index++) {
  22814. if (meshes[index]) {
  22815. totalVertices += meshes[index].getTotalVertices();
  22816. if (totalVertices > 65536) {
  22817. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22818. return null;
  22819. }
  22820. }
  22821. }
  22822. }
  22823. // Merge
  22824. var vertexData;
  22825. var otherVertexData;
  22826. var indiceArray = new Array();
  22827. var source;
  22828. for (index = 0; index < meshes.length; index++) {
  22829. if (meshes[index]) {
  22830. meshes[index].computeWorldMatrix(true);
  22831. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22832. otherVertexData.transform(meshes[index].getWorldMatrix());
  22833. if (vertexData) {
  22834. vertexData.merge(otherVertexData);
  22835. }
  22836. else {
  22837. vertexData = otherVertexData;
  22838. source = meshes[index];
  22839. }
  22840. if (subdivideWithSubMeshes) {
  22841. indiceArray.push(meshes[index].getTotalIndices());
  22842. }
  22843. }
  22844. }
  22845. if (!meshSubclass) {
  22846. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22847. }
  22848. vertexData.applyToMesh(meshSubclass);
  22849. // Setting properties
  22850. meshSubclass.material = source.material;
  22851. meshSubclass.checkCollisions = source.checkCollisions;
  22852. // Cleaning
  22853. if (disposeSource) {
  22854. for (index = 0; index < meshes.length; index++) {
  22855. if (meshes[index]) {
  22856. meshes[index].dispose();
  22857. }
  22858. }
  22859. }
  22860. // Subdivide
  22861. if (subdivideWithSubMeshes) {
  22862. //-- Suppresions du submesh global
  22863. meshSubclass.releaseSubMeshes();
  22864. index = 0;
  22865. var offset = 0;
  22866. //-- aplique la subdivision en fonction du tableau d'indices
  22867. while (index < indiceArray.length) {
  22868. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22869. offset += indiceArray[index];
  22870. index++;
  22871. }
  22872. }
  22873. return meshSubclass;
  22874. };
  22875. return Mesh;
  22876. }(BABYLON.AbstractMesh));
  22877. // Consts
  22878. Mesh._FRONTSIDE = 0;
  22879. Mesh._BACKSIDE = 1;
  22880. Mesh._DOUBLESIDE = 2;
  22881. Mesh._DEFAULTSIDE = 0;
  22882. Mesh._NO_CAP = 0;
  22883. Mesh._CAP_START = 1;
  22884. Mesh._CAP_END = 2;
  22885. Mesh._CAP_ALL = 3;
  22886. BABYLON.Mesh = Mesh;
  22887. })(BABYLON || (BABYLON = {}));
  22888. //# sourceMappingURL=babylon.mesh.js.map
  22889. var BABYLON;
  22890. (function (BABYLON) {
  22891. var BaseSubMesh = (function () {
  22892. function BaseSubMesh() {
  22893. }
  22894. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22895. get: function () {
  22896. return this._materialEffect;
  22897. },
  22898. enumerable: true,
  22899. configurable: true
  22900. });
  22901. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22902. if (this._materialEffect === effect) {
  22903. if (!effect) {
  22904. this._materialDefines = undefined;
  22905. }
  22906. return;
  22907. }
  22908. this._materialDefines = defines;
  22909. this._materialEffect = effect;
  22910. };
  22911. return BaseSubMesh;
  22912. }());
  22913. BABYLON.BaseSubMesh = BaseSubMesh;
  22914. var SubMesh = (function (_super) {
  22915. __extends(SubMesh, _super);
  22916. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22917. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22918. var _this = _super.call(this) || this;
  22919. _this.materialIndex = materialIndex;
  22920. _this.verticesStart = verticesStart;
  22921. _this.verticesCount = verticesCount;
  22922. _this.indexStart = indexStart;
  22923. _this.indexCount = indexCount;
  22924. _this._renderId = 0;
  22925. _this._mesh = mesh;
  22926. _this._renderingMesh = renderingMesh || mesh;
  22927. mesh.subMeshes.push(_this);
  22928. _this._trianglePlanes = [];
  22929. _this._id = mesh.subMeshes.length - 1;
  22930. if (createBoundingBox) {
  22931. _this.refreshBoundingInfo();
  22932. mesh.computeWorldMatrix(true);
  22933. }
  22934. return _this;
  22935. }
  22936. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22937. get: function () {
  22938. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22939. },
  22940. enumerable: true,
  22941. configurable: true
  22942. });
  22943. /**
  22944. * Returns the submesh BoudingInfo object.
  22945. */
  22946. SubMesh.prototype.getBoundingInfo = function () {
  22947. if (this.IsGlobal) {
  22948. return this._mesh.getBoundingInfo();
  22949. }
  22950. return this._boundingInfo;
  22951. };
  22952. /**
  22953. * Sets the submesh BoundingInfo.
  22954. * Return the SubMesh.
  22955. */
  22956. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22957. this._boundingInfo = boundingInfo;
  22958. return this;
  22959. };
  22960. /**
  22961. * Returns the mesh of the current submesh.
  22962. */
  22963. SubMesh.prototype.getMesh = function () {
  22964. return this._mesh;
  22965. };
  22966. /**
  22967. * Returns the rendering mesh of the submesh.
  22968. */
  22969. SubMesh.prototype.getRenderingMesh = function () {
  22970. return this._renderingMesh;
  22971. };
  22972. /**
  22973. * Returns the submesh material.
  22974. */
  22975. SubMesh.prototype.getMaterial = function () {
  22976. var rootMaterial = this._renderingMesh.material;
  22977. if (rootMaterial && rootMaterial.getSubMaterial) {
  22978. var multiMaterial = rootMaterial;
  22979. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22980. if (this._currentMaterial !== effectiveMaterial) {
  22981. this._currentMaterial = effectiveMaterial;
  22982. this._materialDefines = undefined;
  22983. }
  22984. return effectiveMaterial;
  22985. }
  22986. if (!rootMaterial) {
  22987. return this._mesh.getScene().defaultMaterial;
  22988. }
  22989. return rootMaterial;
  22990. };
  22991. // Methods
  22992. /**
  22993. * Sets a new updated BoundingInfo object to the submesh.
  22994. * Returns the SubMesh.
  22995. */
  22996. SubMesh.prototype.refreshBoundingInfo = function () {
  22997. this._lastColliderWorldVertices = null;
  22998. if (this.IsGlobal) {
  22999. return;
  23000. }
  23001. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23002. if (!data) {
  23003. this._boundingInfo = this._mesh._boundingInfo;
  23004. return;
  23005. }
  23006. var indices = this._renderingMesh.getIndices();
  23007. var extend;
  23008. //is this the only submesh?
  23009. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23010. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23011. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23012. }
  23013. else {
  23014. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23015. }
  23016. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23017. return this;
  23018. };
  23019. SubMesh.prototype._checkCollision = function (collider) {
  23020. return this.getBoundingInfo()._checkCollision(collider);
  23021. };
  23022. /**
  23023. * Updates the submesh BoundingInfo.
  23024. * Returns the Submesh.
  23025. */
  23026. SubMesh.prototype.updateBoundingInfo = function (world) {
  23027. if (!this.getBoundingInfo()) {
  23028. this.refreshBoundingInfo();
  23029. }
  23030. this.getBoundingInfo().update(world);
  23031. return this;
  23032. };
  23033. /**
  23034. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23035. * Boolean returned.
  23036. */
  23037. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23038. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23039. };
  23040. /**
  23041. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23042. * Boolean returned.
  23043. */
  23044. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23045. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23046. };
  23047. /**
  23048. * Renders the submesh.
  23049. * Returns it.
  23050. */
  23051. SubMesh.prototype.render = function (enableAlphaMode) {
  23052. this._renderingMesh.render(this, enableAlphaMode);
  23053. return this;
  23054. };
  23055. /**
  23056. * Returns a new Index Buffer.
  23057. * Type returned : WebGLBuffer.
  23058. */
  23059. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23060. if (!this._linesIndexBuffer) {
  23061. var linesIndices = [];
  23062. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23063. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23064. }
  23065. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23066. this.linesIndexCount = linesIndices.length;
  23067. }
  23068. return this._linesIndexBuffer;
  23069. };
  23070. /**
  23071. * True is the passed Ray intersects the submesh bounding box.
  23072. * Boolean returned.
  23073. */
  23074. SubMesh.prototype.canIntersects = function (ray) {
  23075. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23076. };
  23077. /**
  23078. * Returns an object IntersectionInfo.
  23079. */
  23080. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23081. var intersectInfo = null;
  23082. // LineMesh first as it's also a Mesh...
  23083. if (this._mesh instanceof BABYLON.LinesMesh) {
  23084. var lineMesh = this._mesh;
  23085. // Line test
  23086. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23087. var p0 = positions[indices[index]];
  23088. var p1 = positions[indices[index + 1]];
  23089. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23090. if (length < 0) {
  23091. continue;
  23092. }
  23093. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23094. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23095. if (fastCheck) {
  23096. break;
  23097. }
  23098. }
  23099. }
  23100. }
  23101. else {
  23102. // Triangles test
  23103. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23104. var p0 = positions[indices[index]];
  23105. var p1 = positions[indices[index + 1]];
  23106. var p2 = positions[indices[index + 2]];
  23107. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23108. if (currentIntersectInfo) {
  23109. if (currentIntersectInfo.distance < 0) {
  23110. continue;
  23111. }
  23112. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23113. intersectInfo = currentIntersectInfo;
  23114. intersectInfo.faceId = index / 3;
  23115. if (fastCheck) {
  23116. break;
  23117. }
  23118. }
  23119. }
  23120. }
  23121. }
  23122. return intersectInfo;
  23123. };
  23124. // Clone
  23125. /**
  23126. * Creates a new Submesh from the passed Mesh.
  23127. */
  23128. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23129. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23130. if (!this.IsGlobal) {
  23131. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23132. }
  23133. return result;
  23134. };
  23135. // Dispose
  23136. /**
  23137. * Disposes the Submesh.
  23138. * Returns nothing.
  23139. */
  23140. SubMesh.prototype.dispose = function () {
  23141. if (this._linesIndexBuffer) {
  23142. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23143. this._linesIndexBuffer = null;
  23144. }
  23145. // Remove from mesh
  23146. var index = this._mesh.subMeshes.indexOf(this);
  23147. this._mesh.subMeshes.splice(index, 1);
  23148. };
  23149. // Statics
  23150. /**
  23151. * Creates a new Submesh from the passed parameters :
  23152. * - materialIndex (integer) : the index of the main mesh material.
  23153. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23154. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23155. * - mesh (Mesh) : the main mesh to create the submesh from.
  23156. * - renderingMesh (optional Mesh) : rendering mesh.
  23157. */
  23158. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23159. var minVertexIndex = Number.MAX_VALUE;
  23160. var maxVertexIndex = -Number.MAX_VALUE;
  23161. renderingMesh = renderingMesh || mesh;
  23162. var indices = renderingMesh.getIndices();
  23163. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23164. var vertexIndex = indices[index];
  23165. if (vertexIndex < minVertexIndex)
  23166. minVertexIndex = vertexIndex;
  23167. if (vertexIndex > maxVertexIndex)
  23168. maxVertexIndex = vertexIndex;
  23169. }
  23170. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23171. };
  23172. return SubMesh;
  23173. }(BaseSubMesh));
  23174. BABYLON.SubMesh = SubMesh;
  23175. })(BABYLON || (BABYLON = {}));
  23176. //# sourceMappingURL=babylon.subMesh.js.map
  23177. var BABYLON;
  23178. (function (BABYLON) {
  23179. var EffectFallbacks = (function () {
  23180. function EffectFallbacks() {
  23181. this._defines = {};
  23182. this._currentRank = 32;
  23183. this._maxRank = -1;
  23184. }
  23185. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23186. if (!this._defines[rank]) {
  23187. if (rank < this._currentRank) {
  23188. this._currentRank = rank;
  23189. }
  23190. if (rank > this._maxRank) {
  23191. this._maxRank = rank;
  23192. }
  23193. this._defines[rank] = new Array();
  23194. }
  23195. this._defines[rank].push(define);
  23196. };
  23197. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23198. this._meshRank = rank;
  23199. this._mesh = mesh;
  23200. if (rank < this._currentRank) {
  23201. this._currentRank = rank;
  23202. }
  23203. if (rank > this._maxRank) {
  23204. this._maxRank = rank;
  23205. }
  23206. };
  23207. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23208. get: function () {
  23209. return this._currentRank <= this._maxRank;
  23210. },
  23211. enumerable: true,
  23212. configurable: true
  23213. });
  23214. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23215. // First we try to switch to CPU skinning
  23216. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23217. this._mesh.computeBonesUsingShaders = false;
  23218. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23219. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23220. var scene = this._mesh.getScene();
  23221. for (var index = 0; index < scene.meshes.length; index++) {
  23222. var otherMesh = scene.meshes[index];
  23223. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23224. otherMesh.computeBonesUsingShaders = false;
  23225. }
  23226. }
  23227. }
  23228. else {
  23229. var currentFallbacks = this._defines[this._currentRank];
  23230. if (currentFallbacks) {
  23231. for (var index = 0; index < currentFallbacks.length; index++) {
  23232. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23233. }
  23234. }
  23235. this._currentRank++;
  23236. }
  23237. return currentDefines;
  23238. };
  23239. return EffectFallbacks;
  23240. }());
  23241. BABYLON.EffectFallbacks = EffectFallbacks;
  23242. var EffectCreationOptions = (function () {
  23243. function EffectCreationOptions() {
  23244. }
  23245. return EffectCreationOptions;
  23246. }());
  23247. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23248. var Effect = (function () {
  23249. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23250. var _this = this;
  23251. this.uniqueId = 0;
  23252. this.onCompileObservable = new BABYLON.Observable();
  23253. this.onErrorObservable = new BABYLON.Observable();
  23254. this.onBindObservable = new BABYLON.Observable();
  23255. this._uniformBuffersNames = {};
  23256. this._isReady = false;
  23257. this._compilationError = "";
  23258. this._valueCache = {};
  23259. this.name = baseName;
  23260. if (attributesNamesOrOptions.attributes) {
  23261. var options = attributesNamesOrOptions;
  23262. this._engine = uniformsNamesOrEngine;
  23263. this._attributesNames = options.attributes;
  23264. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  23265. this._samplers = options.samplers;
  23266. this.defines = options.defines;
  23267. this.onError = options.onError;
  23268. this.onCompiled = options.onCompiled;
  23269. this._fallbacks = options.fallbacks;
  23270. this._indexParameters = options.indexParameters;
  23271. if (options.uniformBuffersNames) {
  23272. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  23273. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  23274. }
  23275. }
  23276. }
  23277. else {
  23278. this._engine = engine;
  23279. this.defines = defines;
  23280. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  23281. this._samplers = samplers;
  23282. this._attributesNames = attributesNamesOrOptions;
  23283. this.onError = onError;
  23284. this.onCompiled = onCompiled;
  23285. this._indexParameters = indexParameters;
  23286. this._fallbacks = fallbacks;
  23287. }
  23288. this.uniqueId = Effect._uniqueIdSeed++;
  23289. var vertexSource;
  23290. var fragmentSource;
  23291. if (baseName.vertexElement) {
  23292. vertexSource = document.getElementById(baseName.vertexElement);
  23293. if (!vertexSource) {
  23294. vertexSource = baseName.vertexElement;
  23295. }
  23296. }
  23297. else {
  23298. vertexSource = baseName.vertex || baseName;
  23299. }
  23300. if (baseName.fragmentElement) {
  23301. fragmentSource = document.getElementById(baseName.fragmentElement);
  23302. if (!fragmentSource) {
  23303. fragmentSource = baseName.fragmentElement;
  23304. }
  23305. }
  23306. else {
  23307. fragmentSource = baseName.fragment || baseName;
  23308. }
  23309. this._loadVertexShader(vertexSource, function (vertexCode) {
  23310. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23311. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  23312. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23313. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23314. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  23315. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  23316. });
  23317. });
  23318. });
  23319. });
  23320. });
  23321. });
  23322. }
  23323. Object.defineProperty(Effect.prototype, "key", {
  23324. get: function () {
  23325. return this._key;
  23326. },
  23327. enumerable: true,
  23328. configurable: true
  23329. });
  23330. // Properties
  23331. Effect.prototype.isReady = function () {
  23332. return this._isReady;
  23333. };
  23334. Effect.prototype.getEngine = function () {
  23335. return this._engine;
  23336. };
  23337. Effect.prototype.getProgram = function () {
  23338. return this._program;
  23339. };
  23340. Effect.prototype.getAttributesNames = function () {
  23341. return this._attributesNames;
  23342. };
  23343. Effect.prototype.getAttributeLocation = function (index) {
  23344. return this._attributes[index];
  23345. };
  23346. Effect.prototype.getAttributeLocationByName = function (name) {
  23347. var index = this._attributesNames.indexOf(name);
  23348. return this._attributes[index];
  23349. };
  23350. Effect.prototype.getAttributesCount = function () {
  23351. return this._attributes.length;
  23352. };
  23353. Effect.prototype.getUniformIndex = function (uniformName) {
  23354. return this._uniformsNames.indexOf(uniformName);
  23355. };
  23356. Effect.prototype.getUniform = function (uniformName) {
  23357. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23358. };
  23359. Effect.prototype.getSamplers = function () {
  23360. return this._samplers;
  23361. };
  23362. Effect.prototype.getCompilationError = function () {
  23363. return this._compilationError;
  23364. };
  23365. Effect.prototype.getVertexShaderSource = function () {
  23366. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  23367. };
  23368. Effect.prototype.getFragmentShaderSource = function () {
  23369. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  23370. };
  23371. // Methods
  23372. Effect.prototype.executeWhenCompiled = function (func) {
  23373. var _this = this;
  23374. if (this.isReady()) {
  23375. func(this);
  23376. return;
  23377. }
  23378. var observer = this.onCompileObservable.add(function (effect) {
  23379. _this.onCompileObservable.remove(observer);
  23380. func(effect);
  23381. });
  23382. };
  23383. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23384. // DOM element ?
  23385. if (vertex instanceof HTMLElement) {
  23386. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23387. callback(vertexCode);
  23388. return;
  23389. }
  23390. // Base64 encoded ?
  23391. if (vertex.substr(0, 7) === "base64:") {
  23392. var vertexBinary = window.atob(vertex.substr(7));
  23393. callback(vertexBinary);
  23394. return;
  23395. }
  23396. // Is in local store ?
  23397. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23398. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23399. return;
  23400. }
  23401. var vertexShaderUrl;
  23402. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23403. vertexShaderUrl = vertex;
  23404. }
  23405. else {
  23406. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23407. }
  23408. // Vertex shader
  23409. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23410. };
  23411. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23412. // DOM element ?
  23413. if (fragment instanceof HTMLElement) {
  23414. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23415. callback(fragmentCode);
  23416. return;
  23417. }
  23418. // Base64 encoded ?
  23419. if (fragment.substr(0, 7) === "base64:") {
  23420. var fragmentBinary = window.atob(fragment.substr(7));
  23421. callback(fragmentBinary);
  23422. return;
  23423. }
  23424. // Is in local store ?
  23425. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23426. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23427. return;
  23428. }
  23429. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23430. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23431. return;
  23432. }
  23433. var fragmentShaderUrl;
  23434. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23435. fragmentShaderUrl = fragment;
  23436. }
  23437. else {
  23438. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23439. }
  23440. // Fragment shader
  23441. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23442. };
  23443. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  23444. // Rebuild shaders source code
  23445. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  23446. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  23447. vertexCode = prefix + vertexCode;
  23448. fragmentCode = prefix + fragmentCode;
  23449. // Number lines of shaders source code
  23450. var i = 2;
  23451. var regex = /\n/gm;
  23452. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23453. i = 2;
  23454. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23455. // Dump shaders name and formatted source code
  23456. if (this.name.vertexElement) {
  23457. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  23458. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  23459. }
  23460. else if (this.name.vertex) {
  23461. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  23462. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  23463. }
  23464. else {
  23465. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  23466. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  23467. }
  23468. };
  23469. ;
  23470. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  23471. var preparedSourceCode = this._processPrecision(sourceCode);
  23472. if (this._engine.webGLVersion == 1) {
  23473. callback(preparedSourceCode);
  23474. return;
  23475. }
  23476. // Already converted
  23477. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  23478. callback(preparedSourceCode.replace("#version 300 es", ""));
  23479. return;
  23480. }
  23481. // Remove extensions
  23482. // #extension GL_OES_standard_derivatives : enable
  23483. // #extension GL_EXT_shader_texture_lod : enable
  23484. // #extension GL_EXT_frag_depth : enable
  23485. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  23486. var result = preparedSourceCode.replace(regex, "");
  23487. // Migrate to GLSL v300
  23488. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  23489. result = result.replace(/attribute[ \t]/g, "in ");
  23490. result = result.replace(/[ \t]attribute/g, " in");
  23491. if (isFragment) {
  23492. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  23493. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  23494. result = result.replace(/texture2D\(/g, "texture(");
  23495. result = result.replace(/textureCube\(/g, "texture(");
  23496. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  23497. result = result.replace(/gl_FragColor/g, "glFragColor");
  23498. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  23499. }
  23500. callback(result);
  23501. };
  23502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23503. var _this = this;
  23504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23505. var match = regex.exec(sourceCode);
  23506. var returnValue = new String(sourceCode);
  23507. while (match != null) {
  23508. var includeFile = match[1];
  23509. // Uniform declaration
  23510. if (includeFile.indexOf("__decl__") !== -1) {
  23511. includeFile = includeFile.replace(/__decl__/, "");
  23512. if (this._engine.webGLVersion != 1) {
  23513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  23514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  23515. }
  23516. includeFile = includeFile + "Declaration";
  23517. }
  23518. if (Effect.IncludesShadersStore[includeFile]) {
  23519. // Substitution
  23520. var includeContent = Effect.IncludesShadersStore[includeFile];
  23521. if (match[2]) {
  23522. var splits = match[3].split(",");
  23523. for (var index = 0; index < splits.length; index += 2) {
  23524. var source = new RegExp(splits[index], "g");
  23525. var dest = splits[index + 1];
  23526. includeContent = includeContent.replace(source, dest);
  23527. }
  23528. }
  23529. if (match[4]) {
  23530. var indexString = match[5];
  23531. if (indexString.indexOf("..") !== -1) {
  23532. var indexSplits = indexString.split("..");
  23533. var minIndex = parseInt(indexSplits[0]);
  23534. var maxIndex = parseInt(indexSplits[1]);
  23535. var sourceIncludeContent = includeContent.slice(0);
  23536. includeContent = "";
  23537. if (isNaN(maxIndex)) {
  23538. maxIndex = this._indexParameters[indexSplits[1]];
  23539. }
  23540. for (var i = minIndex; i < maxIndex; i++) {
  23541. if (this._engine.webGLVersion === 1) {
  23542. // Ubo replacement
  23543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23544. return p1 + "{X}";
  23545. });
  23546. }
  23547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23548. }
  23549. }
  23550. else {
  23551. if (this._engine.webGLVersion === 1) {
  23552. // Ubo replacement
  23553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23554. return p1 + "{X}";
  23555. });
  23556. }
  23557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23558. }
  23559. }
  23560. // Replace
  23561. returnValue = returnValue.replace(match[0], includeContent);
  23562. }
  23563. else {
  23564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23565. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23566. Effect.IncludesShadersStore[includeFile] = fileContent;
  23567. _this._processIncludes(returnValue, callback);
  23568. });
  23569. return;
  23570. }
  23571. match = regex.exec(sourceCode);
  23572. }
  23573. callback(returnValue);
  23574. };
  23575. Effect.prototype._processPrecision = function (source) {
  23576. if (source.indexOf("precision highp float") === -1) {
  23577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23578. source = "precision mediump float;\n" + source;
  23579. }
  23580. else {
  23581. source = "precision highp float;\n" + source;
  23582. }
  23583. }
  23584. else {
  23585. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23586. source = source.replace("precision highp float", "precision mediump float");
  23587. }
  23588. }
  23589. return source;
  23590. };
  23591. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23592. try {
  23593. var engine = this._engine;
  23594. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23595. if (engine.webGLVersion > 1) {
  23596. for (var name in this._uniformBuffersNames) {
  23597. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23598. }
  23599. }
  23600. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23601. this._attributes = engine.getAttributes(this._program, attributesNames);
  23602. var index;
  23603. for (index = 0; index < this._samplers.length; index++) {
  23604. var sampler = this.getUniform(this._samplers[index]);
  23605. if (sampler == null) {
  23606. this._samplers.splice(index, 1);
  23607. index--;
  23608. }
  23609. }
  23610. engine.bindSamplers(this);
  23611. this._compilationError = "";
  23612. this._isReady = true;
  23613. if (this.onCompiled) {
  23614. this.onCompiled(this);
  23615. }
  23616. this.onCompileObservable.notifyObservers(this);
  23617. }
  23618. catch (e) {
  23619. this._compilationError = e.message;
  23620. // Let's go through fallbacks then
  23621. BABYLON.Tools.Error("Unable to compile effect:");
  23622. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23623. return " " + uniform;
  23624. }));
  23625. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23626. return " " + attribute;
  23627. }));
  23628. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23629. BABYLON.Tools.Error("Error: " + this._compilationError);
  23630. if (fallbacks && fallbacks.isMoreFallbacks) {
  23631. BABYLON.Tools.Error("Trying next fallback.");
  23632. defines = fallbacks.reduce(defines);
  23633. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23634. }
  23635. else {
  23636. if (this.onError) {
  23637. this.onError(this, this._compilationError);
  23638. }
  23639. this.onErrorObservable.notifyObservers(this);
  23640. }
  23641. }
  23642. };
  23643. Object.defineProperty(Effect.prototype, "isSupported", {
  23644. get: function () {
  23645. return this._compilationError === "";
  23646. },
  23647. enumerable: true,
  23648. configurable: true
  23649. });
  23650. Effect.prototype._bindTexture = function (channel, texture) {
  23651. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23652. };
  23653. Effect.prototype.setTexture = function (channel, texture) {
  23654. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23655. };
  23656. Effect.prototype.setTextureArray = function (channel, textures) {
  23657. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23658. var initialPos = this._samplers.indexOf(channel);
  23659. for (var index = 1; index < textures.length; index++) {
  23660. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23661. }
  23662. }
  23663. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23664. };
  23665. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23666. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23667. };
  23668. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23669. var cache = this._valueCache[uniformName];
  23670. var flag = matrix.updateFlag;
  23671. if (cache !== undefined && cache === flag) {
  23672. return false;
  23673. }
  23674. this._valueCache[uniformName] = flag;
  23675. return true;
  23676. };
  23677. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23678. var cache = this._valueCache[uniformName];
  23679. if (!cache) {
  23680. cache = [x, y];
  23681. this._valueCache[uniformName] = cache;
  23682. return true;
  23683. }
  23684. var changed = false;
  23685. if (cache[0] !== x) {
  23686. cache[0] = x;
  23687. changed = true;
  23688. }
  23689. if (cache[1] !== y) {
  23690. cache[1] = y;
  23691. changed = true;
  23692. }
  23693. return changed;
  23694. };
  23695. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23696. var cache = this._valueCache[uniformName];
  23697. if (!cache) {
  23698. cache = [x, y, z];
  23699. this._valueCache[uniformName] = cache;
  23700. return true;
  23701. }
  23702. var changed = false;
  23703. if (cache[0] !== x) {
  23704. cache[0] = x;
  23705. changed = true;
  23706. }
  23707. if (cache[1] !== y) {
  23708. cache[1] = y;
  23709. changed = true;
  23710. }
  23711. if (cache[2] !== z) {
  23712. cache[2] = z;
  23713. changed = true;
  23714. }
  23715. return changed;
  23716. };
  23717. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23718. var cache = this._valueCache[uniformName];
  23719. if (!cache) {
  23720. cache = [x, y, z, w];
  23721. this._valueCache[uniformName] = cache;
  23722. return true;
  23723. }
  23724. var changed = false;
  23725. if (cache[0] !== x) {
  23726. cache[0] = x;
  23727. changed = true;
  23728. }
  23729. if (cache[1] !== y) {
  23730. cache[1] = y;
  23731. changed = true;
  23732. }
  23733. if (cache[2] !== z) {
  23734. cache[2] = z;
  23735. changed = true;
  23736. }
  23737. if (cache[3] !== w) {
  23738. cache[3] = w;
  23739. changed = true;
  23740. }
  23741. return changed;
  23742. };
  23743. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23744. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23745. return;
  23746. }
  23747. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23748. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23749. };
  23750. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23751. this._engine.bindUniformBlock(this._program, blockName, index);
  23752. };
  23753. Effect.prototype.setIntArray = function (uniformName, array) {
  23754. this._valueCache[uniformName] = null;
  23755. this._engine.setIntArray(this.getUniform(uniformName), array);
  23756. return this;
  23757. };
  23758. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23759. this._valueCache[uniformName] = null;
  23760. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23761. return this;
  23762. };
  23763. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23764. this._valueCache[uniformName] = null;
  23765. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23766. return this;
  23767. };
  23768. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23769. this._valueCache[uniformName] = null;
  23770. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23771. return this;
  23772. };
  23773. Effect.prototype.setFloatArray = function (uniformName, array) {
  23774. this._valueCache[uniformName] = null;
  23775. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23776. return this;
  23777. };
  23778. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23779. this._valueCache[uniformName] = null;
  23780. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23781. return this;
  23782. };
  23783. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23784. this._valueCache[uniformName] = null;
  23785. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23786. return this;
  23787. };
  23788. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23789. this._valueCache[uniformName] = null;
  23790. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23791. return this;
  23792. };
  23793. Effect.prototype.setArray = function (uniformName, array) {
  23794. this._valueCache[uniformName] = null;
  23795. this._engine.setArray(this.getUniform(uniformName), array);
  23796. return this;
  23797. };
  23798. Effect.prototype.setArray2 = function (uniformName, array) {
  23799. this._valueCache[uniformName] = null;
  23800. this._engine.setArray2(this.getUniform(uniformName), array);
  23801. return this;
  23802. };
  23803. Effect.prototype.setArray3 = function (uniformName, array) {
  23804. this._valueCache[uniformName] = null;
  23805. this._engine.setArray3(this.getUniform(uniformName), array);
  23806. return this;
  23807. };
  23808. Effect.prototype.setArray4 = function (uniformName, array) {
  23809. this._valueCache[uniformName] = null;
  23810. this._engine.setArray4(this.getUniform(uniformName), array);
  23811. return this;
  23812. };
  23813. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23814. if (!matrices) {
  23815. return;
  23816. }
  23817. this._valueCache[uniformName] = null;
  23818. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23819. return this;
  23820. };
  23821. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23822. if (this._cacheMatrix(uniformName, matrix)) {
  23823. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23824. }
  23825. return this;
  23826. };
  23827. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23828. this._valueCache[uniformName] = null;
  23829. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23830. return this;
  23831. };
  23832. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23833. this._valueCache[uniformName] = null;
  23834. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23835. return this;
  23836. };
  23837. Effect.prototype.setFloat = function (uniformName, value) {
  23838. var cache = this._valueCache[uniformName];
  23839. if (cache !== undefined && cache === value)
  23840. return this;
  23841. this._valueCache[uniformName] = value;
  23842. this._engine.setFloat(this.getUniform(uniformName), value);
  23843. return this;
  23844. };
  23845. Effect.prototype.setBool = function (uniformName, bool) {
  23846. var cache = this._valueCache[uniformName];
  23847. if (cache !== undefined && cache === bool)
  23848. return this;
  23849. this._valueCache[uniformName] = bool;
  23850. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23851. return this;
  23852. };
  23853. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23854. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23855. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23856. }
  23857. return this;
  23858. };
  23859. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23860. if (this._cacheFloat2(uniformName, x, y)) {
  23861. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23862. }
  23863. return this;
  23864. };
  23865. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23866. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23867. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23868. }
  23869. return this;
  23870. };
  23871. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23872. if (this._cacheFloat3(uniformName, x, y, z)) {
  23873. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23874. }
  23875. return this;
  23876. };
  23877. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23878. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23879. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23880. }
  23881. return this;
  23882. };
  23883. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23884. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23885. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23886. }
  23887. return this;
  23888. };
  23889. Effect.prototype.setColor3 = function (uniformName, color3) {
  23890. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23891. this._engine.setColor3(this.getUniform(uniformName), color3);
  23892. }
  23893. return this;
  23894. };
  23895. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23896. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23897. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23898. }
  23899. return this;
  23900. };
  23901. Effect.prototype._recombineShader = function (node) {
  23902. if (node.define) {
  23903. if (node.condition) {
  23904. var defineIndex = this.defines.indexOf("#define " + node.define);
  23905. if (defineIndex === -1) {
  23906. return null;
  23907. }
  23908. var nextComma = this.defines.indexOf("\n", defineIndex);
  23909. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23910. var condition = defineValue + node.condition;
  23911. if (!eval(condition)) {
  23912. return null;
  23913. }
  23914. }
  23915. else if (node.ndef) {
  23916. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23917. return null;
  23918. }
  23919. }
  23920. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23921. return null;
  23922. }
  23923. }
  23924. var result = "";
  23925. for (var index = 0; index < node.children.length; index++) {
  23926. var line = node.children[index];
  23927. if (line.children) {
  23928. var combined = this._recombineShader(line);
  23929. if (combined !== null) {
  23930. result += combined + "\r\n";
  23931. }
  23932. continue;
  23933. }
  23934. if (line.length > 0) {
  23935. result += line + "\r\n";
  23936. }
  23937. }
  23938. return result;
  23939. };
  23940. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23941. var root = {
  23942. children: []
  23943. };
  23944. var currentNode = root;
  23945. var lines = shaderString.split("\n");
  23946. for (var index = 0; index < lines.length; index++) {
  23947. var line = lines[index].trim();
  23948. // #ifdef
  23949. var pos = line.indexOf("#ifdef ");
  23950. if (pos !== -1) {
  23951. var define = line.substr(pos + 7);
  23952. var newNode = {
  23953. condition: null,
  23954. ndef: false,
  23955. define: define,
  23956. children: [],
  23957. parent: currentNode
  23958. };
  23959. currentNode.children.push(newNode);
  23960. currentNode = newNode;
  23961. continue;
  23962. }
  23963. // #ifndef
  23964. var pos = line.indexOf("#ifndef ");
  23965. if (pos !== -1) {
  23966. var define = line.substr(pos + 8);
  23967. newNode = {
  23968. condition: null,
  23969. define: define,
  23970. ndef: true,
  23971. children: [],
  23972. parent: currentNode
  23973. };
  23974. currentNode.children.push(newNode);
  23975. currentNode = newNode;
  23976. continue;
  23977. }
  23978. // #if
  23979. var pos = line.indexOf("#if ");
  23980. if (pos !== -1) {
  23981. var define = line.substr(pos + 4).trim();
  23982. var conditionPos = define.indexOf(" ");
  23983. newNode = {
  23984. condition: define.substr(conditionPos + 1),
  23985. define: define.substr(0, conditionPos),
  23986. ndef: false,
  23987. children: [],
  23988. parent: currentNode
  23989. };
  23990. currentNode.children.push(newNode);
  23991. currentNode = newNode;
  23992. continue;
  23993. }
  23994. // #endif
  23995. pos = line.indexOf("#endif");
  23996. if (pos !== -1) {
  23997. currentNode = currentNode.parent;
  23998. continue;
  23999. }
  24000. currentNode.children.push(line);
  24001. }
  24002. // Recombine
  24003. return this._recombineShader(root);
  24004. };
  24005. return Effect;
  24006. }());
  24007. Effect._uniqueIdSeed = 0;
  24008. Effect._baseCache = {};
  24009. // Statics
  24010. Effect.ShadersStore = {};
  24011. Effect.IncludesShadersStore = {};
  24012. BABYLON.Effect = Effect;
  24013. })(BABYLON || (BABYLON = {}));
  24014. //# sourceMappingURL=babylon.effect.js.map
  24015. var BABYLON;
  24016. (function (BABYLON) {
  24017. var MaterialHelper = (function () {
  24018. function MaterialHelper() {
  24019. }
  24020. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24021. defines._needUVs = true;
  24022. defines[key] = true;
  24023. if (texture.getTextureMatrix().isIdentity(true)) {
  24024. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24025. if (texture.coordinatesIndex === 0) {
  24026. defines["MAINUV1"] = true;
  24027. }
  24028. else {
  24029. defines["MAINUV2"] = true;
  24030. }
  24031. }
  24032. else {
  24033. defines[key + "DIRECTUV"] = 0;
  24034. }
  24035. };
  24036. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24037. var matrix = texture.getTextureMatrix();
  24038. if (!matrix.isIdentity(true)) {
  24039. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24040. }
  24041. };
  24042. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24043. if (defines._areMiscDirty) {
  24044. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24045. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24046. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24047. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24048. }
  24049. };
  24050. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24051. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24052. var changed = false;
  24053. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24054. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24055. changed = true;
  24056. }
  24057. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24058. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24059. changed = true;
  24060. }
  24061. if (defines["INSTANCES"] !== useInstances) {
  24062. defines["INSTANCES"] = useInstances;
  24063. changed = true;
  24064. }
  24065. if (changed) {
  24066. defines.markAsUnprocessed();
  24067. }
  24068. };
  24069. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24070. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24071. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24072. return false;
  24073. }
  24074. defines._normals = defines._needNormals;
  24075. defines._uvs = defines._needUVs;
  24076. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24077. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24078. defines["TANGENT"] = true;
  24079. }
  24080. if (defines._needUVs) {
  24081. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24082. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24083. }
  24084. else {
  24085. defines["UV1"] = false;
  24086. defines["UV2"] = false;
  24087. }
  24088. if (useVertexColor) {
  24089. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24090. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24091. }
  24092. if (useBones) {
  24093. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24094. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24095. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24096. }
  24097. else {
  24098. defines["NUM_BONE_INFLUENCERS"] = 0;
  24099. defines["BonesPerMesh"] = 0;
  24100. }
  24101. }
  24102. if (useMorphTargets) {
  24103. if (mesh.morphTargetManager) {
  24104. var manager = mesh.morphTargetManager;
  24105. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24106. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24107. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24108. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24109. }
  24110. else {
  24111. defines["MORPHTARGETS_TANGENT"] = false;
  24112. defines["MORPHTARGETS_NORMAL"] = false;
  24113. defines["MORPHTARGETS"] = false;
  24114. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24115. }
  24116. }
  24117. return true;
  24118. };
  24119. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24120. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24121. if (disableLighting === void 0) { disableLighting = false; }
  24122. if (!defines._areLightsDirty) {
  24123. return defines._needNormals;
  24124. }
  24125. var lightIndex = 0;
  24126. var needNormals = false;
  24127. var needRebuild = false;
  24128. var lightmapMode = false;
  24129. var shadowEnabled = false;
  24130. var specularEnabled = false;
  24131. if (scene.lightsEnabled && !disableLighting) {
  24132. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24133. var light = _a[_i];
  24134. needNormals = true;
  24135. if (defines["LIGHT" + lightIndex] === undefined) {
  24136. needRebuild = true;
  24137. }
  24138. defines["LIGHT" + lightIndex] = true;
  24139. defines["SPOTLIGHT" + lightIndex] = false;
  24140. defines["HEMILIGHT" + lightIndex] = false;
  24141. defines["POINTLIGHT" + lightIndex] = false;
  24142. defines["DIRLIGHT" + lightIndex] = false;
  24143. var type;
  24144. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24145. type = "SPOTLIGHT" + lightIndex;
  24146. }
  24147. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24148. type = "HEMILIGHT" + lightIndex;
  24149. }
  24150. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24151. type = "POINTLIGHT" + lightIndex;
  24152. }
  24153. else {
  24154. type = "DIRLIGHT" + lightIndex;
  24155. }
  24156. defines[type] = true;
  24157. // Specular
  24158. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24159. specularEnabled = true;
  24160. }
  24161. // Shadows
  24162. defines["SHADOW" + lightIndex] = false;
  24163. defines["SHADOWPCF" + lightIndex] = false;
  24164. defines["SHADOWESM" + lightIndex] = false;
  24165. defines["SHADOWCUBE" + lightIndex] = false;
  24166. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24167. var shadowGenerator = light.getShadowGenerator();
  24168. if (shadowGenerator) {
  24169. shadowEnabled = true;
  24170. shadowGenerator.prepareDefines(defines, lightIndex);
  24171. }
  24172. }
  24173. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24174. lightmapMode = true;
  24175. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24176. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24177. }
  24178. else {
  24179. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24180. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24181. }
  24182. lightIndex++;
  24183. if (lightIndex === maxSimultaneousLights)
  24184. break;
  24185. }
  24186. }
  24187. defines["SPECULARTERM"] = specularEnabled;
  24188. defines["SHADOWS"] = shadowEnabled;
  24189. // Resetting all other lights if any
  24190. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24191. if (defines["LIGHT" + index] !== undefined) {
  24192. defines["LIGHT" + index] = false;
  24193. defines["HEMILIGHT" + lightIndex] = false;
  24194. defines["POINTLIGHT" + lightIndex] = false;
  24195. defines["DIRLIGHT" + lightIndex] = false;
  24196. defines["SPOTLIGHT" + lightIndex] = false;
  24197. defines["SHADOW" + lightIndex] = false;
  24198. }
  24199. }
  24200. var caps = scene.getEngine().getCaps();
  24201. if (defines["SHADOWFLOAT"] === undefined) {
  24202. needRebuild = true;
  24203. }
  24204. defines["SHADOWFLOAT"] = shadowEnabled &&
  24205. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24206. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24207. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24208. if (needRebuild) {
  24209. defines.rebuild();
  24210. }
  24211. return needNormals;
  24212. };
  24213. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24214. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24215. var uniformsList, uniformBuffersList, samplersList, defines;
  24216. if (uniformsListOrOptions.uniformsNames) {
  24217. var options = uniformsListOrOptions;
  24218. uniformsList = options.uniformsNames;
  24219. uniformBuffersList = options.uniformBuffersNames;
  24220. samplersList = options.samplers;
  24221. defines = options.defines;
  24222. maxSimultaneousLights = options.maxSimultaneousLights;
  24223. }
  24224. else {
  24225. uniformsList = uniformsListOrOptions;
  24226. }
  24227. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24228. if (!defines["LIGHT" + lightIndex]) {
  24229. break;
  24230. }
  24231. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24232. if (uniformBuffersList) {
  24233. uniformBuffersList.push("Light" + lightIndex);
  24234. }
  24235. samplersList.push("shadowSampler" + lightIndex);
  24236. }
  24237. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24238. uniformsList.push("morphTargetInfluences");
  24239. }
  24240. };
  24241. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24242. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24243. if (!defines["SHADOWS"]) {
  24244. return;
  24245. }
  24246. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24247. if (!defines["LIGHT" + lightIndex]) {
  24248. break;
  24249. }
  24250. if (lightIndex > 0) {
  24251. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24252. }
  24253. if (defines["SHADOW" + lightIndex]) {
  24254. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24255. }
  24256. if (defines["SHADOWPCF" + lightIndex]) {
  24257. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24258. }
  24259. if (defines["SHADOWESM" + lightIndex]) {
  24260. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24261. }
  24262. }
  24263. };
  24264. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24265. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24266. if (influencers > 0) {
  24267. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24268. var manager = mesh.morphTargetManager;
  24269. var normal = manager.supportsNormals && defines["NORMAL"];
  24270. var tangent = manager.supportsTangents && defines["TANGENT"];
  24271. for (var index = 0; index < influencers; index++) {
  24272. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24273. if (normal) {
  24274. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24275. }
  24276. if (tangent) {
  24277. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24278. }
  24279. if (attribs.length > maxAttributesCount) {
  24280. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24281. }
  24282. }
  24283. }
  24284. };
  24285. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24286. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24287. fallbacks.addCPUSkinningFallback(0, mesh);
  24288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24290. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24291. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24292. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24293. }
  24294. }
  24295. };
  24296. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24297. if (defines["INSTANCES"]) {
  24298. attribs.push("world0");
  24299. attribs.push("world1");
  24300. attribs.push("world2");
  24301. attribs.push("world3");
  24302. }
  24303. };
  24304. // Bindings
  24305. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24306. if (light.shadowEnabled && mesh.receiveShadows) {
  24307. var shadowGenerator = light.getShadowGenerator();
  24308. if (shadowGenerator) {
  24309. shadowGenerator.bindShadowLight(lightIndex, effect);
  24310. }
  24311. }
  24312. };
  24313. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24314. light.transferToEffect(effect, lightIndex + "");
  24315. };
  24316. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24317. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24318. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24319. var lightIndex = 0;
  24320. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24321. var light = _a[_i];
  24322. var scaledIntensity = light.getScaledIntensity();
  24323. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24324. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24325. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24326. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24327. if (defines["SPECULARTERM"]) {
  24328. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24329. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24330. }
  24331. // Shadows
  24332. if (scene.shadowsEnabled) {
  24333. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24334. }
  24335. light._uniformBuffer.update();
  24336. lightIndex++;
  24337. if (lightIndex === maxSimultaneousLights)
  24338. break;
  24339. }
  24340. };
  24341. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24342. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24343. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24344. effect.setColor3("vFogColor", scene.fogColor);
  24345. }
  24346. };
  24347. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24348. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24349. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24350. if (matrices) {
  24351. effect.setMatrices("mBones", matrices);
  24352. }
  24353. }
  24354. };
  24355. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  24356. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  24357. return;
  24358. }
  24359. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  24360. };
  24361. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24362. if (defines["LOGARITHMICDEPTH"]) {
  24363. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24364. }
  24365. };
  24366. MaterialHelper.BindClipPlane = function (effect, scene) {
  24367. if (scene.clipPlane) {
  24368. var clipPlane = scene.clipPlane;
  24369. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24370. }
  24371. };
  24372. return MaterialHelper;
  24373. }());
  24374. BABYLON.MaterialHelper = MaterialHelper;
  24375. })(BABYLON || (BABYLON = {}));
  24376. //# sourceMappingURL=babylon.materialHelper.js.map
  24377. var BABYLON;
  24378. (function (BABYLON) {
  24379. var MaterialDefines = (function () {
  24380. function MaterialDefines() {
  24381. this._isDirty = true;
  24382. this._areLightsDirty = true;
  24383. this._areAttributesDirty = true;
  24384. this._areTexturesDirty = true;
  24385. this._areFresnelDirty = true;
  24386. this._areMiscDirty = true;
  24387. this._areImageProcessingDirty = true;
  24388. this._normals = false;
  24389. this._uvs = false;
  24390. this._needNormals = false;
  24391. this._needUVs = false;
  24392. }
  24393. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  24394. get: function () {
  24395. return this._isDirty;
  24396. },
  24397. enumerable: true,
  24398. configurable: true
  24399. });
  24400. MaterialDefines.prototype.markAsProcessed = function () {
  24401. this._isDirty = false;
  24402. this._areAttributesDirty = false;
  24403. this._areTexturesDirty = false;
  24404. this._areFresnelDirty = false;
  24405. this._areLightsDirty = false;
  24406. this._areMiscDirty = false;
  24407. this._areImageProcessingDirty = false;
  24408. };
  24409. MaterialDefines.prototype.markAsUnprocessed = function () {
  24410. this._isDirty = true;
  24411. };
  24412. MaterialDefines.prototype.markAllAsDirty = function () {
  24413. this._areTexturesDirty = true;
  24414. this._areAttributesDirty = true;
  24415. this._areLightsDirty = true;
  24416. this._areFresnelDirty = true;
  24417. this._areMiscDirty = true;
  24418. this._areImageProcessingDirty = true;
  24419. this._isDirty = true;
  24420. };
  24421. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  24422. this._areImageProcessingDirty = true;
  24423. this._isDirty = true;
  24424. };
  24425. MaterialDefines.prototype.markAsLightDirty = function () {
  24426. this._areLightsDirty = true;
  24427. this._isDirty = true;
  24428. };
  24429. MaterialDefines.prototype.markAsAttributesDirty = function () {
  24430. this._areAttributesDirty = true;
  24431. this._isDirty = true;
  24432. };
  24433. MaterialDefines.prototype.markAsTexturesDirty = function () {
  24434. this._areTexturesDirty = true;
  24435. this._isDirty = true;
  24436. };
  24437. MaterialDefines.prototype.markAsFresnelDirty = function () {
  24438. this._areFresnelDirty = true;
  24439. this._isDirty = true;
  24440. };
  24441. MaterialDefines.prototype.markAsMiscDirty = function () {
  24442. this._areMiscDirty = true;
  24443. this._isDirty = true;
  24444. };
  24445. MaterialDefines.prototype.rebuild = function () {
  24446. if (this._keys) {
  24447. delete this._keys;
  24448. }
  24449. this._keys = [];
  24450. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  24451. var key = _a[_i];
  24452. if (key[0] === "_") {
  24453. continue;
  24454. }
  24455. this._keys.push(key);
  24456. }
  24457. };
  24458. MaterialDefines.prototype.isEqual = function (other) {
  24459. if (this._keys.length !== other._keys.length) {
  24460. return false;
  24461. }
  24462. for (var index = 0; index < this._keys.length; index++) {
  24463. var prop = this._keys[index];
  24464. if (this[prop] !== other[prop]) {
  24465. return false;
  24466. }
  24467. }
  24468. return true;
  24469. };
  24470. MaterialDefines.prototype.cloneTo = function (other) {
  24471. if (this._keys.length !== other._keys.length) {
  24472. other._keys = this._keys.slice(0);
  24473. }
  24474. for (var index = 0; index < this._keys.length; index++) {
  24475. var prop = this._keys[index];
  24476. other[prop] = this[prop];
  24477. }
  24478. };
  24479. MaterialDefines.prototype.reset = function () {
  24480. for (var index = 0; index < this._keys.length; index++) {
  24481. var prop = this._keys[index];
  24482. if (typeof (this[prop]) === "number") {
  24483. this[prop] = 0;
  24484. }
  24485. else {
  24486. this[prop] = false;
  24487. }
  24488. }
  24489. };
  24490. MaterialDefines.prototype.toString = function () {
  24491. var result = "";
  24492. for (var index = 0; index < this._keys.length; index++) {
  24493. var prop = this._keys[index];
  24494. var value = this[prop];
  24495. if (typeof (value) === "number") {
  24496. result += "#define " + prop + " " + this[prop] + "\n";
  24497. }
  24498. else if (value) {
  24499. result += "#define " + prop + "\n";
  24500. }
  24501. }
  24502. return result;
  24503. };
  24504. return MaterialDefines;
  24505. }());
  24506. BABYLON.MaterialDefines = MaterialDefines;
  24507. var Material = (function () {
  24508. function Material(name, scene, doNotAdd) {
  24509. this.checkReadyOnEveryCall = false;
  24510. this.checkReadyOnlyOnce = false;
  24511. this.state = "";
  24512. this.alpha = 1.0;
  24513. this._backFaceCulling = true;
  24514. this.doNotSerialize = false;
  24515. this.storeEffectOnSubMeshes = false;
  24516. /**
  24517. * An event triggered when the material is disposed.
  24518. * @type {BABYLON.Observable}
  24519. */
  24520. this.onDisposeObservable = new BABYLON.Observable();
  24521. /**
  24522. * An event triggered when the material is bound.
  24523. * @type {BABYLON.Observable}
  24524. */
  24525. this.onBindObservable = new BABYLON.Observable();
  24526. /**
  24527. * An event triggered when the material is unbound.
  24528. * @type {BABYLON.Observable}
  24529. */
  24530. this.onUnBindObservable = new BABYLON.Observable();
  24531. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24532. this.disableDepthWrite = false;
  24533. this._fogEnabled = true;
  24534. this.pointSize = 1.0;
  24535. this.zOffset = 0;
  24536. this._wasPreviouslyReady = false;
  24537. this._fillMode = Material.TriangleFillMode;
  24538. this.name = name;
  24539. this.id = name || BABYLON.Tools.RandomId();
  24540. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24541. if (this._scene.useRightHandedSystem) {
  24542. this.sideOrientation = Material.ClockWiseSideOrientation;
  24543. }
  24544. else {
  24545. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24546. }
  24547. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  24548. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  24549. if (!doNotAdd) {
  24550. this._scene.materials.push(this);
  24551. }
  24552. }
  24553. Object.defineProperty(Material, "TriangleFillMode", {
  24554. get: function () {
  24555. return Material._TriangleFillMode;
  24556. },
  24557. enumerable: true,
  24558. configurable: true
  24559. });
  24560. Object.defineProperty(Material, "WireFrameFillMode", {
  24561. get: function () {
  24562. return Material._WireFrameFillMode;
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Object.defineProperty(Material, "PointFillMode", {
  24568. get: function () {
  24569. return Material._PointFillMode;
  24570. },
  24571. enumerable: true,
  24572. configurable: true
  24573. });
  24574. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24575. get: function () {
  24576. return Material._ClockWiseSideOrientation;
  24577. },
  24578. enumerable: true,
  24579. configurable: true
  24580. });
  24581. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24582. get: function () {
  24583. return Material._CounterClockWiseSideOrientation;
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. Object.defineProperty(Material, "TextureDirtyFlag", {
  24589. get: function () {
  24590. return Material._TextureDirtyFlag;
  24591. },
  24592. enumerable: true,
  24593. configurable: true
  24594. });
  24595. Object.defineProperty(Material, "LightDirtyFlag", {
  24596. get: function () {
  24597. return Material._LightDirtyFlag;
  24598. },
  24599. enumerable: true,
  24600. configurable: true
  24601. });
  24602. Object.defineProperty(Material, "FresnelDirtyFlag", {
  24603. get: function () {
  24604. return Material._FresnelDirtyFlag;
  24605. },
  24606. enumerable: true,
  24607. configurable: true
  24608. });
  24609. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24610. get: function () {
  24611. return Material._AttributesDirtyFlag;
  24612. },
  24613. enumerable: true,
  24614. configurable: true
  24615. });
  24616. Object.defineProperty(Material, "MiscDirtyFlag", {
  24617. get: function () {
  24618. return Material._MiscDirtyFlag;
  24619. },
  24620. enumerable: true,
  24621. configurable: true
  24622. });
  24623. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24624. get: function () {
  24625. return this._backFaceCulling;
  24626. },
  24627. set: function (value) {
  24628. if (this._backFaceCulling === value) {
  24629. return;
  24630. }
  24631. this._backFaceCulling = value;
  24632. this.markAsDirty(Material.TextureDirtyFlag);
  24633. },
  24634. enumerable: true,
  24635. configurable: true
  24636. });
  24637. Object.defineProperty(Material.prototype, "onDispose", {
  24638. set: function (callback) {
  24639. if (this._onDisposeObserver) {
  24640. this.onDisposeObservable.remove(this._onDisposeObserver);
  24641. }
  24642. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24643. },
  24644. enumerable: true,
  24645. configurable: true
  24646. });
  24647. Object.defineProperty(Material.prototype, "onBind", {
  24648. set: function (callback) {
  24649. if (this._onBindObserver) {
  24650. this.onBindObservable.remove(this._onBindObserver);
  24651. }
  24652. this._onBindObserver = this.onBindObservable.add(callback);
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. Object.defineProperty(Material.prototype, "fogEnabled", {
  24658. get: function () {
  24659. return this._fogEnabled;
  24660. },
  24661. set: function (value) {
  24662. if (this._fogEnabled === value) {
  24663. return;
  24664. }
  24665. this._fogEnabled = value;
  24666. this.markAsDirty(Material.MiscDirtyFlag);
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(Material.prototype, "wireframe", {
  24672. get: function () {
  24673. return this._fillMode === Material.WireFrameFillMode;
  24674. },
  24675. set: function (value) {
  24676. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24677. },
  24678. enumerable: true,
  24679. configurable: true
  24680. });
  24681. Object.defineProperty(Material.prototype, "pointsCloud", {
  24682. get: function () {
  24683. return this._fillMode === Material.PointFillMode;
  24684. },
  24685. set: function (value) {
  24686. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. Object.defineProperty(Material.prototype, "fillMode", {
  24692. get: function () {
  24693. return this._fillMode;
  24694. },
  24695. set: function (value) {
  24696. if (this._fillMode === value) {
  24697. return;
  24698. }
  24699. this._fillMode = value;
  24700. this.markAsDirty(Material.MiscDirtyFlag);
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. /**
  24706. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24707. * subclasses should override adding information pertainent to themselves
  24708. */
  24709. Material.prototype.toString = function (fullDetails) {
  24710. var ret = "Name: " + this.name;
  24711. if (fullDetails) {
  24712. }
  24713. return ret;
  24714. };
  24715. /**
  24716. * Child classes can use it to update shaders
  24717. */
  24718. Material.prototype.getClassName = function () {
  24719. return "Material";
  24720. };
  24721. Object.defineProperty(Material.prototype, "isFrozen", {
  24722. get: function () {
  24723. return this.checkReadyOnlyOnce;
  24724. },
  24725. enumerable: true,
  24726. configurable: true
  24727. });
  24728. Material.prototype.freeze = function () {
  24729. this.checkReadyOnlyOnce = true;
  24730. };
  24731. Material.prototype.unfreeze = function () {
  24732. this.checkReadyOnlyOnce = false;
  24733. };
  24734. Material.prototype.isReady = function (mesh, useInstances) {
  24735. return true;
  24736. };
  24737. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24738. return false;
  24739. };
  24740. Material.prototype.getEffect = function () {
  24741. return this._effect;
  24742. };
  24743. Material.prototype.getScene = function () {
  24744. return this._scene;
  24745. };
  24746. Material.prototype.needAlphaBlending = function () {
  24747. return (this.alpha < 1.0);
  24748. };
  24749. Material.prototype.needAlphaTesting = function () {
  24750. return false;
  24751. };
  24752. Material.prototype.getAlphaTestTexture = function () {
  24753. return null;
  24754. };
  24755. Material.prototype.markDirty = function () {
  24756. this._wasPreviouslyReady = false;
  24757. };
  24758. Material.prototype._preBind = function (effect) {
  24759. var engine = this._scene.getEngine();
  24760. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24761. engine.enableEffect(effect ? effect : this._effect);
  24762. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24763. };
  24764. Material.prototype.bind = function (world, mesh) {
  24765. };
  24766. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24767. };
  24768. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24769. };
  24770. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24771. sceneUbo.bindToEffect(effect, "Scene");
  24772. };
  24773. Material.prototype.bindView = function (effect) {
  24774. if (!this._useUBO) {
  24775. effect.setMatrix("view", this.getScene().getViewMatrix());
  24776. }
  24777. else {
  24778. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24779. }
  24780. };
  24781. Material.prototype.bindViewProjection = function (effect) {
  24782. if (!this._useUBO) {
  24783. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24784. }
  24785. else {
  24786. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24787. }
  24788. };
  24789. Material.prototype._afterBind = function (mesh) {
  24790. this._scene._cachedMaterial = this;
  24791. this.onBindObservable.notifyObservers(mesh);
  24792. if (this.disableDepthWrite) {
  24793. var engine = this._scene.getEngine();
  24794. this._cachedDepthWriteState = engine.getDepthWrite();
  24795. engine.setDepthWrite(false);
  24796. }
  24797. };
  24798. Material.prototype.unbind = function () {
  24799. this.onUnBindObservable.notifyObservers(this);
  24800. if (this.disableDepthWrite) {
  24801. var engine = this._scene.getEngine();
  24802. engine.setDepthWrite(this._cachedDepthWriteState);
  24803. }
  24804. };
  24805. Material.prototype.getActiveTextures = function () {
  24806. return [];
  24807. };
  24808. Material.prototype.hasTexture = function (texture) {
  24809. return false;
  24810. };
  24811. Material.prototype.clone = function (name) {
  24812. return null;
  24813. };
  24814. Material.prototype.getBindedMeshes = function () {
  24815. var result = new Array();
  24816. for (var index = 0; index < this._scene.meshes.length; index++) {
  24817. var mesh = this._scene.meshes[index];
  24818. if (mesh.material === this) {
  24819. result.push(mesh);
  24820. }
  24821. }
  24822. return result;
  24823. };
  24824. /**
  24825. * Force shader compilation including textures ready check
  24826. */
  24827. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24828. var _this = this;
  24829. var subMesh = new BABYLON.BaseSubMesh();
  24830. var scene = this.getScene();
  24831. var engine = scene.getEngine();
  24832. var checkReady = function () {
  24833. if (!_this._scene || !_this._scene.getEngine()) {
  24834. return;
  24835. }
  24836. if (subMesh._materialDefines) {
  24837. subMesh._materialDefines._renderId = -1;
  24838. }
  24839. var alphaTestState = engine.getAlphaTesting();
  24840. var clipPlaneState = scene.clipPlane;
  24841. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24842. if (options && options.clipPlane) {
  24843. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  24844. }
  24845. if (_this.storeEffectOnSubMeshes) {
  24846. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24847. if (onCompiled) {
  24848. onCompiled(_this);
  24849. }
  24850. }
  24851. else {
  24852. setTimeout(checkReady, 16);
  24853. }
  24854. }
  24855. else {
  24856. if (_this.isReady(mesh)) {
  24857. if (onCompiled) {
  24858. onCompiled(_this);
  24859. }
  24860. }
  24861. else {
  24862. setTimeout(checkReady, 16);
  24863. }
  24864. }
  24865. engine.setAlphaTesting(alphaTestState);
  24866. if (options && options.clipPlane) {
  24867. scene.clipPlane = clipPlaneState;
  24868. }
  24869. };
  24870. checkReady();
  24871. };
  24872. Material.prototype.markAsDirty = function (flag) {
  24873. if (flag & Material.TextureDirtyFlag) {
  24874. this._markAllSubMeshesAsTexturesDirty();
  24875. }
  24876. if (flag & Material.LightDirtyFlag) {
  24877. this._markAllSubMeshesAsLightsDirty();
  24878. }
  24879. if (flag & Material.FresnelDirtyFlag) {
  24880. this._markAllSubMeshesAsFresnelDirty();
  24881. }
  24882. if (flag & Material.AttributesDirtyFlag) {
  24883. this._markAllSubMeshesAsAttributesDirty();
  24884. }
  24885. if (flag & Material.MiscDirtyFlag) {
  24886. this._markAllSubMeshesAsMiscDirty();
  24887. }
  24888. this.getScene().resetCachedMaterial();
  24889. };
  24890. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24891. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24892. var mesh = _a[_i];
  24893. if (!mesh.subMeshes) {
  24894. continue;
  24895. }
  24896. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24897. var subMesh = _c[_b];
  24898. if (subMesh.getMaterial() !== this) {
  24899. continue;
  24900. }
  24901. if (!subMesh._materialDefines) {
  24902. continue;
  24903. }
  24904. func(subMesh._materialDefines);
  24905. }
  24906. }
  24907. };
  24908. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  24909. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  24910. };
  24911. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24912. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24913. };
  24914. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24915. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24916. };
  24917. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24918. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24919. };
  24920. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24921. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24922. };
  24923. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24924. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24925. };
  24926. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24927. // Animations
  24928. this.getScene().stopAnimation(this);
  24929. // Remove from scene
  24930. var index = this._scene.materials.indexOf(this);
  24931. if (index >= 0) {
  24932. this._scene.materials.splice(index, 1);
  24933. }
  24934. // Remove from meshes
  24935. for (index = 0; index < this._scene.meshes.length; index++) {
  24936. var mesh = this._scene.meshes[index];
  24937. if (mesh.material === this) {
  24938. mesh.material = null;
  24939. if (mesh.geometry) {
  24940. var geometry = mesh.geometry;
  24941. if (this.storeEffectOnSubMeshes) {
  24942. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24943. var subMesh = _a[_i];
  24944. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24945. }
  24946. }
  24947. else {
  24948. geometry._releaseVertexArrayObject(this._effect);
  24949. }
  24950. }
  24951. }
  24952. }
  24953. this._uniformBuffer.dispose();
  24954. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24955. if (forceDisposeEffect && this._effect) {
  24956. if (this.storeEffectOnSubMeshes) {
  24957. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24958. var subMesh = _c[_b];
  24959. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24960. }
  24961. }
  24962. else {
  24963. this._scene.getEngine()._releaseEffect(this._effect);
  24964. }
  24965. this._effect = null;
  24966. }
  24967. // Callback
  24968. this.onDisposeObservable.notifyObservers(this);
  24969. this.onDisposeObservable.clear();
  24970. this.onBindObservable.clear();
  24971. this.onUnBindObservable.clear();
  24972. };
  24973. Material.prototype.serialize = function () {
  24974. return BABYLON.SerializationHelper.Serialize(this);
  24975. };
  24976. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24977. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24978. multiMaterial.id = parsedMultiMaterial.id;
  24979. if (BABYLON.Tags) {
  24980. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24981. }
  24982. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24983. var subMatId = parsedMultiMaterial.materials[matIndex];
  24984. if (subMatId) {
  24985. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24986. }
  24987. else {
  24988. multiMaterial.subMaterials.push(null);
  24989. }
  24990. }
  24991. return multiMaterial;
  24992. };
  24993. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24994. if (!parsedMaterial.customType) {
  24995. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24996. }
  24997. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24998. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24999. if (!BABYLON.LegacyPBRMaterial) {
  25000. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25001. return;
  25002. }
  25003. }
  25004. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25005. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25006. ;
  25007. };
  25008. return Material;
  25009. }());
  25010. Material._TriangleFillMode = 0;
  25011. Material._WireFrameFillMode = 1;
  25012. Material._PointFillMode = 2;
  25013. Material._ClockWiseSideOrientation = 0;
  25014. Material._CounterClockWiseSideOrientation = 1;
  25015. Material._TextureDirtyFlag = 1;
  25016. Material._LightDirtyFlag = 2;
  25017. Material._FresnelDirtyFlag = 4;
  25018. Material._AttributesDirtyFlag = 8;
  25019. Material._MiscDirtyFlag = 16;
  25020. __decorate([
  25021. BABYLON.serialize()
  25022. ], Material.prototype, "id", void 0);
  25023. __decorate([
  25024. BABYLON.serialize()
  25025. ], Material.prototype, "name", void 0);
  25026. __decorate([
  25027. BABYLON.serialize()
  25028. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25029. __decorate([
  25030. BABYLON.serialize()
  25031. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25032. __decorate([
  25033. BABYLON.serialize()
  25034. ], Material.prototype, "state", void 0);
  25035. __decorate([
  25036. BABYLON.serialize()
  25037. ], Material.prototype, "alpha", void 0);
  25038. __decorate([
  25039. BABYLON.serialize("backFaceCulling")
  25040. ], Material.prototype, "_backFaceCulling", void 0);
  25041. __decorate([
  25042. BABYLON.serialize()
  25043. ], Material.prototype, "sideOrientation", void 0);
  25044. __decorate([
  25045. BABYLON.serialize()
  25046. ], Material.prototype, "alphaMode", void 0);
  25047. __decorate([
  25048. BABYLON.serialize()
  25049. ], Material.prototype, "disableDepthWrite", void 0);
  25050. __decorate([
  25051. BABYLON.serialize("fogEnabled")
  25052. ], Material.prototype, "_fogEnabled", void 0);
  25053. __decorate([
  25054. BABYLON.serialize()
  25055. ], Material.prototype, "pointSize", void 0);
  25056. __decorate([
  25057. BABYLON.serialize()
  25058. ], Material.prototype, "zOffset", void 0);
  25059. __decorate([
  25060. BABYLON.serialize()
  25061. ], Material.prototype, "wireframe", null);
  25062. __decorate([
  25063. BABYLON.serialize()
  25064. ], Material.prototype, "pointsCloud", null);
  25065. __decorate([
  25066. BABYLON.serialize()
  25067. ], Material.prototype, "fillMode", null);
  25068. BABYLON.Material = Material;
  25069. })(BABYLON || (BABYLON = {}));
  25070. //# sourceMappingURL=babylon.material.js.map
  25071. var BABYLON;
  25072. (function (BABYLON) {
  25073. var UniformBuffer = (function () {
  25074. /**
  25075. * Uniform buffer objects.
  25076. *
  25077. * Handles blocks of uniform on the GPU.
  25078. *
  25079. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25080. *
  25081. * For more information, please refer to :
  25082. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25083. */
  25084. function UniformBuffer(engine, data, dynamic) {
  25085. this._engine = engine;
  25086. this._noUBO = engine.webGLVersion === 1;
  25087. this._dynamic = dynamic;
  25088. this._data = data || [];
  25089. this._uniformLocations = {};
  25090. this._uniformSizes = {};
  25091. this._uniformLocationPointer = 0;
  25092. this._needSync = false;
  25093. if (this._noUBO) {
  25094. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25095. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25096. this.updateFloat = this._updateFloatForEffect;
  25097. this.updateFloat2 = this._updateFloat2ForEffect;
  25098. this.updateFloat3 = this._updateFloat3ForEffect;
  25099. this.updateFloat4 = this._updateFloat4ForEffect;
  25100. this.updateMatrix = this._updateMatrixForEffect;
  25101. this.updateVector3 = this._updateVector3ForEffect;
  25102. this.updateVector4 = this._updateVector4ForEffect;
  25103. this.updateColor3 = this._updateColor3ForEffect;
  25104. this.updateColor4 = this._updateColor4ForEffect;
  25105. }
  25106. else {
  25107. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25108. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25109. this.updateFloat = this._updateFloatForUniform;
  25110. this.updateFloat2 = this._updateFloat2ForUniform;
  25111. this.updateFloat3 = this._updateFloat3ForUniform;
  25112. this.updateFloat4 = this._updateFloat4ForUniform;
  25113. this.updateMatrix = this._updateMatrixForUniform;
  25114. this.updateVector3 = this._updateVector3ForUniform;
  25115. this.updateVector4 = this._updateVector4ForUniform;
  25116. this.updateColor3 = this._updateColor3ForUniform;
  25117. this.updateColor4 = this._updateColor4ForUniform;
  25118. }
  25119. }
  25120. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25121. // Properties
  25122. /**
  25123. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25124. * or just falling back on setUniformXXX calls.
  25125. */
  25126. get: function () {
  25127. return !this._noUBO;
  25128. },
  25129. enumerable: true,
  25130. configurable: true
  25131. });
  25132. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25133. /**
  25134. * Indicates if the WebGL underlying uniform buffer is in sync
  25135. * with the javascript cache data.
  25136. */
  25137. get: function () {
  25138. return !this._needSync;
  25139. },
  25140. enumerable: true,
  25141. configurable: true
  25142. });
  25143. /**
  25144. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25145. * Also, a dynamic UniformBuffer will disable cache verification and always
  25146. * update the underlying WebGL uniform buffer to the GPU.
  25147. */
  25148. UniformBuffer.prototype.isDynamic = function () {
  25149. return this._dynamic;
  25150. };
  25151. /**
  25152. * The data cache on JS side.
  25153. */
  25154. UniformBuffer.prototype.getData = function () {
  25155. return this._bufferData;
  25156. };
  25157. /**
  25158. * The underlying WebGL Uniform buffer.
  25159. */
  25160. UniformBuffer.prototype.getBuffer = function () {
  25161. return this._buffer;
  25162. };
  25163. /**
  25164. * std140 layout specifies how to align data within an UBO structure.
  25165. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25166. * for specs.
  25167. */
  25168. UniformBuffer.prototype._fillAlignment = function (size) {
  25169. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25170. // and 4x4 matrices
  25171. // TODO : change if other types are used
  25172. var alignment;
  25173. if (size <= 2) {
  25174. alignment = size;
  25175. }
  25176. else {
  25177. alignment = 4;
  25178. }
  25179. if ((this._uniformLocationPointer % alignment) !== 0) {
  25180. var oldPointer = this._uniformLocationPointer;
  25181. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25182. var diff = this._uniformLocationPointer - oldPointer;
  25183. for (var i = 0; i < diff; i++) {
  25184. this._data.push(0);
  25185. }
  25186. }
  25187. };
  25188. /**
  25189. * Adds an uniform in the buffer.
  25190. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25191. * for the layout to be correct !
  25192. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25193. * @param {number|number[]} size Data size, or data directly.
  25194. */
  25195. UniformBuffer.prototype.addUniform = function (name, size) {
  25196. if (this._noUBO) {
  25197. return;
  25198. }
  25199. if (this._uniformLocations[name] !== undefined) {
  25200. // Already existing uniform
  25201. return;
  25202. }
  25203. // This function must be called in the order of the shader layout !
  25204. // size can be the size of the uniform, or data directly
  25205. var data;
  25206. if (size instanceof Array) {
  25207. data = size;
  25208. size = data.length;
  25209. }
  25210. else {
  25211. size = size;
  25212. data = [];
  25213. // Fill with zeros
  25214. for (var i = 0; i < size; i++) {
  25215. data.push(0);
  25216. }
  25217. }
  25218. this._fillAlignment(size);
  25219. this._uniformSizes[name] = size;
  25220. this._uniformLocations[name] = this._uniformLocationPointer;
  25221. this._uniformLocationPointer += size;
  25222. for (var i = 0; i < size; i++) {
  25223. this._data.push(data[i]);
  25224. }
  25225. this._needSync = true;
  25226. };
  25227. /**
  25228. * Wrapper for addUniform.
  25229. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25230. * @param {Matrix} mat A 4x4 matrix.
  25231. */
  25232. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25233. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25234. };
  25235. /**
  25236. * Wrapper for addUniform.
  25237. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25238. * @param {number} x
  25239. * @param {number} y
  25240. */
  25241. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25242. var temp = [x, y];
  25243. this.addUniform(name, temp);
  25244. };
  25245. /**
  25246. * Wrapper for addUniform.
  25247. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25248. * @param {number} x
  25249. * @param {number} y
  25250. * @param {number} z
  25251. */
  25252. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25253. var temp = [x, y, z];
  25254. this.addUniform(name, temp);
  25255. };
  25256. /**
  25257. * Wrapper for addUniform.
  25258. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25259. * @param {Color3} color
  25260. */
  25261. UniformBuffer.prototype.addColor3 = function (name, color) {
  25262. var temp = [];
  25263. color.toArray(temp);
  25264. this.addUniform(name, temp);
  25265. };
  25266. /**
  25267. * Wrapper for addUniform.
  25268. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25269. * @param {Color3} color
  25270. * @param {number} alpha
  25271. */
  25272. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25273. var temp = [];
  25274. color.toArray(temp);
  25275. temp.push(alpha);
  25276. this.addUniform(name, temp);
  25277. };
  25278. /**
  25279. * Wrapper for addUniform.
  25280. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25281. * @param {Vector3} vector
  25282. */
  25283. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25284. var temp = [];
  25285. vector.toArray(temp);
  25286. this.addUniform(name, temp);
  25287. };
  25288. /**
  25289. * Wrapper for addUniform.
  25290. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25291. */
  25292. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25293. this.addUniform(name, 12);
  25294. };
  25295. /**
  25296. * Wrapper for addUniform.
  25297. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25298. */
  25299. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25300. this.addUniform(name, 8);
  25301. };
  25302. /**
  25303. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25304. */
  25305. UniformBuffer.prototype.create = function () {
  25306. if (this._noUBO) {
  25307. return;
  25308. }
  25309. if (this._buffer) {
  25310. return; // nothing to do
  25311. }
  25312. // See spec, alignment must be filled as a vec4
  25313. this._fillAlignment(4);
  25314. this._bufferData = new Float32Array(this._data);
  25315. if (this._dynamic) {
  25316. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25317. }
  25318. else {
  25319. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25320. }
  25321. this._needSync = true;
  25322. };
  25323. /**
  25324. * Updates the WebGL Uniform Buffer on the GPU.
  25325. * If the `dynamic` flag is set to true, no cache comparison is done.
  25326. * Otherwise, the buffer will be updated only if the cache differs.
  25327. */
  25328. UniformBuffer.prototype.update = function () {
  25329. if (!this._buffer) {
  25330. this.create();
  25331. return;
  25332. }
  25333. if (!this._dynamic && !this._needSync) {
  25334. return;
  25335. }
  25336. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25337. this._needSync = false;
  25338. };
  25339. /**
  25340. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  25341. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25342. * @param {number[]|Float32Array} data Flattened data
  25343. * @param {number} size Size of the data.
  25344. */
  25345. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  25346. var location = this._uniformLocations[uniformName];
  25347. if (location === undefined) {
  25348. if (this._buffer) {
  25349. // Cannot add an uniform if the buffer is already created
  25350. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  25351. return;
  25352. }
  25353. this.addUniform(uniformName, size);
  25354. location = this._uniformLocations[uniformName];
  25355. }
  25356. if (!this._buffer) {
  25357. this.create();
  25358. }
  25359. if (!this._dynamic) {
  25360. // Cache for static uniform buffers
  25361. var changed = false;
  25362. for (var i = 0; i < size; i++) {
  25363. if (this._bufferData[location + i] !== data[i]) {
  25364. changed = true;
  25365. this._bufferData[location + i] = data[i];
  25366. }
  25367. }
  25368. this._needSync = this._needSync || changed;
  25369. }
  25370. else {
  25371. // No cache for dynamic
  25372. for (var i = 0; i < size; i++) {
  25373. this._bufferData[location + i] = data[i];
  25374. }
  25375. }
  25376. };
  25377. // Update methods
  25378. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  25379. // To match std140, matrix must be realigned
  25380. for (var i = 0; i < 3; i++) {
  25381. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  25382. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  25383. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  25384. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25385. }
  25386. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  25387. };
  25388. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  25389. this._currentEffect.setMatrix3x3(name, matrix);
  25390. };
  25391. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  25392. this._currentEffect.setMatrix2x2(name, matrix);
  25393. };
  25394. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  25395. // To match std140, matrix must be realigned
  25396. for (var i = 0; i < 2; i++) {
  25397. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  25398. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  25399. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  25400. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25401. }
  25402. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  25403. };
  25404. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  25405. this._currentEffect.setFloat(name, x);
  25406. };
  25407. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  25408. UniformBuffer._tempBuffer[0] = x;
  25409. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  25410. };
  25411. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  25412. if (suffix === void 0) { suffix = ""; }
  25413. this._currentEffect.setFloat2(name + suffix, x, y);
  25414. };
  25415. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  25416. if (suffix === void 0) { suffix = ""; }
  25417. UniformBuffer._tempBuffer[0] = x;
  25418. UniformBuffer._tempBuffer[1] = y;
  25419. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  25420. };
  25421. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  25422. if (suffix === void 0) { suffix = ""; }
  25423. this._currentEffect.setFloat3(name + suffix, x, y, z);
  25424. };
  25425. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  25426. if (suffix === void 0) { suffix = ""; }
  25427. UniformBuffer._tempBuffer[0] = x;
  25428. UniformBuffer._tempBuffer[1] = y;
  25429. UniformBuffer._tempBuffer[2] = z;
  25430. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25431. };
  25432. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  25433. if (suffix === void 0) { suffix = ""; }
  25434. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  25435. };
  25436. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  25437. if (suffix === void 0) { suffix = ""; }
  25438. UniformBuffer._tempBuffer[0] = x;
  25439. UniformBuffer._tempBuffer[1] = y;
  25440. UniformBuffer._tempBuffer[2] = z;
  25441. UniformBuffer._tempBuffer[3] = w;
  25442. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25443. };
  25444. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  25445. this._currentEffect.setMatrix(name, mat);
  25446. };
  25447. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  25448. this.updateUniform(name, mat.toArray(), 16);
  25449. };
  25450. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  25451. this._currentEffect.setVector3(name, vector);
  25452. };
  25453. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  25454. vector.toArray(UniformBuffer._tempBuffer);
  25455. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25456. };
  25457. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  25458. this._currentEffect.setVector4(name, vector);
  25459. };
  25460. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  25461. vector.toArray(UniformBuffer._tempBuffer);
  25462. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25463. };
  25464. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  25465. if (suffix === void 0) { suffix = ""; }
  25466. this._currentEffect.setColor3(name + suffix, color);
  25467. };
  25468. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  25469. if (suffix === void 0) { suffix = ""; }
  25470. color.toArray(UniformBuffer._tempBuffer);
  25471. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25472. };
  25473. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  25474. if (suffix === void 0) { suffix = ""; }
  25475. this._currentEffect.setColor4(name + suffix, color, alpha);
  25476. };
  25477. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  25478. if (suffix === void 0) { suffix = ""; }
  25479. color.toArray(UniformBuffer._tempBuffer);
  25480. UniformBuffer._tempBuffer[3] = alpha;
  25481. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25482. };
  25483. /**
  25484. * Sets a sampler uniform on the effect.
  25485. * @param {string} name Name of the sampler.
  25486. * @param {Texture} texture
  25487. */
  25488. UniformBuffer.prototype.setTexture = function (name, texture) {
  25489. this._currentEffect.setTexture(name, texture);
  25490. };
  25491. /**
  25492. * Directly updates the value of the uniform in the cache AND on the GPU.
  25493. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25494. * @param {number[]|Float32Array} data Flattened data
  25495. */
  25496. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  25497. this.updateUniform(uniformName, data, data.length);
  25498. this.update();
  25499. };
  25500. /**
  25501. * Binds this uniform buffer to an effect.
  25502. * @param {Effect} effect
  25503. * @param {string} name Name of the uniform block in the shader.
  25504. */
  25505. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  25506. this._currentEffect = effect;
  25507. if (this._noUBO) {
  25508. return;
  25509. }
  25510. effect.bindUniformBuffer(this._buffer, name);
  25511. };
  25512. /**
  25513. * Disposes the uniform buffer.
  25514. */
  25515. UniformBuffer.prototype.dispose = function () {
  25516. if (!this._buffer) {
  25517. return;
  25518. }
  25519. if (this._engine._releaseBuffer(this._buffer)) {
  25520. this._buffer = null;
  25521. }
  25522. };
  25523. return UniformBuffer;
  25524. }());
  25525. // Pool for avoiding memory leaks
  25526. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  25527. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  25528. BABYLON.UniformBuffer = UniformBuffer;
  25529. })(BABYLON || (BABYLON = {}));
  25530. //# sourceMappingURL=babylon.uniformBuffer.js.map
  25531. var BABYLON;
  25532. (function (BABYLON) {
  25533. var PushMaterial = (function (_super) {
  25534. __extends(PushMaterial, _super);
  25535. function PushMaterial(name, scene) {
  25536. var _this = _super.call(this, name, scene) || this;
  25537. _this.storeEffectOnSubMeshes = true;
  25538. return _this;
  25539. }
  25540. PushMaterial.prototype.getEffect = function () {
  25541. return this._activeEffect;
  25542. };
  25543. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  25544. if (!mesh) {
  25545. return false;
  25546. }
  25547. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25548. return true;
  25549. }
  25550. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  25551. };
  25552. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25553. this._activeEffect.setMatrix("world", world);
  25554. };
  25555. PushMaterial.prototype.bind = function (world, mesh) {
  25556. if (!mesh) {
  25557. return;
  25558. }
  25559. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  25560. };
  25561. PushMaterial.prototype._afterBind = function (mesh, effect) {
  25562. _super.prototype._afterBind.call(this, mesh);
  25563. this.getScene()._cachedEffect = effect;
  25564. };
  25565. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  25566. if (visibility === void 0) { visibility = 0; }
  25567. return scene.isCachedMaterialValid(this, effect, visibility);
  25568. };
  25569. return PushMaterial;
  25570. }(BABYLON.Material));
  25571. BABYLON.PushMaterial = PushMaterial;
  25572. })(BABYLON || (BABYLON = {}));
  25573. //# sourceMappingURL=babylon.pushMaterial.js.map
  25574. var BABYLON;
  25575. (function (BABYLON) {
  25576. var VertexData = (function () {
  25577. function VertexData() {
  25578. }
  25579. VertexData.prototype.set = function (data, kind) {
  25580. switch (kind) {
  25581. case BABYLON.VertexBuffer.PositionKind:
  25582. this.positions = data;
  25583. break;
  25584. case BABYLON.VertexBuffer.NormalKind:
  25585. this.normals = data;
  25586. break;
  25587. case BABYLON.VertexBuffer.TangentKind:
  25588. this.tangents = data;
  25589. break;
  25590. case BABYLON.VertexBuffer.UVKind:
  25591. this.uvs = data;
  25592. break;
  25593. case BABYLON.VertexBuffer.UV2Kind:
  25594. this.uvs2 = data;
  25595. break;
  25596. case BABYLON.VertexBuffer.UV3Kind:
  25597. this.uvs3 = data;
  25598. break;
  25599. case BABYLON.VertexBuffer.UV4Kind:
  25600. this.uvs4 = data;
  25601. break;
  25602. case BABYLON.VertexBuffer.UV5Kind:
  25603. this.uvs5 = data;
  25604. break;
  25605. case BABYLON.VertexBuffer.UV6Kind:
  25606. this.uvs6 = data;
  25607. break;
  25608. case BABYLON.VertexBuffer.ColorKind:
  25609. this.colors = data;
  25610. break;
  25611. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25612. this.matricesIndices = data;
  25613. break;
  25614. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25615. this.matricesWeights = data;
  25616. break;
  25617. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25618. this.matricesIndicesExtra = data;
  25619. break;
  25620. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25621. this.matricesWeightsExtra = data;
  25622. break;
  25623. }
  25624. };
  25625. /**
  25626. * Associates the vertexData to the passed Mesh.
  25627. * Sets it as updatable or not (default `false`).
  25628. * Returns the VertexData.
  25629. */
  25630. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25631. this._applyTo(mesh, updatable);
  25632. return this;
  25633. };
  25634. /**
  25635. * Associates the vertexData to the passed Geometry.
  25636. * Sets it as updatable or not (default `false`).
  25637. * Returns the VertexData.
  25638. */
  25639. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25640. this._applyTo(geometry, updatable);
  25641. return this;
  25642. };
  25643. /**
  25644. * Updates the associated mesh.
  25645. * Returns the VertexData.
  25646. */
  25647. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25648. this._update(mesh);
  25649. return this;
  25650. };
  25651. /**
  25652. * Updates the associated geometry.
  25653. * Returns the VertexData.
  25654. */
  25655. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25656. this._update(geometry);
  25657. return this;
  25658. };
  25659. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25660. if (this.positions) {
  25661. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25662. }
  25663. if (this.normals) {
  25664. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25665. }
  25666. if (this.tangents) {
  25667. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25668. }
  25669. if (this.uvs) {
  25670. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25671. }
  25672. if (this.uvs2) {
  25673. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25674. }
  25675. if (this.uvs3) {
  25676. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25677. }
  25678. if (this.uvs4) {
  25679. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25680. }
  25681. if (this.uvs5) {
  25682. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25683. }
  25684. if (this.uvs6) {
  25685. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25686. }
  25687. if (this.colors) {
  25688. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25689. }
  25690. if (this.matricesIndices) {
  25691. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25692. }
  25693. if (this.matricesWeights) {
  25694. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25695. }
  25696. if (this.matricesIndicesExtra) {
  25697. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25698. }
  25699. if (this.matricesWeightsExtra) {
  25700. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25701. }
  25702. if (this.indices) {
  25703. meshOrGeometry.setIndices(this.indices);
  25704. }
  25705. return this;
  25706. };
  25707. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25708. if (this.positions) {
  25709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25710. }
  25711. if (this.normals) {
  25712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25713. }
  25714. if (this.tangents) {
  25715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25716. }
  25717. if (this.uvs) {
  25718. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25719. }
  25720. if (this.uvs2) {
  25721. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25722. }
  25723. if (this.uvs3) {
  25724. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25725. }
  25726. if (this.uvs4) {
  25727. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25728. }
  25729. if (this.uvs5) {
  25730. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25731. }
  25732. if (this.uvs6) {
  25733. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25734. }
  25735. if (this.colors) {
  25736. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25737. }
  25738. if (this.matricesIndices) {
  25739. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25740. }
  25741. if (this.matricesWeights) {
  25742. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25743. }
  25744. if (this.matricesIndicesExtra) {
  25745. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25746. }
  25747. if (this.matricesWeightsExtra) {
  25748. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25749. }
  25750. if (this.indices) {
  25751. meshOrGeometry.setIndices(this.indices);
  25752. }
  25753. return this;
  25754. };
  25755. /**
  25756. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25757. * Returns the VertexData.
  25758. */
  25759. VertexData.prototype.transform = function (matrix) {
  25760. var transformed = BABYLON.Vector3.Zero();
  25761. var index;
  25762. if (this.positions) {
  25763. var position = BABYLON.Vector3.Zero();
  25764. for (index = 0; index < this.positions.length; index += 3) {
  25765. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25766. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25767. this.positions[index] = transformed.x;
  25768. this.positions[index + 1] = transformed.y;
  25769. this.positions[index + 2] = transformed.z;
  25770. }
  25771. }
  25772. if (this.normals) {
  25773. var normal = BABYLON.Vector3.Zero();
  25774. for (index = 0; index < this.normals.length; index += 3) {
  25775. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25776. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25777. this.normals[index] = transformed.x;
  25778. this.normals[index + 1] = transformed.y;
  25779. this.normals[index + 2] = transformed.z;
  25780. }
  25781. }
  25782. if (this.tangents) {
  25783. var tangent = BABYLON.Vector4.Zero();
  25784. var tangentTransformed = BABYLON.Vector4.Zero();
  25785. for (index = 0; index < this.tangents.length; index += 4) {
  25786. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25787. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25788. this.tangents[index] = tangentTransformed.x;
  25789. this.tangents[index + 1] = tangentTransformed.y;
  25790. this.tangents[index + 2] = tangentTransformed.z;
  25791. this.tangents[index + 3] = tangentTransformed.w;
  25792. }
  25793. }
  25794. return this;
  25795. };
  25796. /**
  25797. * Merges the passed VertexData into the current one.
  25798. * Returns the modified VertexData.
  25799. */
  25800. VertexData.prototype.merge = function (other) {
  25801. if (other.indices) {
  25802. if (!this.indices) {
  25803. this.indices = [];
  25804. }
  25805. var offset = this.positions ? this.positions.length / 3 : 0;
  25806. for (var index = 0; index < other.indices.length; index++) {
  25807. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25808. this.indices.push(other.indices[index] + offset);
  25809. }
  25810. }
  25811. this.positions = this._mergeElement(this.positions, other.positions);
  25812. this.normals = this._mergeElement(this.normals, other.normals);
  25813. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25814. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25815. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25816. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25817. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25818. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25819. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25820. this.colors = this._mergeElement(this.colors, other.colors);
  25821. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25822. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25823. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25824. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25825. return this;
  25826. };
  25827. VertexData.prototype._mergeElement = function (source, other) {
  25828. if (!other)
  25829. return source;
  25830. if (!source)
  25831. return other;
  25832. var len = other.length + source.length;
  25833. var isSrcTypedArray = source instanceof Float32Array;
  25834. var isOthTypedArray = other instanceof Float32Array;
  25835. // use non-loop method when the source is Float32Array
  25836. if (isSrcTypedArray) {
  25837. var ret32 = new Float32Array(len);
  25838. ret32.set(source);
  25839. ret32.set(other, source.length);
  25840. return ret32;
  25841. // source is number[], when other is also use concat
  25842. }
  25843. else if (!isOthTypedArray) {
  25844. return source.concat(other);
  25845. // source is a number[], but other is a Float32Array, loop required
  25846. }
  25847. else {
  25848. var ret = source.slice(0); // copy source to a separate array
  25849. for (var i = 0, len = other.length; i < len; i++) {
  25850. ret.push(other[i]);
  25851. }
  25852. return ret;
  25853. }
  25854. };
  25855. /**
  25856. * Serializes the VertexData.
  25857. * Returns a serialized object.
  25858. */
  25859. VertexData.prototype.serialize = function () {
  25860. var serializationObject = this.serialize();
  25861. if (this.positions) {
  25862. serializationObject.positions = this.positions;
  25863. }
  25864. if (this.normals) {
  25865. serializationObject.normals = this.normals;
  25866. }
  25867. if (this.tangents) {
  25868. serializationObject.tangents = this.tangents;
  25869. }
  25870. if (this.uvs) {
  25871. serializationObject.uvs = this.uvs;
  25872. }
  25873. if (this.uvs2) {
  25874. serializationObject.uvs2 = this.uvs2;
  25875. }
  25876. if (this.uvs3) {
  25877. serializationObject.uvs3 = this.uvs3;
  25878. }
  25879. if (this.uvs4) {
  25880. serializationObject.uvs4 = this.uvs4;
  25881. }
  25882. if (this.uvs5) {
  25883. serializationObject.uvs5 = this.uvs5;
  25884. }
  25885. if (this.uvs6) {
  25886. serializationObject.uvs6 = this.uvs6;
  25887. }
  25888. if (this.colors) {
  25889. serializationObject.colors = this.colors;
  25890. }
  25891. if (this.matricesIndices) {
  25892. serializationObject.matricesIndices = this.matricesIndices;
  25893. serializationObject.matricesIndices._isExpanded = true;
  25894. }
  25895. if (this.matricesWeights) {
  25896. serializationObject.matricesWeights = this.matricesWeights;
  25897. }
  25898. if (this.matricesIndicesExtra) {
  25899. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25900. serializationObject.matricesIndicesExtra._isExpanded = true;
  25901. }
  25902. if (this.matricesWeightsExtra) {
  25903. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25904. }
  25905. serializationObject.indices = this.indices;
  25906. return serializationObject;
  25907. };
  25908. // Statics
  25909. /**
  25910. * Returns the object VertexData associated to the passed mesh.
  25911. */
  25912. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25913. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25914. };
  25915. /**
  25916. * Returns the object VertexData associated to the passed geometry.
  25917. */
  25918. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25919. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25920. };
  25921. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25922. var result = new VertexData();
  25923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25924. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25925. }
  25926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25927. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25928. }
  25929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25930. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25931. }
  25932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25933. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25934. }
  25935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25936. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25937. }
  25938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25939. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25940. }
  25941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25942. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25943. }
  25944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25945. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25946. }
  25947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25948. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25949. }
  25950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25951. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25952. }
  25953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25954. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25955. }
  25956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25957. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25958. }
  25959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25960. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25961. }
  25962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25963. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25964. }
  25965. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25966. return result;
  25967. };
  25968. /**
  25969. * Creates the vertexData of the Ribbon.
  25970. */
  25971. VertexData.CreateRibbon = function (options) {
  25972. var pathArray = options.pathArray;
  25973. var closeArray = options.closeArray || false;
  25974. var closePath = options.closePath || false;
  25975. var invertUV = options.invertUV || false;
  25976. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25977. var offset = options.offset || defaultOffset;
  25978. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25979. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25980. var customUV = options.uvs;
  25981. var customColors = options.colors;
  25982. var positions = [];
  25983. var indices = [];
  25984. var normals = [];
  25985. var uvs = [];
  25986. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25987. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25988. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25989. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25990. var minlg; // minimal length among all paths from pathArray
  25991. var lg = []; // array of path lengths : nb of vertex per path
  25992. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25993. var p; // path iterator
  25994. var i; // point iterator
  25995. var j; // point iterator
  25996. // if single path in pathArray
  25997. if (pathArray.length < 2) {
  25998. var ar1 = [];
  25999. var ar2 = [];
  26000. for (i = 0; i < pathArray[0].length - offset; i++) {
  26001. ar1.push(pathArray[0][i]);
  26002. ar2.push(pathArray[0][i + offset]);
  26003. }
  26004. pathArray = [ar1, ar2];
  26005. }
  26006. // positions and horizontal distances (u)
  26007. var idc = 0;
  26008. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26009. var path;
  26010. var l;
  26011. minlg = pathArray[0].length;
  26012. var vectlg;
  26013. var dist;
  26014. for (p = 0; p < pathArray.length; p++) {
  26015. uTotalDistance[p] = 0;
  26016. us[p] = [0];
  26017. path = pathArray[p];
  26018. l = path.length;
  26019. minlg = (minlg < l) ? minlg : l;
  26020. j = 0;
  26021. while (j < l) {
  26022. positions.push(path[j].x, path[j].y, path[j].z);
  26023. if (j > 0) {
  26024. vectlg = path[j].subtract(path[j - 1]).length();
  26025. dist = vectlg + uTotalDistance[p];
  26026. us[p].push(dist);
  26027. uTotalDistance[p] = dist;
  26028. }
  26029. j++;
  26030. }
  26031. if (closePath) {
  26032. j--;
  26033. positions.push(path[0].x, path[0].y, path[0].z);
  26034. vectlg = path[j].subtract(path[0]).length();
  26035. dist = vectlg + uTotalDistance[p];
  26036. us[p].push(dist);
  26037. uTotalDistance[p] = dist;
  26038. }
  26039. lg[p] = l + closePathCorr;
  26040. idx[p] = idc;
  26041. idc += (l + closePathCorr);
  26042. }
  26043. // vertical distances (v)
  26044. var path1;
  26045. var path2;
  26046. var vertex1;
  26047. var vertex2;
  26048. for (i = 0; i < minlg + closePathCorr; i++) {
  26049. vTotalDistance[i] = 0;
  26050. vs[i] = [0];
  26051. for (p = 0; p < pathArray.length - 1; p++) {
  26052. path1 = pathArray[p];
  26053. path2 = pathArray[p + 1];
  26054. if (i === minlg) {
  26055. vertex1 = path1[0];
  26056. vertex2 = path2[0];
  26057. }
  26058. else {
  26059. vertex1 = path1[i];
  26060. vertex2 = path2[i];
  26061. }
  26062. vectlg = vertex2.subtract(vertex1).length();
  26063. dist = vectlg + vTotalDistance[i];
  26064. vs[i].push(dist);
  26065. vTotalDistance[i] = dist;
  26066. }
  26067. if (closeArray) {
  26068. path1 = pathArray[p];
  26069. path2 = pathArray[0];
  26070. if (i === minlg) {
  26071. vertex2 = path2[0];
  26072. }
  26073. vectlg = vertex2.subtract(vertex1).length();
  26074. dist = vectlg + vTotalDistance[i];
  26075. vTotalDistance[i] = dist;
  26076. }
  26077. }
  26078. // uvs
  26079. var u;
  26080. var v;
  26081. if (customUV) {
  26082. for (p = 0; p < customUV.length; p++) {
  26083. uvs.push(customUV[p].x, customUV[p].y);
  26084. }
  26085. }
  26086. else {
  26087. for (p = 0; p < pathArray.length; p++) {
  26088. for (i = 0; i < minlg + closePathCorr; i++) {
  26089. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26090. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26091. if (invertUV) {
  26092. uvs.push(v, u);
  26093. }
  26094. else {
  26095. uvs.push(u, v);
  26096. }
  26097. }
  26098. }
  26099. }
  26100. // indices
  26101. p = 0; // path index
  26102. var pi = 0; // positions array index
  26103. var l1 = lg[p] - 1; // path1 length
  26104. var l2 = lg[p + 1] - 1; // path2 length
  26105. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26106. var shft = idx[1] - idx[0]; // shift
  26107. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26108. while (pi <= min && p < path1nb) {
  26109. // 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
  26110. indices.push(pi, pi + shft, pi + 1);
  26111. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26112. pi += 1;
  26113. if (pi === min) {
  26114. p++;
  26115. if (p === lg.length - 1) {
  26116. shft = idx[0] - idx[p];
  26117. l1 = lg[p] - 1;
  26118. l2 = lg[0] - 1;
  26119. }
  26120. else {
  26121. shft = idx[p + 1] - idx[p];
  26122. l1 = lg[p] - 1;
  26123. l2 = lg[p + 1] - 1;
  26124. }
  26125. pi = idx[p];
  26126. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26127. }
  26128. }
  26129. // normals
  26130. VertexData.ComputeNormals(positions, indices, normals);
  26131. if (closePath) {
  26132. var indexFirst = 0;
  26133. var indexLast = 0;
  26134. for (p = 0; p < pathArray.length; p++) {
  26135. indexFirst = idx[p] * 3;
  26136. if (p + 1 < pathArray.length) {
  26137. indexLast = (idx[p + 1] - 1) * 3;
  26138. }
  26139. else {
  26140. indexLast = normals.length - 3;
  26141. }
  26142. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26143. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26144. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26145. normals[indexLast] = normals[indexFirst];
  26146. normals[indexLast + 1] = normals[indexFirst + 1];
  26147. normals[indexLast + 2] = normals[indexFirst + 2];
  26148. }
  26149. }
  26150. // sides
  26151. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26152. // Colors
  26153. if (customColors) {
  26154. var colors = new Float32Array(customColors.length * 4);
  26155. for (var c = 0; c < customColors.length; c++) {
  26156. colors[c * 4] = customColors[c].r;
  26157. colors[c * 4 + 1] = customColors[c].g;
  26158. colors[c * 4 + 2] = customColors[c].b;
  26159. colors[c * 4 + 3] = customColors[c].a;
  26160. }
  26161. }
  26162. // Result
  26163. var vertexData = new VertexData();
  26164. var positions32 = new Float32Array(positions);
  26165. var normals32 = new Float32Array(normals);
  26166. var uvs32 = new Float32Array(uvs);
  26167. vertexData.indices = indices;
  26168. vertexData.positions = positions32;
  26169. vertexData.normals = normals32;
  26170. vertexData.uvs = uvs32;
  26171. if (customColors) {
  26172. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26173. }
  26174. if (closePath) {
  26175. vertexData._idx = idx;
  26176. }
  26177. return vertexData;
  26178. };
  26179. /**
  26180. * Creates the VertexData of the Box.
  26181. */
  26182. VertexData.CreateBox = function (options) {
  26183. var normalsSource = [
  26184. new BABYLON.Vector3(0, 0, 1),
  26185. new BABYLON.Vector3(0, 0, -1),
  26186. new BABYLON.Vector3(1, 0, 0),
  26187. new BABYLON.Vector3(-1, 0, 0),
  26188. new BABYLON.Vector3(0, 1, 0),
  26189. new BABYLON.Vector3(0, -1, 0)
  26190. ];
  26191. var indices = [];
  26192. var positions = [];
  26193. var normals = [];
  26194. var uvs = [];
  26195. var width = options.width || options.size || 1;
  26196. var height = options.height || options.size || 1;
  26197. var depth = options.depth || options.size || 1;
  26198. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26199. var faceUV = options.faceUV || new Array(6);
  26200. var faceColors = options.faceColors;
  26201. var colors = [];
  26202. // default face colors and UV if undefined
  26203. for (var f = 0; f < 6; f++) {
  26204. if (faceUV[f] === undefined) {
  26205. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26206. }
  26207. if (faceColors && faceColors[f] === undefined) {
  26208. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26209. }
  26210. }
  26211. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26212. // Create each face in turn.
  26213. for (var index = 0; index < normalsSource.length; index++) {
  26214. var normal = normalsSource[index];
  26215. // Get two vectors perpendicular to the face normal and to each other.
  26216. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26217. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26218. // Six indices (two triangles) per face.
  26219. var verticesLength = positions.length / 3;
  26220. indices.push(verticesLength);
  26221. indices.push(verticesLength + 1);
  26222. indices.push(verticesLength + 2);
  26223. indices.push(verticesLength);
  26224. indices.push(verticesLength + 2);
  26225. indices.push(verticesLength + 3);
  26226. // Four vertices per face.
  26227. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26228. positions.push(vertex.x, vertex.y, vertex.z);
  26229. normals.push(normal.x, normal.y, normal.z);
  26230. uvs.push(faceUV[index].z, faceUV[index].w);
  26231. if (faceColors) {
  26232. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26233. }
  26234. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26235. positions.push(vertex.x, vertex.y, vertex.z);
  26236. normals.push(normal.x, normal.y, normal.z);
  26237. uvs.push(faceUV[index].x, faceUV[index].w);
  26238. if (faceColors) {
  26239. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26240. }
  26241. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26242. positions.push(vertex.x, vertex.y, vertex.z);
  26243. normals.push(normal.x, normal.y, normal.z);
  26244. uvs.push(faceUV[index].x, faceUV[index].y);
  26245. if (faceColors) {
  26246. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26247. }
  26248. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26249. positions.push(vertex.x, vertex.y, vertex.z);
  26250. normals.push(normal.x, normal.y, normal.z);
  26251. uvs.push(faceUV[index].z, faceUV[index].y);
  26252. if (faceColors) {
  26253. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26254. }
  26255. }
  26256. // sides
  26257. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26258. // Result
  26259. var vertexData = new VertexData();
  26260. vertexData.indices = indices;
  26261. vertexData.positions = positions;
  26262. vertexData.normals = normals;
  26263. vertexData.uvs = uvs;
  26264. if (faceColors) {
  26265. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26266. vertexData.colors = totalColors;
  26267. }
  26268. return vertexData;
  26269. };
  26270. /**
  26271. * Creates the VertexData of the Sphere.
  26272. */
  26273. VertexData.CreateSphere = function (options) {
  26274. var segments = options.segments || 32;
  26275. var diameterX = options.diameterX || options.diameter || 1;
  26276. var diameterY = options.diameterY || options.diameter || 1;
  26277. var diameterZ = options.diameterZ || options.diameter || 1;
  26278. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26279. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26280. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26281. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26282. var totalZRotationSteps = 2 + segments;
  26283. var totalYRotationSteps = 2 * totalZRotationSteps;
  26284. var indices = [];
  26285. var positions = [];
  26286. var normals = [];
  26287. var uvs = [];
  26288. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26289. var normalizedZ = zRotationStep / totalZRotationSteps;
  26290. var angleZ = normalizedZ * Math.PI * slice;
  26291. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26292. var normalizedY = yRotationStep / totalYRotationSteps;
  26293. var angleY = normalizedY * Math.PI * 2 * arc;
  26294. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26295. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26296. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26297. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26298. var vertex = complete.multiply(radius);
  26299. var normal = complete.divide(radius).normalize();
  26300. positions.push(vertex.x, vertex.y, vertex.z);
  26301. normals.push(normal.x, normal.y, normal.z);
  26302. uvs.push(normalizedY, normalizedZ);
  26303. }
  26304. if (zRotationStep > 0) {
  26305. var verticesCount = positions.length / 3;
  26306. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26307. indices.push((firstIndex));
  26308. indices.push((firstIndex + 1));
  26309. indices.push(firstIndex + totalYRotationSteps + 1);
  26310. indices.push((firstIndex + totalYRotationSteps + 1));
  26311. indices.push((firstIndex + 1));
  26312. indices.push((firstIndex + totalYRotationSteps + 2));
  26313. }
  26314. }
  26315. }
  26316. // Sides
  26317. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26318. // Result
  26319. var vertexData = new VertexData();
  26320. vertexData.indices = indices;
  26321. vertexData.positions = positions;
  26322. vertexData.normals = normals;
  26323. vertexData.uvs = uvs;
  26324. return vertexData;
  26325. };
  26326. /**
  26327. * Creates the VertexData of the Cylinder or Cone.
  26328. */
  26329. VertexData.CreateCylinder = function (options) {
  26330. var height = options.height || 2;
  26331. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26332. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  26333. var tessellation = options.tessellation || 24;
  26334. var subdivisions = options.subdivisions || 1;
  26335. var hasRings = options.hasRings;
  26336. var enclose = options.enclose;
  26337. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26338. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26339. var faceUV = options.faceUV || new Array(3);
  26340. var faceColors = options.faceColors;
  26341. // default face colors and UV if undefined
  26342. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26343. var ringNb = (hasRings) ? subdivisions : 1;
  26344. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26345. var f;
  26346. for (f = 0; f < surfaceNb; f++) {
  26347. if (faceColors && faceColors[f] === undefined) {
  26348. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26349. }
  26350. }
  26351. for (f = 0; f < surfaceNb; f++) {
  26352. if (faceUV && faceUV[f] === undefined) {
  26353. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26354. }
  26355. }
  26356. var indices = [];
  26357. var positions = [];
  26358. var normals = [];
  26359. var uvs = [];
  26360. var colors = [];
  26361. var angle_step = Math.PI * 2 * arc / tessellation;
  26362. var angle;
  26363. var h;
  26364. var radius;
  26365. var tan = (diameterBottom - diameterTop) / 2 / height;
  26366. var ringVertex = BABYLON.Vector3.Zero();
  26367. var ringNormal = BABYLON.Vector3.Zero();
  26368. var ringFirstVertex = BABYLON.Vector3.Zero();
  26369. var ringFirstNormal = BABYLON.Vector3.Zero();
  26370. var quadNormal = BABYLON.Vector3.Zero();
  26371. var Y = BABYLON.Axis.Y;
  26372. // positions, normals, uvs
  26373. var i;
  26374. var j;
  26375. var r;
  26376. var ringIdx = 1;
  26377. var s = 1; // surface index
  26378. var cs = 0;
  26379. var v = 0;
  26380. for (i = 0; i <= subdivisions; i++) {
  26381. h = i / subdivisions;
  26382. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26383. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26384. for (r = 0; r < ringIdx; r++) {
  26385. if (hasRings) {
  26386. s += r;
  26387. }
  26388. if (enclose) {
  26389. s += 2 * r;
  26390. }
  26391. for (j = 0; j <= tessellation; j++) {
  26392. angle = j * angle_step;
  26393. // position
  26394. ringVertex.x = Math.cos(-angle) * radius;
  26395. ringVertex.y = -height / 2 + h * height;
  26396. ringVertex.z = Math.sin(-angle) * radius;
  26397. // normal
  26398. if (diameterTop === 0 && i === subdivisions) {
  26399. // if no top cap, reuse former normals
  26400. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26401. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26402. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26403. }
  26404. else {
  26405. ringNormal.x = ringVertex.x;
  26406. ringNormal.z = ringVertex.z;
  26407. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26408. ringNormal.normalize();
  26409. }
  26410. // keep first ring vertex values for enclose
  26411. if (j === 0) {
  26412. ringFirstVertex.copyFrom(ringVertex);
  26413. ringFirstNormal.copyFrom(ringNormal);
  26414. }
  26415. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26416. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26417. if (hasRings) {
  26418. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26419. }
  26420. else {
  26421. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26422. }
  26423. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26424. if (faceColors) {
  26425. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26426. }
  26427. }
  26428. // if enclose, add four vertices and their dedicated normals
  26429. if (arc !== 1 && enclose) {
  26430. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26431. positions.push(0, ringVertex.y, 0);
  26432. positions.push(0, ringVertex.y, 0);
  26433. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26434. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26435. quadNormal.normalize();
  26436. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26437. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26438. quadNormal.normalize();
  26439. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26440. if (hasRings) {
  26441. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26442. }
  26443. else {
  26444. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26445. }
  26446. uvs.push(faceUV[s + 1].x, v);
  26447. uvs.push(faceUV[s + 1].z, v);
  26448. if (hasRings) {
  26449. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26450. }
  26451. else {
  26452. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26453. }
  26454. uvs.push(faceUV[s + 2].x, v);
  26455. uvs.push(faceUV[s + 2].z, v);
  26456. if (faceColors) {
  26457. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26458. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26459. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26460. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26461. }
  26462. }
  26463. if (cs !== s) {
  26464. cs = s;
  26465. }
  26466. }
  26467. }
  26468. // indices
  26469. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26470. var s;
  26471. i = 0;
  26472. for (s = 0; s < subdivisions; s++) {
  26473. for (j = 0; j < tessellation; j++) {
  26474. var i0 = i * (e + 1) + j;
  26475. var i1 = (i + 1) * (e + 1) + j;
  26476. var i2 = i * (e + 1) + (j + 1);
  26477. var i3 = (i + 1) * (e + 1) + (j + 1);
  26478. indices.push(i0, i1, i2);
  26479. indices.push(i3, i2, i1);
  26480. }
  26481. if (arc !== 1 && enclose) {
  26482. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26483. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26484. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26485. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26486. }
  26487. i = (hasRings) ? (i + 2) : (i + 1);
  26488. }
  26489. // Caps
  26490. var createCylinderCap = function (isTop) {
  26491. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26492. if (radius === 0) {
  26493. return;
  26494. }
  26495. // Cap positions, normals & uvs
  26496. var angle;
  26497. var circleVector;
  26498. var i;
  26499. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26500. var c;
  26501. if (faceColors) {
  26502. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26503. }
  26504. // cap center
  26505. var vbase = positions.length / 3;
  26506. var offset = isTop ? height / 2 : -height / 2;
  26507. var center = new BABYLON.Vector3(0, offset, 0);
  26508. positions.push(center.x, center.y, center.z);
  26509. normals.push(0, isTop ? 1 : -1, 0);
  26510. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26511. if (faceColors) {
  26512. colors.push(c.r, c.g, c.b, c.a);
  26513. }
  26514. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26515. for (i = 0; i <= tessellation; i++) {
  26516. angle = Math.PI * 2 * i * arc / tessellation;
  26517. var cos = Math.cos(-angle);
  26518. var sin = Math.sin(-angle);
  26519. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26520. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26521. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26522. normals.push(0, isTop ? 1 : -1, 0);
  26523. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26524. if (faceColors) {
  26525. colors.push(c.r, c.g, c.b, c.a);
  26526. }
  26527. }
  26528. // Cap indices
  26529. for (i = 0; i < tessellation; i++) {
  26530. if (!isTop) {
  26531. indices.push(vbase);
  26532. indices.push(vbase + (i + 1));
  26533. indices.push(vbase + (i + 2));
  26534. }
  26535. else {
  26536. indices.push(vbase);
  26537. indices.push(vbase + (i + 2));
  26538. indices.push(vbase + (i + 1));
  26539. }
  26540. }
  26541. };
  26542. // add caps to geometry
  26543. createCylinderCap(false);
  26544. createCylinderCap(true);
  26545. // Sides
  26546. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26547. var vertexData = new VertexData();
  26548. vertexData.indices = indices;
  26549. vertexData.positions = positions;
  26550. vertexData.normals = normals;
  26551. vertexData.uvs = uvs;
  26552. if (faceColors) {
  26553. vertexData.colors = colors;
  26554. }
  26555. return vertexData;
  26556. };
  26557. /**
  26558. * Creates the VertexData of the Torus.
  26559. */
  26560. VertexData.CreateTorus = function (options) {
  26561. var indices = [];
  26562. var positions = [];
  26563. var normals = [];
  26564. var uvs = [];
  26565. var diameter = options.diameter || 1;
  26566. var thickness = options.thickness || 0.5;
  26567. var tessellation = options.tessellation || 16;
  26568. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26569. var stride = tessellation + 1;
  26570. for (var i = 0; i <= tessellation; i++) {
  26571. var u = i / tessellation;
  26572. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26573. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26574. for (var j = 0; j <= tessellation; j++) {
  26575. var v = 1 - j / tessellation;
  26576. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26577. var dx = Math.cos(innerAngle);
  26578. var dy = Math.sin(innerAngle);
  26579. // Create a vertex.
  26580. var normal = new BABYLON.Vector3(dx, dy, 0);
  26581. var position = normal.scale(thickness / 2);
  26582. var textureCoordinate = new BABYLON.Vector2(u, v);
  26583. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26584. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26585. positions.push(position.x, position.y, position.z);
  26586. normals.push(normal.x, normal.y, normal.z);
  26587. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26588. // And create indices for two triangles.
  26589. var nextI = (i + 1) % stride;
  26590. var nextJ = (j + 1) % stride;
  26591. indices.push(i * stride + j);
  26592. indices.push(i * stride + nextJ);
  26593. indices.push(nextI * stride + j);
  26594. indices.push(i * stride + nextJ);
  26595. indices.push(nextI * stride + nextJ);
  26596. indices.push(nextI * stride + j);
  26597. }
  26598. }
  26599. // Sides
  26600. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26601. // Result
  26602. var vertexData = new VertexData();
  26603. vertexData.indices = indices;
  26604. vertexData.positions = positions;
  26605. vertexData.normals = normals;
  26606. vertexData.uvs = uvs;
  26607. return vertexData;
  26608. };
  26609. /**
  26610. * Creates the VertexData of the LineSystem.
  26611. */
  26612. VertexData.CreateLineSystem = function (options) {
  26613. var indices = [];
  26614. var positions = [];
  26615. var lines = options.lines;
  26616. var idx = 0;
  26617. for (var l = 0; l < lines.length; l++) {
  26618. var points = lines[l];
  26619. for (var index = 0; index < points.length; index++) {
  26620. positions.push(points[index].x, points[index].y, points[index].z);
  26621. if (index > 0) {
  26622. indices.push(idx - 1);
  26623. indices.push(idx);
  26624. }
  26625. idx++;
  26626. }
  26627. }
  26628. var vertexData = new VertexData();
  26629. vertexData.indices = indices;
  26630. vertexData.positions = positions;
  26631. return vertexData;
  26632. };
  26633. /**
  26634. * Create the VertexData of the DashedLines.
  26635. */
  26636. VertexData.CreateDashedLines = function (options) {
  26637. var dashSize = options.dashSize || 3;
  26638. var gapSize = options.gapSize || 1;
  26639. var dashNb = options.dashNb || 200;
  26640. var points = options.points;
  26641. var positions = new Array();
  26642. var indices = new Array();
  26643. var curvect = BABYLON.Vector3.Zero();
  26644. var lg = 0;
  26645. var nb = 0;
  26646. var shft = 0;
  26647. var dashshft = 0;
  26648. var curshft = 0;
  26649. var idx = 0;
  26650. var i = 0;
  26651. for (i = 0; i < points.length - 1; i++) {
  26652. points[i + 1].subtractToRef(points[i], curvect);
  26653. lg += curvect.length();
  26654. }
  26655. shft = lg / dashNb;
  26656. dashshft = dashSize * shft / (dashSize + gapSize);
  26657. for (i = 0; i < points.length - 1; i++) {
  26658. points[i + 1].subtractToRef(points[i], curvect);
  26659. nb = Math.floor(curvect.length() / shft);
  26660. curvect.normalize();
  26661. for (var j = 0; j < nb; j++) {
  26662. curshft = shft * j;
  26663. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26664. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26665. indices.push(idx, idx + 1);
  26666. idx += 2;
  26667. }
  26668. }
  26669. // Result
  26670. var vertexData = new VertexData();
  26671. vertexData.positions = positions;
  26672. vertexData.indices = indices;
  26673. return vertexData;
  26674. };
  26675. /**
  26676. * Creates the VertexData of the Ground.
  26677. */
  26678. VertexData.CreateGround = function (options) {
  26679. var indices = [];
  26680. var positions = [];
  26681. var normals = [];
  26682. var uvs = [];
  26683. var row, col;
  26684. var width = options.width || 1;
  26685. var height = options.height || 1;
  26686. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26687. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26688. for (row = 0; row <= subdivisionsY; row++) {
  26689. for (col = 0; col <= subdivisionsX; col++) {
  26690. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26691. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26692. positions.push(position.x, position.y, position.z);
  26693. normals.push(normal.x, normal.y, normal.z);
  26694. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26695. }
  26696. }
  26697. for (row = 0; row < subdivisionsY; row++) {
  26698. for (col = 0; col < subdivisionsX; col++) {
  26699. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26700. indices.push(col + 1 + row * (subdivisionsX + 1));
  26701. indices.push(col + row * (subdivisionsX + 1));
  26702. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26703. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26704. indices.push(col + row * (subdivisionsX + 1));
  26705. }
  26706. }
  26707. // Result
  26708. var vertexData = new VertexData();
  26709. vertexData.indices = indices;
  26710. vertexData.positions = positions;
  26711. vertexData.normals = normals;
  26712. vertexData.uvs = uvs;
  26713. return vertexData;
  26714. };
  26715. /**
  26716. * Creates the VertexData of the TiledGround.
  26717. */
  26718. VertexData.CreateTiledGround = function (options) {
  26719. var xmin = options.xmin || -1.0;
  26720. var zmin = options.zmin || -1.0;
  26721. var xmax = options.xmax || 1.0;
  26722. var zmax = options.zmax || 1.0;
  26723. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26724. var precision = options.precision || { w: 1, h: 1 };
  26725. var indices = [];
  26726. var positions = [];
  26727. var normals = [];
  26728. var uvs = [];
  26729. var row, col, tileRow, tileCol;
  26730. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26731. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26732. precision.w = (precision.w < 1) ? 1 : precision.w;
  26733. precision.h = (precision.h < 1) ? 1 : precision.h;
  26734. var tileSize = {
  26735. 'w': (xmax - xmin) / subdivisions.w,
  26736. 'h': (zmax - zmin) / subdivisions.h
  26737. };
  26738. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26739. // Indices
  26740. var base = positions.length / 3;
  26741. var rowLength = precision.w + 1;
  26742. for (row = 0; row < precision.h; row++) {
  26743. for (col = 0; col < precision.w; col++) {
  26744. var square = [
  26745. base + col + row * rowLength,
  26746. base + (col + 1) + row * rowLength,
  26747. base + (col + 1) + (row + 1) * rowLength,
  26748. base + col + (row + 1) * rowLength
  26749. ];
  26750. indices.push(square[1]);
  26751. indices.push(square[2]);
  26752. indices.push(square[3]);
  26753. indices.push(square[0]);
  26754. indices.push(square[1]);
  26755. indices.push(square[3]);
  26756. }
  26757. }
  26758. // Position, normals and uvs
  26759. var position = BABYLON.Vector3.Zero();
  26760. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26761. for (row = 0; row <= precision.h; row++) {
  26762. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26763. for (col = 0; col <= precision.w; col++) {
  26764. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26765. position.y = 0;
  26766. positions.push(position.x, position.y, position.z);
  26767. normals.push(normal.x, normal.y, normal.z);
  26768. uvs.push(col / precision.w, row / precision.h);
  26769. }
  26770. }
  26771. }
  26772. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26773. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26774. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26775. }
  26776. }
  26777. // Result
  26778. var vertexData = new VertexData();
  26779. vertexData.indices = indices;
  26780. vertexData.positions = positions;
  26781. vertexData.normals = normals;
  26782. vertexData.uvs = uvs;
  26783. return vertexData;
  26784. };
  26785. /**
  26786. * Creates the VertexData of the Ground designed from a heightmap.
  26787. */
  26788. VertexData.CreateGroundFromHeightMap = function (options) {
  26789. var indices = [];
  26790. var positions = [];
  26791. var normals = [];
  26792. var uvs = [];
  26793. var row, col;
  26794. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26795. // Vertices
  26796. for (row = 0; row <= options.subdivisions; row++) {
  26797. for (col = 0; col <= options.subdivisions; col++) {
  26798. 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));
  26799. // Compute height
  26800. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26801. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26802. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26803. var r = options.buffer[pos] / 255.0;
  26804. var g = options.buffer[pos + 1] / 255.0;
  26805. var b = options.buffer[pos + 2] / 255.0;
  26806. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26807. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26808. // Add vertex
  26809. positions.push(position.x, position.y, position.z);
  26810. normals.push(0, 0, 0);
  26811. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26812. }
  26813. }
  26814. // Indices
  26815. for (row = 0; row < options.subdivisions; row++) {
  26816. for (col = 0; col < options.subdivisions; col++) {
  26817. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26818. indices.push(col + 1 + row * (options.subdivisions + 1));
  26819. indices.push(col + row * (options.subdivisions + 1));
  26820. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26821. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26822. indices.push(col + row * (options.subdivisions + 1));
  26823. }
  26824. }
  26825. // Normals
  26826. VertexData.ComputeNormals(positions, indices, normals);
  26827. // Result
  26828. var vertexData = new VertexData();
  26829. vertexData.indices = indices;
  26830. vertexData.positions = positions;
  26831. vertexData.normals = normals;
  26832. vertexData.uvs = uvs;
  26833. return vertexData;
  26834. };
  26835. /**
  26836. * Creates the VertexData of the Plane.
  26837. */
  26838. VertexData.CreatePlane = function (options) {
  26839. var indices = [];
  26840. var positions = [];
  26841. var normals = [];
  26842. var uvs = [];
  26843. var width = options.width || options.size || 1;
  26844. var height = options.height || options.size || 1;
  26845. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26846. // Vertices
  26847. var halfWidth = width / 2.0;
  26848. var halfHeight = height / 2.0;
  26849. positions.push(-halfWidth, -halfHeight, 0);
  26850. normals.push(0, 0, -1.0);
  26851. uvs.push(0.0, 0.0);
  26852. positions.push(halfWidth, -halfHeight, 0);
  26853. normals.push(0, 0, -1.0);
  26854. uvs.push(1.0, 0.0);
  26855. positions.push(halfWidth, halfHeight, 0);
  26856. normals.push(0, 0, -1.0);
  26857. uvs.push(1.0, 1.0);
  26858. positions.push(-halfWidth, halfHeight, 0);
  26859. normals.push(0, 0, -1.0);
  26860. uvs.push(0.0, 1.0);
  26861. // Indices
  26862. indices.push(0);
  26863. indices.push(1);
  26864. indices.push(2);
  26865. indices.push(0);
  26866. indices.push(2);
  26867. indices.push(3);
  26868. // Sides
  26869. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26870. // Result
  26871. var vertexData = new VertexData();
  26872. vertexData.indices = indices;
  26873. vertexData.positions = positions;
  26874. vertexData.normals = normals;
  26875. vertexData.uvs = uvs;
  26876. return vertexData;
  26877. };
  26878. /**
  26879. * Creates the VertexData of the Disc or regular Polygon.
  26880. */
  26881. VertexData.CreateDisc = function (options) {
  26882. var positions = [];
  26883. var indices = [];
  26884. var normals = [];
  26885. var uvs = [];
  26886. var radius = options.radius || 0.5;
  26887. var tessellation = options.tessellation || 64;
  26888. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26889. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26890. // positions and uvs
  26891. positions.push(0, 0, 0); // disc center first
  26892. uvs.push(0.5, 0.5);
  26893. var theta = Math.PI * 2 * arc;
  26894. var step = theta / tessellation;
  26895. for (var a = 0; a < theta; a += step) {
  26896. var x = Math.cos(a);
  26897. var y = Math.sin(a);
  26898. var u = (x + 1) / 2;
  26899. var v = (1 - y) / 2;
  26900. positions.push(radius * x, radius * y, 0);
  26901. uvs.push(u, v);
  26902. }
  26903. if (arc === 1) {
  26904. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26905. uvs.push(uvs[2], uvs[3]);
  26906. }
  26907. //indices
  26908. var vertexNb = positions.length / 3;
  26909. for (var i = 1; i < vertexNb - 1; i++) {
  26910. indices.push(i + 1, 0, i);
  26911. }
  26912. // result
  26913. VertexData.ComputeNormals(positions, indices, normals);
  26914. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26915. var vertexData = new VertexData();
  26916. vertexData.indices = indices;
  26917. vertexData.positions = positions;
  26918. vertexData.normals = normals;
  26919. vertexData.uvs = uvs;
  26920. return vertexData;
  26921. };
  26922. /**
  26923. * Re-creates the VertexData of the Polygon for sideOrientation.
  26924. */
  26925. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26926. var faceUV = fUV || new Array(3);
  26927. var faceColors = fColors;
  26928. var colors = [];
  26929. // default face colors and UV if undefined
  26930. for (var f = 0; f < 3; f++) {
  26931. if (faceUV[f] === undefined) {
  26932. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26933. }
  26934. if (faceColors && faceColors[f] === undefined) {
  26935. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26936. }
  26937. }
  26938. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26939. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26940. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26941. var indices = polygon.getIndices();
  26942. // set face colours and textures
  26943. var idx = 0;
  26944. var face = 0;
  26945. for (var index = 0; index < normals.length; index += 3) {
  26946. //Edge Face no. 1
  26947. if (Math.abs(normals[index + 1]) < 0.001) {
  26948. face = 1;
  26949. }
  26950. //Top Face no. 0
  26951. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  26952. face = 0;
  26953. }
  26954. //Bottom Face no. 2
  26955. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  26956. face = 2;
  26957. }
  26958. idx = index / 3;
  26959. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26960. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26961. if (faceColors) {
  26962. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26963. }
  26964. }
  26965. // sides
  26966. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26967. // Result
  26968. var vertexData = new VertexData();
  26969. vertexData.indices = indices;
  26970. vertexData.positions = positions;
  26971. vertexData.normals = normals;
  26972. vertexData.uvs = uvs;
  26973. if (faceColors) {
  26974. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26975. vertexData.colors = totalColors;
  26976. }
  26977. return vertexData;
  26978. };
  26979. /**
  26980. * Creates the VertexData of the IcoSphere.
  26981. */
  26982. VertexData.CreateIcoSphere = function (options) {
  26983. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26984. var radius = options.radius || 1;
  26985. var flat = (options.flat === undefined) ? true : options.flat;
  26986. var subdivisions = options.subdivisions || 4;
  26987. var radiusX = options.radiusX || radius;
  26988. var radiusY = options.radiusY || radius;
  26989. var radiusZ = options.radiusZ || radius;
  26990. var t = (1 + Math.sqrt(5)) / 2;
  26991. // 12 vertex x,y,z
  26992. var ico_vertices = [
  26993. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26994. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26995. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26996. ];
  26997. // index of 3 vertex makes a face of icopshere
  26998. var ico_indices = [
  26999. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27000. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27001. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27002. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27003. ];
  27004. // vertex for uv have aliased position, not for UV
  27005. var vertices_unalias_id = [
  27006. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27007. // vertex alias
  27008. 0,
  27009. 2,
  27010. 3,
  27011. 3,
  27012. 3,
  27013. 4,
  27014. 7,
  27015. 8,
  27016. 9,
  27017. 9,
  27018. 10,
  27019. 11 // 23: B + 12
  27020. ];
  27021. // uv as integer step (not pixels !)
  27022. var ico_vertexuv = [
  27023. 5, 1, 3, 1, 6, 4, 0, 0,
  27024. 5, 3, 4, 2, 2, 2, 4, 0,
  27025. 2, 0, 1, 1, 6, 0, 6, 2,
  27026. // vertex alias (for same vertex on different faces)
  27027. 0, 4,
  27028. 3, 3,
  27029. 4, 4,
  27030. 3, 1,
  27031. 4, 2,
  27032. 4, 4,
  27033. 0, 2,
  27034. 1, 1,
  27035. 2, 2,
  27036. 3, 3,
  27037. 1, 3,
  27038. 2, 4 // 23: B + 12
  27039. ];
  27040. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27041. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27042. // First island of uv mapping
  27043. // v = 4h 3+ 2
  27044. // v = 3h 9+ 4
  27045. // v = 2h 9+ 5 B
  27046. // v = 1h 9 1 0
  27047. // v = 0h 3 8 7 A
  27048. // u = 0 1 2 3 4 5 6 *a
  27049. // Second island of uv mapping
  27050. // v = 4h 0+ B+ 4+
  27051. // v = 3h A+ 2+
  27052. // v = 2h 7+ 6 3+
  27053. // v = 1h 8+ 3+
  27054. // v = 0h
  27055. // u = 0 1 2 3 4 5 6 *a
  27056. // Face layout on texture UV mapping
  27057. // ============
  27058. // \ 4 /\ 16 / ======
  27059. // \ / \ / /\ 11 /
  27060. // \/ 7 \/ / \ /
  27061. // ======= / 10 \/
  27062. // /\ 17 /\ =======
  27063. // / \ / \ \ 15 /\
  27064. // / 8 \/ 12 \ \ / \
  27065. // ============ \/ 6 \
  27066. // \ 18 /\ ============
  27067. // \ / \ \ 5 /\ 0 /
  27068. // \/ 13 \ \ / \ /
  27069. // ======= \/ 1 \/
  27070. // =============
  27071. // /\ 19 /\ 2 /\
  27072. // / \ / \ / \
  27073. // / 14 \/ 9 \/ 3 \
  27074. // ===================
  27075. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27076. var ustep = 138 / 1024;
  27077. var vstep = 239 / 1024;
  27078. var uoffset = 60 / 1024;
  27079. var voffset = 26 / 1024;
  27080. // Second island should have margin, not to touch the first island
  27081. // avoid any borderline artefact in pixel rounding
  27082. var island_u_offset = -40 / 1024;
  27083. var island_v_offset = +20 / 1024;
  27084. // face is either island 0 or 1 :
  27085. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27086. var island = [
  27087. 0, 0, 0, 0, 1,
  27088. 0, 0, 1, 1, 0,
  27089. 0, 0, 1, 1, 0,
  27090. 0, 1, 1, 1, 0 // 15 - 19
  27091. ];
  27092. var indices = [];
  27093. var positions = [];
  27094. var normals = [];
  27095. var uvs = [];
  27096. var current_indice = 0;
  27097. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27098. var face_vertex_pos = new Array(3);
  27099. var face_vertex_uv = new Array(3);
  27100. var v012;
  27101. for (v012 = 0; v012 < 3; v012++) {
  27102. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27103. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27104. }
  27105. // create all with normals
  27106. for (var face = 0; face < 20; face++) {
  27107. // 3 vertex per face
  27108. for (v012 = 0; v012 < 3; v012++) {
  27109. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27110. var v_id = ico_indices[3 * face + v012];
  27111. // vertex have 3D position (x,y,z)
  27112. 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]);
  27113. // Normalize to get normal, then scale to radius
  27114. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27115. // uv Coordinates from vertex ID
  27116. 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);
  27117. }
  27118. // Subdivide the face (interpolate pos, norm, uv)
  27119. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27120. // - norm is linear interpolation of vertex corner normal
  27121. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27122. // - uv is linear interpolation
  27123. //
  27124. // Topology is as below for sub-divide by 2
  27125. // vertex shown as v0,v1,v2
  27126. // interp index is i1 to progress in range [v0,v1[
  27127. // interp index is i2 to progress in range [v0,v2[
  27128. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27129. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27130. //
  27131. //
  27132. // i2 v2
  27133. // ^ ^
  27134. // / / \
  27135. // / / \
  27136. // / / \
  27137. // / / (0,1) \
  27138. // / #---------\
  27139. // / / \ (0,0)'/ \
  27140. // / / \ / \
  27141. // / / \ / \
  27142. // / / (0,0) \ / (1,0) \
  27143. // / #---------#---------\
  27144. // v0 v1
  27145. //
  27146. // --------------------> i1
  27147. //
  27148. // interp of (i1,i2):
  27149. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27150. // along i1 : lerp(x0,x1, i1/(S-i2))
  27151. //
  27152. // centroid of triangle is needed to get help normal computation
  27153. // (c1,c2) are used for centroid location
  27154. var interp_vertex = function (i1, i2, c1, c2) {
  27155. // vertex is interpolated from
  27156. // - face_vertex_pos[0..2]
  27157. // - face_vertex_uv[0..2]
  27158. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27159. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27160. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27161. pos_interp.normalize();
  27162. var vertex_normal;
  27163. if (flat) {
  27164. // in flat mode, recalculate normal as face centroid normal
  27165. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27166. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27167. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27168. }
  27169. else {
  27170. // in smooth mode, recalculate normal from each single vertex position
  27171. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27172. }
  27173. // Vertex normal need correction due to X,Y,Z radius scaling
  27174. vertex_normal.x /= radiusX;
  27175. vertex_normal.y /= radiusY;
  27176. vertex_normal.z /= radiusZ;
  27177. vertex_normal.normalize();
  27178. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27179. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27180. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27181. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27182. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27183. uvs.push(uv_interp.x, uv_interp.y);
  27184. // push each vertex has member of a face
  27185. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27186. indices.push(current_indice);
  27187. current_indice++;
  27188. };
  27189. for (var i2 = 0; i2 < subdivisions; i2++) {
  27190. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27191. // face : (i1,i2) for /\ :
  27192. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27193. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27194. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27195. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27196. if (i1 + i2 + 1 < subdivisions) {
  27197. // face : (i1,i2)' for \/ :
  27198. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27199. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27200. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27201. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27202. }
  27203. }
  27204. }
  27205. }
  27206. // Sides
  27207. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27208. // Result
  27209. var vertexData = new VertexData();
  27210. vertexData.indices = indices;
  27211. vertexData.positions = positions;
  27212. vertexData.normals = normals;
  27213. vertexData.uvs = uvs;
  27214. return vertexData;
  27215. };
  27216. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27217. /**
  27218. * Creates the VertexData of the Polyhedron.
  27219. */
  27220. VertexData.CreatePolyhedron = function (options) {
  27221. // provided polyhedron types :
  27222. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27223. // 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)
  27224. var polyhedra = [];
  27225. 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]] };
  27226. 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]] };
  27227. polyhedra[2] = {
  27228. 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]],
  27229. 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]]
  27230. };
  27231. polyhedra[3] = {
  27232. 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]],
  27233. 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]]
  27234. };
  27235. polyhedra[4] = {
  27236. 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]],
  27237. 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]]
  27238. };
  27239. 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]] };
  27240. 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]] };
  27241. 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]] };
  27242. 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]] };
  27243. 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]] };
  27244. 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]] };
  27245. 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]] };
  27246. 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]] };
  27247. 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]] };
  27248. polyhedra[14] = {
  27249. 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]],
  27250. 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]]
  27251. };
  27252. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27253. var size = options.size;
  27254. var sizeX = options.sizeX || size || 1;
  27255. var sizeY = options.sizeY || size || 1;
  27256. var sizeZ = options.sizeZ || size || 1;
  27257. var data = options.custom || polyhedra[type];
  27258. var nbfaces = data.face.length;
  27259. var faceUV = options.faceUV || new Array(nbfaces);
  27260. var faceColors = options.faceColors;
  27261. var flat = (options.flat === undefined) ? true : options.flat;
  27262. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27263. var positions = [];
  27264. var indices = [];
  27265. var normals = [];
  27266. var uvs = [];
  27267. var colors = [];
  27268. var index = 0;
  27269. var faceIdx = 0; // face cursor in the array "indexes"
  27270. var indexes = [];
  27271. var i = 0;
  27272. var f = 0;
  27273. var u, v, ang, x, y, tmp;
  27274. // default face colors and UV if undefined
  27275. if (flat) {
  27276. for (f = 0; f < nbfaces; f++) {
  27277. if (faceColors && faceColors[f] === undefined) {
  27278. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27279. }
  27280. if (faceUV && faceUV[f] === undefined) {
  27281. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27282. }
  27283. }
  27284. }
  27285. if (!flat) {
  27286. for (i = 0; i < data.vertex.length; i++) {
  27287. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27288. uvs.push(0, 0);
  27289. }
  27290. for (f = 0; f < nbfaces; f++) {
  27291. for (i = 0; i < data.face[f].length - 2; i++) {
  27292. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27293. }
  27294. }
  27295. }
  27296. else {
  27297. for (f = 0; f < nbfaces; f++) {
  27298. var fl = data.face[f].length; // number of vertices of the current face
  27299. ang = 2 * Math.PI / fl;
  27300. x = 0.5 * Math.tan(ang / 2);
  27301. y = 0.5;
  27302. // positions, uvs, colors
  27303. for (i = 0; i < fl; i++) {
  27304. // positions
  27305. 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);
  27306. indexes.push(index);
  27307. index++;
  27308. // uvs
  27309. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27310. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27311. uvs.push(u, v);
  27312. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27313. y = x * Math.sin(ang) + y * Math.cos(ang);
  27314. x = tmp;
  27315. // colors
  27316. if (faceColors) {
  27317. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27318. }
  27319. }
  27320. // indices from indexes
  27321. for (i = 0; i < fl - 2; i++) {
  27322. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27323. }
  27324. faceIdx += fl;
  27325. }
  27326. }
  27327. VertexData.ComputeNormals(positions, indices, normals);
  27328. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27329. var vertexData = new VertexData();
  27330. vertexData.positions = positions;
  27331. vertexData.indices = indices;
  27332. vertexData.normals = normals;
  27333. vertexData.uvs = uvs;
  27334. if (faceColors && flat) {
  27335. vertexData.colors = colors;
  27336. }
  27337. return vertexData;
  27338. };
  27339. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27340. /**
  27341. * Creates the VertexData of the Torus Knot.
  27342. */
  27343. VertexData.CreateTorusKnot = function (options) {
  27344. var indices = [];
  27345. var positions = [];
  27346. var normals = [];
  27347. var uvs = [];
  27348. var radius = options.radius || 2;
  27349. var tube = options.tube || 0.5;
  27350. var radialSegments = options.radialSegments || 32;
  27351. var tubularSegments = options.tubularSegments || 32;
  27352. var p = options.p || 2;
  27353. var q = options.q || 3;
  27354. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27355. // Helper
  27356. var getPos = function (angle) {
  27357. var cu = Math.cos(angle);
  27358. var su = Math.sin(angle);
  27359. var quOverP = q / p * angle;
  27360. var cs = Math.cos(quOverP);
  27361. var tx = radius * (2 + cs) * 0.5 * cu;
  27362. var ty = radius * (2 + cs) * su * 0.5;
  27363. var tz = radius * Math.sin(quOverP) * 0.5;
  27364. return new BABYLON.Vector3(tx, ty, tz);
  27365. };
  27366. // Vertices
  27367. var i;
  27368. var j;
  27369. for (i = 0; i <= radialSegments; i++) {
  27370. var modI = i % radialSegments;
  27371. var u = modI / radialSegments * 2 * p * Math.PI;
  27372. var p1 = getPos(u);
  27373. var p2 = getPos(u + 0.01);
  27374. var tang = p2.subtract(p1);
  27375. var n = p2.add(p1);
  27376. var bitan = BABYLON.Vector3.Cross(tang, n);
  27377. n = BABYLON.Vector3.Cross(bitan, tang);
  27378. bitan.normalize();
  27379. n.normalize();
  27380. for (j = 0; j < tubularSegments; j++) {
  27381. var modJ = j % tubularSegments;
  27382. var v = modJ / tubularSegments * 2 * Math.PI;
  27383. var cx = -tube * Math.cos(v);
  27384. var cy = tube * Math.sin(v);
  27385. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27386. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27387. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27388. uvs.push(i / radialSegments);
  27389. uvs.push(j / tubularSegments);
  27390. }
  27391. }
  27392. for (i = 0; i < radialSegments; i++) {
  27393. for (j = 0; j < tubularSegments; j++) {
  27394. var jNext = (j + 1) % tubularSegments;
  27395. var a = i * tubularSegments + j;
  27396. var b = (i + 1) * tubularSegments + j;
  27397. var c = (i + 1) * tubularSegments + jNext;
  27398. var d = i * tubularSegments + jNext;
  27399. indices.push(d);
  27400. indices.push(b);
  27401. indices.push(a);
  27402. indices.push(d);
  27403. indices.push(c);
  27404. indices.push(b);
  27405. }
  27406. }
  27407. // Normals
  27408. VertexData.ComputeNormals(positions, indices, normals);
  27409. // Sides
  27410. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27411. // Result
  27412. var vertexData = new VertexData();
  27413. vertexData.indices = indices;
  27414. vertexData.positions = positions;
  27415. vertexData.normals = normals;
  27416. vertexData.uvs = uvs;
  27417. return vertexData;
  27418. };
  27419. // Tools
  27420. /**
  27421. * @param {any} - positions (number[] or Float32Array)
  27422. * @param {any} - indices (number[] or Uint16Array)
  27423. * @param {any} - normals (number[] or Float32Array)
  27424. * options (optional) :
  27425. * facetPositions : optional array of facet positions (vector3)
  27426. * facetNormals : optional array of facet normals (vector3)
  27427. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  27428. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  27429. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  27430. * bbSize : optional bounding box size data, required for facetPartitioning computation
  27431. * bInfo : optional bounding info, required for facetPartitioning computation
  27432. */
  27433. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  27434. // temporary scalar variables
  27435. var index = 0; // facet index
  27436. var p1p2x = 0.0; // p1p2 vector x coordinate
  27437. var p1p2y = 0.0; // p1p2 vector y coordinate
  27438. var p1p2z = 0.0; // p1p2 vector z coordinate
  27439. var p3p2x = 0.0; // p3p2 vector x coordinate
  27440. var p3p2y = 0.0; // p3p2 vector y coordinate
  27441. var p3p2z = 0.0; // p3p2 vector z coordinate
  27442. var faceNormalx = 0.0; // facet normal x coordinate
  27443. var faceNormaly = 0.0; // facet normal y coordinate
  27444. var faceNormalz = 0.0; // facet normal z coordinate
  27445. var length = 0.0; // facet normal length before normalization
  27446. var v1x = 0; // vector1 x index in the positions array
  27447. var v1y = 0; // vector1 y index in the positions array
  27448. var v1z = 0; // vector1 z index in the positions array
  27449. var v2x = 0; // vector2 x index in the positions array
  27450. var v2y = 0; // vector2 y index in the positions array
  27451. var v2z = 0; // vector2 z index in the positions array
  27452. var v3x = 0; // vector3 x index in the positions array
  27453. var v3y = 0; // vector3 y index in the positions array
  27454. var v3z = 0; // vector3 z index in the positions array
  27455. var computeFacetNormals = false;
  27456. var computeFacetPositions = false;
  27457. var computeFacetPartitioning = false;
  27458. var faceNormalSign = 1;
  27459. if (options) {
  27460. computeFacetNormals = (options.facetNormals) ? true : false;
  27461. computeFacetPositions = (options.facetPositions) ? true : false;
  27462. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  27463. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  27464. }
  27465. // facetPartitioning reinit if needed
  27466. if (computeFacetPartitioning) {
  27467. var ox = 0; // X partitioning index for facet position
  27468. var oy = 0; // Y partinioning index for facet position
  27469. var oz = 0; // Z partinioning index for facet position
  27470. var b1x = 0; // X partitioning index for facet v1 vertex
  27471. var b1y = 0; // Y partitioning index for facet v1 vertex
  27472. var b1z = 0; // z partitioning index for facet v1 vertex
  27473. var b2x = 0; // X partitioning index for facet v2 vertex
  27474. var b2y = 0; // Y partitioning index for facet v2 vertex
  27475. var b2z = 0; // Z partitioning index for facet v2 vertex
  27476. var b3x = 0; // X partitioning index for facet v3 vertex
  27477. var b3y = 0; // Y partitioning index for facet v3 vertex
  27478. var b3z = 0; // Z partitioning index for facet v3 vertex
  27479. var block_idx_o = 0; // facet barycenter block index
  27480. var block_idx_v1 = 0; // v1 vertex block index
  27481. var block_idx_v2 = 0; // v2 vertex block index
  27482. var block_idx_v3 = 0; // v3 vertex block index
  27483. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  27484. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  27485. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  27486. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  27487. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  27488. var subSq = options.subDiv.max * options.subDiv.max;
  27489. options.facetPartitioning.length = 0;
  27490. }
  27491. // reset the normals
  27492. for (index = 0; index < positions.length; index++) {
  27493. normals[index] = 0.0;
  27494. }
  27495. // Loop : 1 indice triplet = 1 facet
  27496. var nbFaces = indices.length / 3;
  27497. for (index = 0; index < nbFaces; index++) {
  27498. // get the indexes of the coordinates of each vertex of the facet
  27499. v1x = indices[index * 3] * 3;
  27500. v1y = v1x + 1;
  27501. v1z = v1x + 2;
  27502. v2x = indices[index * 3 + 1] * 3;
  27503. v2y = v2x + 1;
  27504. v2z = v2x + 2;
  27505. v3x = indices[index * 3 + 2] * 3;
  27506. v3y = v3x + 1;
  27507. v3z = v3x + 2;
  27508. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  27509. p1p2y = positions[v1y] - positions[v2y];
  27510. p1p2z = positions[v1z] - positions[v2z];
  27511. p3p2x = positions[v3x] - positions[v2x];
  27512. p3p2y = positions[v3y] - positions[v2y];
  27513. p3p2z = positions[v3z] - positions[v2z];
  27514. // compute the face normal with the cross product
  27515. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  27516. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  27517. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  27518. // normalize this normal and store it in the array facetData
  27519. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27520. length = (length === 0) ? 1.0 : length;
  27521. faceNormalx /= length;
  27522. faceNormaly /= length;
  27523. faceNormalz /= length;
  27524. if (computeFacetNormals) {
  27525. options.facetNormals[index].x = faceNormalx;
  27526. options.facetNormals[index].y = faceNormaly;
  27527. options.facetNormals[index].z = faceNormalz;
  27528. }
  27529. if (computeFacetPositions) {
  27530. // compute and the facet barycenter coordinates in the array facetPositions
  27531. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  27532. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  27533. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  27534. }
  27535. if (computeFacetPartitioning) {
  27536. // store the facet indexes in arrays in the main facetPartitioning array :
  27537. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  27538. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27539. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27540. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27541. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27542. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27543. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27544. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27545. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27546. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27547. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27548. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27549. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27550. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  27551. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  27552. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  27553. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  27554. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  27555. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  27556. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  27557. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  27558. // push each facet index in each block containing the vertex
  27559. options.facetPartitioning[block_idx_v1].push(index);
  27560. if (block_idx_v2 != block_idx_v1) {
  27561. options.facetPartitioning[block_idx_v2].push(index);
  27562. }
  27563. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  27564. options.facetPartitioning[block_idx_v3].push(index);
  27565. }
  27566. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  27567. options.facetPartitioning[block_idx_o].push(index);
  27568. }
  27569. }
  27570. // compute the normals anyway
  27571. normals[v1x] += faceNormalx; // accumulate all the normals per face
  27572. normals[v1y] += faceNormaly;
  27573. normals[v1z] += faceNormalz;
  27574. normals[v2x] += faceNormalx;
  27575. normals[v2y] += faceNormaly;
  27576. normals[v2z] += faceNormalz;
  27577. normals[v3x] += faceNormalx;
  27578. normals[v3y] += faceNormaly;
  27579. normals[v3z] += faceNormalz;
  27580. }
  27581. // last normalization of each normal
  27582. for (index = 0; index < normals.length / 3; index++) {
  27583. faceNormalx = normals[index * 3];
  27584. faceNormaly = normals[index * 3 + 1];
  27585. faceNormalz = normals[index * 3 + 2];
  27586. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27587. length = (length === 0) ? 1.0 : length;
  27588. faceNormalx /= length;
  27589. faceNormaly /= length;
  27590. faceNormalz /= length;
  27591. normals[index * 3] = faceNormalx;
  27592. normals[index * 3 + 1] = faceNormaly;
  27593. normals[index * 3 + 2] = faceNormalz;
  27594. }
  27595. };
  27596. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  27597. var li = indices.length;
  27598. var ln = normals.length;
  27599. var i;
  27600. var n;
  27601. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27602. switch (sideOrientation) {
  27603. case BABYLON.Mesh.FRONTSIDE:
  27604. // nothing changed
  27605. break;
  27606. case BABYLON.Mesh.BACKSIDE:
  27607. var tmp;
  27608. // indices
  27609. for (i = 0; i < li; i += 3) {
  27610. tmp = indices[i];
  27611. indices[i] = indices[i + 2];
  27612. indices[i + 2] = tmp;
  27613. }
  27614. // normals
  27615. for (n = 0; n < ln; n++) {
  27616. normals[n] = -normals[n];
  27617. }
  27618. break;
  27619. case BABYLON.Mesh.DOUBLESIDE:
  27620. // positions
  27621. var lp = positions.length;
  27622. var l = lp / 3;
  27623. for (var p = 0; p < lp; p++) {
  27624. positions[lp + p] = positions[p];
  27625. }
  27626. // indices
  27627. for (i = 0; i < li; i += 3) {
  27628. indices[i + li] = indices[i + 2] + l;
  27629. indices[i + 1 + li] = indices[i + 1] + l;
  27630. indices[i + 2 + li] = indices[i] + l;
  27631. }
  27632. // normals
  27633. for (n = 0; n < ln; n++) {
  27634. normals[ln + n] = -normals[n];
  27635. }
  27636. // uvs
  27637. var lu = uvs.length;
  27638. var u = 0;
  27639. for (u = 0; u < lu; u++) {
  27640. uvs[u + lu] = uvs[u];
  27641. }
  27642. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27643. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27644. u = 0;
  27645. for (i = 0; i < lu / 2; i++) {
  27646. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27647. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27648. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27649. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27650. u += 2;
  27651. }
  27652. break;
  27653. }
  27654. };
  27655. /**
  27656. * Creates a new VertexData from the imported parameters.
  27657. */
  27658. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27659. var vertexData = new VertexData();
  27660. // positions
  27661. var positions = parsedVertexData.positions;
  27662. if (positions) {
  27663. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27664. }
  27665. // normals
  27666. var normals = parsedVertexData.normals;
  27667. if (normals) {
  27668. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27669. }
  27670. // tangents
  27671. var tangents = parsedVertexData.tangents;
  27672. if (tangents) {
  27673. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27674. }
  27675. // uvs
  27676. var uvs = parsedVertexData.uvs;
  27677. if (uvs) {
  27678. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27679. }
  27680. // uv2s
  27681. var uv2s = parsedVertexData.uv2s;
  27682. if (uv2s) {
  27683. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27684. }
  27685. // uv3s
  27686. var uv3s = parsedVertexData.uv3s;
  27687. if (uv3s) {
  27688. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27689. }
  27690. // uv4s
  27691. var uv4s = parsedVertexData.uv4s;
  27692. if (uv4s) {
  27693. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27694. }
  27695. // uv5s
  27696. var uv5s = parsedVertexData.uv5s;
  27697. if (uv5s) {
  27698. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27699. }
  27700. // uv6s
  27701. var uv6s = parsedVertexData.uv6s;
  27702. if (uv6s) {
  27703. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27704. }
  27705. // colors
  27706. var colors = parsedVertexData.colors;
  27707. if (colors) {
  27708. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27709. }
  27710. // matricesIndices
  27711. var matricesIndices = parsedVertexData.matricesIndices;
  27712. if (matricesIndices) {
  27713. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27714. }
  27715. // matricesWeights
  27716. var matricesWeights = parsedVertexData.matricesWeights;
  27717. if (matricesWeights) {
  27718. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27719. }
  27720. // indices
  27721. var indices = parsedVertexData.indices;
  27722. if (indices) {
  27723. vertexData.indices = indices;
  27724. }
  27725. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27726. };
  27727. return VertexData;
  27728. }());
  27729. BABYLON.VertexData = VertexData;
  27730. })(BABYLON || (BABYLON = {}));
  27731. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27732. var BABYLON;
  27733. (function (BABYLON) {
  27734. var Geometry = (function () {
  27735. function Geometry(id, scene, vertexData, updatable, mesh) {
  27736. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27737. this._totalVertices = 0;
  27738. this._isDisposed = false;
  27739. this.id = id;
  27740. this._engine = scene.getEngine();
  27741. this._meshes = [];
  27742. this._scene = scene;
  27743. //Init vertex buffer cache
  27744. this._vertexBuffers = {};
  27745. this._indices = [];
  27746. this._updatable = updatable;
  27747. // vertexData
  27748. if (vertexData) {
  27749. this.setAllVerticesData(vertexData, updatable);
  27750. }
  27751. else {
  27752. this._totalVertices = 0;
  27753. this._indices = [];
  27754. }
  27755. if (this._engine.getCaps().vertexArrayObject) {
  27756. this._vertexArrayObjects = {};
  27757. }
  27758. // applyToMesh
  27759. if (mesh) {
  27760. if (mesh.getClassName() === "LinesMesh") {
  27761. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27762. this.updateExtend();
  27763. }
  27764. this.applyToMesh(mesh);
  27765. mesh.computeWorldMatrix(true);
  27766. }
  27767. }
  27768. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27769. /**
  27770. * 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
  27771. * @returns The Bias Vector
  27772. */
  27773. get: function () {
  27774. return this._boundingBias;
  27775. },
  27776. set: function (value) {
  27777. if (this._boundingBias && this._boundingBias.equals(value)) {
  27778. return;
  27779. }
  27780. this._boundingBias = value.clone();
  27781. this.updateBoundingInfo(true, null);
  27782. },
  27783. enumerable: true,
  27784. configurable: true
  27785. });
  27786. Object.defineProperty(Geometry.prototype, "extend", {
  27787. get: function () {
  27788. return this._extend;
  27789. },
  27790. enumerable: true,
  27791. configurable: true
  27792. });
  27793. Geometry.prototype.getScene = function () {
  27794. return this._scene;
  27795. };
  27796. Geometry.prototype.getEngine = function () {
  27797. return this._engine;
  27798. };
  27799. Geometry.prototype.isReady = function () {
  27800. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27801. };
  27802. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27803. get: function () {
  27804. for (var index = 0; index < this._meshes.length; index++) {
  27805. if (!this._meshes[index].doNotSerialize) {
  27806. return false;
  27807. }
  27808. }
  27809. return true;
  27810. },
  27811. enumerable: true,
  27812. configurable: true
  27813. });
  27814. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27815. vertexData.applyToGeometry(this, updatable);
  27816. this.notifyUpdate();
  27817. };
  27818. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27819. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27820. this.setVerticesBuffer(buffer);
  27821. };
  27822. Geometry.prototype.removeVerticesData = function (kind) {
  27823. if (this._vertexBuffers[kind]) {
  27824. this._vertexBuffers[kind].dispose();
  27825. delete this._vertexBuffers[kind];
  27826. }
  27827. };
  27828. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27829. var kind = buffer.getKind();
  27830. if (this._vertexBuffers[kind]) {
  27831. this._vertexBuffers[kind].dispose();
  27832. }
  27833. this._vertexBuffers[kind] = buffer;
  27834. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27835. var data = buffer.getData();
  27836. var stride = buffer.getStrideSize();
  27837. this._totalVertices = data.length / stride;
  27838. this.updateExtend(data, stride);
  27839. this._resetPointsArrayCache();
  27840. var meshes = this._meshes;
  27841. var numOfMeshes = meshes.length;
  27842. for (var index = 0; index < numOfMeshes; index++) {
  27843. var mesh = meshes[index];
  27844. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27845. mesh._createGlobalSubMesh(false);
  27846. mesh.computeWorldMatrix(true);
  27847. }
  27848. }
  27849. this.notifyUpdate(kind);
  27850. if (this._vertexArrayObjects) {
  27851. this._disposeVertexArrayObjects();
  27852. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27853. }
  27854. };
  27855. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27856. var vertexBuffer = this.getVertexBuffer(kind);
  27857. if (!vertexBuffer) {
  27858. return;
  27859. }
  27860. vertexBuffer.updateDirectly(data, offset);
  27861. this.notifyUpdate(kind);
  27862. };
  27863. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27864. var vertexBuffer = this.getVertexBuffer(kind);
  27865. if (!vertexBuffer) {
  27866. return;
  27867. }
  27868. vertexBuffer.update(data);
  27869. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27870. var stride = vertexBuffer.getStrideSize();
  27871. this._totalVertices = data.length / stride;
  27872. this.updateBoundingInfo(updateExtends, data);
  27873. }
  27874. this.notifyUpdate(kind);
  27875. };
  27876. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27877. if (updateExtends) {
  27878. this.updateExtend(data);
  27879. }
  27880. var meshes = this._meshes;
  27881. var numOfMeshes = meshes.length;
  27882. this._resetPointsArrayCache();
  27883. for (var index = 0; index < numOfMeshes; index++) {
  27884. var mesh = meshes[index];
  27885. if (updateExtends) {
  27886. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27887. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27888. var subMesh = mesh.subMeshes[subIndex];
  27889. subMesh.refreshBoundingInfo();
  27890. }
  27891. }
  27892. }
  27893. };
  27894. Geometry.prototype._bind = function (effect, indexToBind) {
  27895. if (indexToBind === void 0) { indexToBind = undefined; }
  27896. if (indexToBind === undefined) {
  27897. indexToBind = this._indexBuffer;
  27898. }
  27899. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27900. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27901. return;
  27902. }
  27903. // Using VAO
  27904. if (!this._vertexArrayObjects[effect.key]) {
  27905. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27906. }
  27907. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27908. };
  27909. Geometry.prototype.getTotalVertices = function () {
  27910. if (!this.isReady()) {
  27911. return 0;
  27912. }
  27913. return this._totalVertices;
  27914. };
  27915. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27916. var vertexBuffer = this.getVertexBuffer(kind);
  27917. if (!vertexBuffer) {
  27918. return null;
  27919. }
  27920. var orig = vertexBuffer.getData();
  27921. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27922. return orig;
  27923. }
  27924. else {
  27925. var len = orig.length;
  27926. var copy = [];
  27927. for (var i = 0; i < len; i++) {
  27928. copy.push(orig[i]);
  27929. }
  27930. return copy;
  27931. }
  27932. };
  27933. Geometry.prototype.getVertexBuffer = function (kind) {
  27934. if (!this.isReady()) {
  27935. return null;
  27936. }
  27937. return this._vertexBuffers[kind];
  27938. };
  27939. Geometry.prototype.getVertexBuffers = function () {
  27940. if (!this.isReady()) {
  27941. return null;
  27942. }
  27943. return this._vertexBuffers;
  27944. };
  27945. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27946. if (!this._vertexBuffers) {
  27947. if (this._delayInfo) {
  27948. return this._delayInfo.indexOf(kind) !== -1;
  27949. }
  27950. return false;
  27951. }
  27952. return this._vertexBuffers[kind] !== undefined;
  27953. };
  27954. Geometry.prototype.getVerticesDataKinds = function () {
  27955. var result = [];
  27956. var kind;
  27957. if (!this._vertexBuffers && this._delayInfo) {
  27958. for (kind in this._delayInfo) {
  27959. result.push(kind);
  27960. }
  27961. }
  27962. else {
  27963. for (kind in this._vertexBuffers) {
  27964. result.push(kind);
  27965. }
  27966. }
  27967. return result;
  27968. };
  27969. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27970. if (this._indexBuffer) {
  27971. this._engine._releaseBuffer(this._indexBuffer);
  27972. }
  27973. this._disposeVertexArrayObjects();
  27974. this._indices = indices;
  27975. if (this._meshes.length !== 0 && this._indices) {
  27976. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27977. }
  27978. if (totalVertices !== undefined) {
  27979. this._totalVertices = totalVertices;
  27980. }
  27981. var meshes = this._meshes;
  27982. var numOfMeshes = meshes.length;
  27983. for (var index = 0; index < numOfMeshes; index++) {
  27984. meshes[index]._createGlobalSubMesh(true);
  27985. }
  27986. this.notifyUpdate();
  27987. };
  27988. Geometry.prototype.getTotalIndices = function () {
  27989. if (!this.isReady()) {
  27990. return 0;
  27991. }
  27992. return this._indices.length;
  27993. };
  27994. Geometry.prototype.getIndices = function (copyWhenShared) {
  27995. if (!this.isReady()) {
  27996. return null;
  27997. }
  27998. var orig = this._indices;
  27999. if (!copyWhenShared || this._meshes.length === 1) {
  28000. return orig;
  28001. }
  28002. else {
  28003. var len = orig.length;
  28004. var copy = [];
  28005. for (var i = 0; i < len; i++) {
  28006. copy.push(orig[i]);
  28007. }
  28008. return copy;
  28009. }
  28010. };
  28011. Geometry.prototype.getIndexBuffer = function () {
  28012. if (!this.isReady()) {
  28013. return null;
  28014. }
  28015. return this._indexBuffer;
  28016. };
  28017. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28018. if (!effect || !this._vertexArrayObjects) {
  28019. return;
  28020. }
  28021. if (this._vertexArrayObjects[effect.key]) {
  28022. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28023. delete this._vertexArrayObjects[effect.key];
  28024. }
  28025. };
  28026. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28027. var meshes = this._meshes;
  28028. var index = meshes.indexOf(mesh);
  28029. if (index === -1) {
  28030. return;
  28031. }
  28032. meshes.splice(index, 1);
  28033. mesh._geometry = null;
  28034. if (meshes.length === 0 && shouldDispose) {
  28035. this.dispose();
  28036. }
  28037. };
  28038. Geometry.prototype.applyToMesh = function (mesh) {
  28039. if (mesh._geometry === this) {
  28040. return;
  28041. }
  28042. var previousGeometry = mesh._geometry;
  28043. if (previousGeometry) {
  28044. previousGeometry.releaseForMesh(mesh);
  28045. }
  28046. var meshes = this._meshes;
  28047. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28048. mesh._geometry = this;
  28049. this._scene.pushGeometry(this);
  28050. meshes.push(mesh);
  28051. if (this.isReady()) {
  28052. this._applyToMesh(mesh);
  28053. }
  28054. else {
  28055. mesh._boundingInfo = this._boundingInfo;
  28056. }
  28057. };
  28058. Geometry.prototype.updateExtend = function (data, stride) {
  28059. if (data === void 0) { data = null; }
  28060. if (!data) {
  28061. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28062. }
  28063. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28064. };
  28065. Geometry.prototype._applyToMesh = function (mesh) {
  28066. var numOfMeshes = this._meshes.length;
  28067. // vertexBuffers
  28068. for (var kind in this._vertexBuffers) {
  28069. if (numOfMeshes === 1) {
  28070. this._vertexBuffers[kind].create();
  28071. }
  28072. var buffer = this._vertexBuffers[kind].getBuffer();
  28073. if (buffer)
  28074. buffer.references = numOfMeshes;
  28075. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28076. if (!this._extend) {
  28077. this.updateExtend(this._vertexBuffers[kind].getData());
  28078. }
  28079. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28080. mesh._createGlobalSubMesh(false);
  28081. //bounding info was just created again, world matrix should be applied again.
  28082. mesh._updateBoundingInfo();
  28083. }
  28084. }
  28085. // indexBuffer
  28086. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28087. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28088. }
  28089. if (this._indexBuffer) {
  28090. this._indexBuffer.references = numOfMeshes;
  28091. }
  28092. };
  28093. Geometry.prototype.notifyUpdate = function (kind) {
  28094. if (this.onGeometryUpdated) {
  28095. this.onGeometryUpdated(this, kind);
  28096. }
  28097. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28098. var mesh = _a[_i];
  28099. mesh._markSubMeshesAsAttributesDirty();
  28100. }
  28101. };
  28102. Geometry.prototype.load = function (scene, onLoaded) {
  28103. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28104. return;
  28105. }
  28106. if (this.isReady()) {
  28107. if (onLoaded) {
  28108. onLoaded();
  28109. }
  28110. return;
  28111. }
  28112. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28113. this._queueLoad(scene, onLoaded);
  28114. };
  28115. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28116. var _this = this;
  28117. scene._addPendingData(this);
  28118. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28119. _this._delayLoadingFunction(JSON.parse(data), _this);
  28120. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28121. _this._delayInfo = [];
  28122. scene._removePendingData(_this);
  28123. var meshes = _this._meshes;
  28124. var numOfMeshes = meshes.length;
  28125. for (var index = 0; index < numOfMeshes; index++) {
  28126. _this._applyToMesh(meshes[index]);
  28127. }
  28128. if (onLoaded) {
  28129. onLoaded();
  28130. }
  28131. }, function () { }, scene.database);
  28132. };
  28133. /**
  28134. * Invert the geometry to move from a right handed system to a left handed one.
  28135. */
  28136. Geometry.prototype.toLeftHanded = function () {
  28137. // Flip faces
  28138. var tIndices = this.getIndices(false);
  28139. if (tIndices != null && tIndices.length > 0) {
  28140. for (var i = 0; i < tIndices.length; i += 3) {
  28141. var tTemp = tIndices[i + 0];
  28142. tIndices[i + 0] = tIndices[i + 2];
  28143. tIndices[i + 2] = tTemp;
  28144. }
  28145. this.setIndices(tIndices);
  28146. }
  28147. // Negate position.z
  28148. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28149. if (tPositions != null && tPositions.length > 0) {
  28150. for (var i = 0; i < tPositions.length; i += 3) {
  28151. tPositions[i + 2] = -tPositions[i + 2];
  28152. }
  28153. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28154. }
  28155. // Negate normal.z
  28156. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28157. if (tNormals != null && tNormals.length > 0) {
  28158. for (var i = 0; i < tNormals.length; i += 3) {
  28159. tNormals[i + 2] = -tNormals[i + 2];
  28160. }
  28161. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28162. }
  28163. };
  28164. // Cache
  28165. Geometry.prototype._resetPointsArrayCache = function () {
  28166. this._positions = null;
  28167. };
  28168. Geometry.prototype._generatePointsArray = function () {
  28169. if (this._positions)
  28170. return true;
  28171. this._positions = [];
  28172. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28173. if (!data) {
  28174. return false;
  28175. }
  28176. for (var index = 0; index < data.length; index += 3) {
  28177. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28178. }
  28179. return true;
  28180. };
  28181. Geometry.prototype.isDisposed = function () {
  28182. return this._isDisposed;
  28183. };
  28184. Geometry.prototype._disposeVertexArrayObjects = function () {
  28185. if (this._vertexArrayObjects) {
  28186. for (var kind in this._vertexArrayObjects) {
  28187. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28188. }
  28189. this._vertexArrayObjects = {};
  28190. }
  28191. };
  28192. Geometry.prototype.dispose = function () {
  28193. var meshes = this._meshes;
  28194. var numOfMeshes = meshes.length;
  28195. var index;
  28196. for (index = 0; index < numOfMeshes; index++) {
  28197. this.releaseForMesh(meshes[index]);
  28198. }
  28199. this._meshes = [];
  28200. this._disposeVertexArrayObjects();
  28201. for (var kind in this._vertexBuffers) {
  28202. this._vertexBuffers[kind].dispose();
  28203. }
  28204. this._vertexBuffers = {};
  28205. this._totalVertices = 0;
  28206. if (this._indexBuffer) {
  28207. this._engine._releaseBuffer(this._indexBuffer);
  28208. }
  28209. this._indexBuffer = null;
  28210. this._indices = [];
  28211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28212. this.delayLoadingFile = null;
  28213. this._delayLoadingFunction = null;
  28214. this._delayInfo = [];
  28215. this._boundingInfo = null;
  28216. this._scene.removeGeometry(this);
  28217. this._isDisposed = true;
  28218. };
  28219. Geometry.prototype.copy = function (id) {
  28220. var vertexData = new BABYLON.VertexData();
  28221. vertexData.indices = [];
  28222. var indices = this.getIndices();
  28223. for (var index = 0; index < indices.length; index++) {
  28224. vertexData.indices.push(indices[index]);
  28225. }
  28226. var updatable = false;
  28227. var stopChecking = false;
  28228. var kind;
  28229. for (kind in this._vertexBuffers) {
  28230. // using slice() to make a copy of the array and not just reference it
  28231. var data = this.getVerticesData(kind);
  28232. if (data instanceof Float32Array) {
  28233. vertexData.set(new Float32Array(data), kind);
  28234. }
  28235. else {
  28236. vertexData.set(data.slice(0), kind);
  28237. }
  28238. if (!stopChecking) {
  28239. updatable = this.getVertexBuffer(kind).isUpdatable();
  28240. stopChecking = !updatable;
  28241. }
  28242. }
  28243. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28244. geometry.delayLoadState = this.delayLoadState;
  28245. geometry.delayLoadingFile = this.delayLoadingFile;
  28246. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28247. for (kind in this._delayInfo) {
  28248. geometry._delayInfo = geometry._delayInfo || [];
  28249. geometry._delayInfo.push(kind);
  28250. }
  28251. // Bounding info
  28252. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28253. return geometry;
  28254. };
  28255. Geometry.prototype.serialize = function () {
  28256. var serializationObject = {};
  28257. serializationObject.id = this.id;
  28258. serializationObject.updatable = this._updatable;
  28259. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28260. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28261. }
  28262. return serializationObject;
  28263. };
  28264. Geometry.prototype.toNumberArray = function (origin) {
  28265. if (Array.isArray(origin)) {
  28266. return origin;
  28267. }
  28268. else {
  28269. return Array.prototype.slice.call(origin);
  28270. }
  28271. };
  28272. Geometry.prototype.serializeVerticeData = function () {
  28273. var serializationObject = this.serialize();
  28274. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28275. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28276. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28277. serializationObject.positions._updatable = true;
  28278. }
  28279. }
  28280. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28281. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28282. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28283. serializationObject.normals._updatable = true;
  28284. }
  28285. }
  28286. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28287. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28288. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28289. serializationObject.uvs._updatable = true;
  28290. }
  28291. }
  28292. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28293. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28294. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28295. serializationObject.uv2s._updatable = true;
  28296. }
  28297. }
  28298. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28299. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28300. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28301. serializationObject.uv3s._updatable = true;
  28302. }
  28303. }
  28304. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28305. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28306. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28307. serializationObject.uv4s._updatable = true;
  28308. }
  28309. }
  28310. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28311. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28312. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28313. serializationObject.uv5s._updatable = true;
  28314. }
  28315. }
  28316. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28317. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  28318. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  28319. serializationObject.uv6s._updatable = true;
  28320. }
  28321. }
  28322. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28323. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  28324. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  28325. serializationObject.colors._updatable = true;
  28326. }
  28327. }
  28328. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28329. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  28330. serializationObject.matricesIndices._isExpanded = true;
  28331. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  28332. serializationObject.matricesIndices._updatable = true;
  28333. }
  28334. }
  28335. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28336. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  28337. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  28338. serializationObject.matricesWeights._updatable = true;
  28339. }
  28340. }
  28341. serializationObject.indices = this.toNumberArray(this.getIndices());
  28342. return serializationObject;
  28343. };
  28344. // Statics
  28345. Geometry.ExtractFromMesh = function (mesh, id) {
  28346. var geometry = mesh._geometry;
  28347. if (!geometry) {
  28348. return null;
  28349. }
  28350. return geometry.copy(id);
  28351. };
  28352. /**
  28353. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  28354. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28355. * Be aware Math.random() could cause collisions, but:
  28356. * "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"
  28357. */
  28358. Geometry.RandomId = function () {
  28359. return BABYLON.Tools.RandomId();
  28360. };
  28361. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28362. var scene = mesh.getScene();
  28363. // Geometry
  28364. var geometryId = parsedGeometry.geometryId;
  28365. if (geometryId) {
  28366. var geometry = scene.getGeometryByID(geometryId);
  28367. if (geometry) {
  28368. geometry.applyToMesh(mesh);
  28369. }
  28370. }
  28371. else if (parsedGeometry instanceof ArrayBuffer) {
  28372. var binaryInfo = mesh._binaryInfo;
  28373. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28374. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28375. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28376. }
  28377. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28378. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28379. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28380. }
  28381. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28382. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28383. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28384. }
  28385. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28386. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28387. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28388. }
  28389. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28390. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28391. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28392. }
  28393. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28394. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28395. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28396. }
  28397. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28398. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28399. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28400. }
  28401. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28402. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28403. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28404. }
  28405. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28406. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28407. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28408. }
  28409. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28410. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28411. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28412. }
  28413. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28414. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28415. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28416. }
  28417. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28418. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28419. mesh.setIndices(indicesData);
  28420. }
  28421. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28422. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28423. mesh.subMeshes = [];
  28424. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28425. var materialIndex = subMeshesData[(i * 5) + 0];
  28426. var verticesStart = subMeshesData[(i * 5) + 1];
  28427. var verticesCount = subMeshesData[(i * 5) + 2];
  28428. var indexStart = subMeshesData[(i * 5) + 3];
  28429. var indexCount = subMeshesData[(i * 5) + 4];
  28430. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28431. }
  28432. }
  28433. }
  28434. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28435. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  28436. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  28437. if (parsedGeometry.uvs) {
  28438. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  28439. }
  28440. if (parsedGeometry.uvs2) {
  28441. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  28442. }
  28443. if (parsedGeometry.uvs3) {
  28444. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  28445. }
  28446. if (parsedGeometry.uvs4) {
  28447. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  28448. }
  28449. if (parsedGeometry.uvs5) {
  28450. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  28451. }
  28452. if (parsedGeometry.uvs6) {
  28453. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  28454. }
  28455. if (parsedGeometry.colors) {
  28456. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  28457. }
  28458. if (parsedGeometry.matricesIndices) {
  28459. if (!parsedGeometry.matricesIndices._isExpanded) {
  28460. var floatIndices = [];
  28461. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28462. var matricesIndex = parsedGeometry.matricesIndices[i];
  28463. floatIndices.push(matricesIndex & 0x000000FF);
  28464. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28465. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28466. floatIndices.push(matricesIndex >> 24);
  28467. }
  28468. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  28469. }
  28470. else {
  28471. delete parsedGeometry.matricesIndices._isExpanded;
  28472. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  28473. }
  28474. }
  28475. if (parsedGeometry.matricesIndicesExtra) {
  28476. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28477. var floatIndices = [];
  28478. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28479. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28480. floatIndices.push(matricesIndex & 0x000000FF);
  28481. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28482. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28483. floatIndices.push(matricesIndex >> 24);
  28484. }
  28485. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  28486. }
  28487. else {
  28488. delete parsedGeometry.matricesIndices._isExpanded;
  28489. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  28490. }
  28491. }
  28492. if (parsedGeometry.matricesWeights) {
  28493. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  28494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  28495. }
  28496. if (parsedGeometry.matricesWeightsExtra) {
  28497. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  28498. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  28499. }
  28500. mesh.setIndices(parsedGeometry.indices);
  28501. }
  28502. // SubMeshes
  28503. if (parsedGeometry.subMeshes) {
  28504. mesh.subMeshes = [];
  28505. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28506. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28507. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28508. }
  28509. }
  28510. // Flat shading
  28511. if (mesh._shouldGenerateFlatShading) {
  28512. mesh.convertToFlatShadedMesh();
  28513. delete mesh._shouldGenerateFlatShading;
  28514. }
  28515. // Update
  28516. mesh.computeWorldMatrix(true);
  28517. // Octree
  28518. if (scene['_selectionOctree']) {
  28519. scene['_selectionOctree'].addMesh(mesh);
  28520. }
  28521. };
  28522. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  28523. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  28524. return;
  28525. }
  28526. var size = matricesWeights.length;
  28527. for (var i = 0; i < size; i += influencers) {
  28528. var weight = 0;
  28529. var biggerIndex = i;
  28530. var biggerWeight = 0;
  28531. for (var j = 0; j < influencers - 1; j++) {
  28532. weight += matricesWeights[i + j];
  28533. if (matricesWeights[i + j] > biggerWeight) {
  28534. biggerWeight = matricesWeights[i + j];
  28535. biggerIndex = i + j;
  28536. }
  28537. }
  28538. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  28539. }
  28540. };
  28541. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28542. if (scene.getGeometryByID(parsedVertexData.id)) {
  28543. return null; // null since geometry could be something else than a box...
  28544. }
  28545. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  28546. if (BABYLON.Tags) {
  28547. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28548. }
  28549. if (parsedVertexData.delayLoadingFile) {
  28550. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28551. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28552. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28553. geometry._delayInfo = [];
  28554. if (parsedVertexData.hasUVs) {
  28555. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28556. }
  28557. if (parsedVertexData.hasUVs2) {
  28558. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28559. }
  28560. if (parsedVertexData.hasUVs3) {
  28561. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28562. }
  28563. if (parsedVertexData.hasUVs4) {
  28564. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28565. }
  28566. if (parsedVertexData.hasUVs5) {
  28567. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28568. }
  28569. if (parsedVertexData.hasUVs6) {
  28570. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28571. }
  28572. if (parsedVertexData.hasColors) {
  28573. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28574. }
  28575. if (parsedVertexData.hasMatricesIndices) {
  28576. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28577. }
  28578. if (parsedVertexData.hasMatricesWeights) {
  28579. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28580. }
  28581. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28582. }
  28583. else {
  28584. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28585. }
  28586. scene.pushGeometry(geometry, true);
  28587. return geometry;
  28588. };
  28589. return Geometry;
  28590. }());
  28591. BABYLON.Geometry = Geometry;
  28592. /////// Primitives //////////////////////////////////////////////
  28593. (function (Geometry) {
  28594. var Primitives;
  28595. (function (Primitives) {
  28596. /// Abstract class
  28597. var _Primitive = (function (_super) {
  28598. __extends(_Primitive, _super);
  28599. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28600. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  28601. _this._canBeRegenerated = _canBeRegenerated;
  28602. _this._beingRegenerated = true;
  28603. _this.regenerate();
  28604. _this._beingRegenerated = false;
  28605. return _this;
  28606. }
  28607. _Primitive.prototype.canBeRegenerated = function () {
  28608. return this._canBeRegenerated;
  28609. };
  28610. _Primitive.prototype.regenerate = function () {
  28611. if (!this._canBeRegenerated) {
  28612. return;
  28613. }
  28614. this._beingRegenerated = true;
  28615. this.setAllVerticesData(this._regenerateVertexData(), false);
  28616. this._beingRegenerated = false;
  28617. };
  28618. _Primitive.prototype.asNewGeometry = function (id) {
  28619. return _super.prototype.copy.call(this, id);
  28620. };
  28621. // overrides
  28622. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28623. if (!this._beingRegenerated) {
  28624. return;
  28625. }
  28626. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28627. };
  28628. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28629. if (!this._beingRegenerated) {
  28630. return;
  28631. }
  28632. _super.prototype.setVerticesData.call(this, kind, data, false);
  28633. };
  28634. // to override
  28635. // protected
  28636. _Primitive.prototype._regenerateVertexData = function () {
  28637. throw new Error("Abstract method");
  28638. };
  28639. _Primitive.prototype.copy = function (id) {
  28640. throw new Error("Must be overriden in sub-classes.");
  28641. };
  28642. _Primitive.prototype.serialize = function () {
  28643. var serializationObject = _super.prototype.serialize.call(this);
  28644. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28645. return serializationObject;
  28646. };
  28647. return _Primitive;
  28648. }(Geometry));
  28649. Primitives._Primitive = _Primitive;
  28650. var Ribbon = (function (_super) {
  28651. __extends(Ribbon, _super);
  28652. // Members
  28653. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28654. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28655. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28656. _this.pathArray = pathArray;
  28657. _this.closeArray = closeArray;
  28658. _this.closePath = closePath;
  28659. _this.offset = offset;
  28660. _this.side = side;
  28661. return _this;
  28662. }
  28663. Ribbon.prototype._regenerateVertexData = function () {
  28664. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28665. };
  28666. Ribbon.prototype.copy = function (id) {
  28667. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28668. };
  28669. return Ribbon;
  28670. }(_Primitive));
  28671. Primitives.Ribbon = Ribbon;
  28672. var Box = (function (_super) {
  28673. __extends(Box, _super);
  28674. // Members
  28675. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28676. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28677. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28678. _this.size = size;
  28679. _this.side = side;
  28680. return _this;
  28681. }
  28682. Box.prototype._regenerateVertexData = function () {
  28683. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28684. };
  28685. Box.prototype.copy = function (id) {
  28686. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28687. };
  28688. Box.prototype.serialize = function () {
  28689. var serializationObject = _super.prototype.serialize.call(this);
  28690. serializationObject.size = this.size;
  28691. return serializationObject;
  28692. };
  28693. Box.Parse = function (parsedBox, scene) {
  28694. if (scene.getGeometryByID(parsedBox.id)) {
  28695. return null; // null since geometry could be something else than a box...
  28696. }
  28697. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28698. if (BABYLON.Tags) {
  28699. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28700. }
  28701. scene.pushGeometry(box, true);
  28702. return box;
  28703. };
  28704. return Box;
  28705. }(_Primitive));
  28706. Primitives.Box = Box;
  28707. var Sphere = (function (_super) {
  28708. __extends(Sphere, _super);
  28709. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28711. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28712. _this.segments = segments;
  28713. _this.diameter = diameter;
  28714. _this.side = side;
  28715. return _this;
  28716. }
  28717. Sphere.prototype._regenerateVertexData = function () {
  28718. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28719. };
  28720. Sphere.prototype.copy = function (id) {
  28721. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28722. };
  28723. Sphere.prototype.serialize = function () {
  28724. var serializationObject = _super.prototype.serialize.call(this);
  28725. serializationObject.segments = this.segments;
  28726. serializationObject.diameter = this.diameter;
  28727. return serializationObject;
  28728. };
  28729. Sphere.Parse = function (parsedSphere, scene) {
  28730. if (scene.getGeometryByID(parsedSphere.id)) {
  28731. return null; // null since geometry could be something else than a sphere...
  28732. }
  28733. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28734. if (BABYLON.Tags) {
  28735. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28736. }
  28737. scene.pushGeometry(sphere, true);
  28738. return sphere;
  28739. };
  28740. return Sphere;
  28741. }(_Primitive));
  28742. Primitives.Sphere = Sphere;
  28743. var Disc = (function (_super) {
  28744. __extends(Disc, _super);
  28745. // Members
  28746. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28747. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28748. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28749. _this.radius = radius;
  28750. _this.tessellation = tessellation;
  28751. _this.side = side;
  28752. return _this;
  28753. }
  28754. Disc.prototype._regenerateVertexData = function () {
  28755. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28756. };
  28757. Disc.prototype.copy = function (id) {
  28758. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28759. };
  28760. return Disc;
  28761. }(_Primitive));
  28762. Primitives.Disc = Disc;
  28763. var Cylinder = (function (_super) {
  28764. __extends(Cylinder, _super);
  28765. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28766. if (subdivisions === void 0) { subdivisions = 1; }
  28767. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28768. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28769. _this.height = height;
  28770. _this.diameterTop = diameterTop;
  28771. _this.diameterBottom = diameterBottom;
  28772. _this.tessellation = tessellation;
  28773. _this.subdivisions = subdivisions;
  28774. _this.side = side;
  28775. return _this;
  28776. }
  28777. Cylinder.prototype._regenerateVertexData = function () {
  28778. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28779. };
  28780. Cylinder.prototype.copy = function (id) {
  28781. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28782. };
  28783. Cylinder.prototype.serialize = function () {
  28784. var serializationObject = _super.prototype.serialize.call(this);
  28785. serializationObject.height = this.height;
  28786. serializationObject.diameterTop = this.diameterTop;
  28787. serializationObject.diameterBottom = this.diameterBottom;
  28788. serializationObject.tessellation = this.tessellation;
  28789. return serializationObject;
  28790. };
  28791. Cylinder.Parse = function (parsedCylinder, scene) {
  28792. if (scene.getGeometryByID(parsedCylinder.id)) {
  28793. return null; // null since geometry could be something else than a cylinder...
  28794. }
  28795. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28796. if (BABYLON.Tags) {
  28797. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28798. }
  28799. scene.pushGeometry(cylinder, true);
  28800. return cylinder;
  28801. };
  28802. return Cylinder;
  28803. }(_Primitive));
  28804. Primitives.Cylinder = Cylinder;
  28805. var Torus = (function (_super) {
  28806. __extends(Torus, _super);
  28807. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28808. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28809. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28810. _this.diameter = diameter;
  28811. _this.thickness = thickness;
  28812. _this.tessellation = tessellation;
  28813. _this.side = side;
  28814. return _this;
  28815. }
  28816. Torus.prototype._regenerateVertexData = function () {
  28817. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28818. };
  28819. Torus.prototype.copy = function (id) {
  28820. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28821. };
  28822. Torus.prototype.serialize = function () {
  28823. var serializationObject = _super.prototype.serialize.call(this);
  28824. serializationObject.diameter = this.diameter;
  28825. serializationObject.thickness = this.thickness;
  28826. serializationObject.tessellation = this.tessellation;
  28827. return serializationObject;
  28828. };
  28829. Torus.Parse = function (parsedTorus, scene) {
  28830. if (scene.getGeometryByID(parsedTorus.id)) {
  28831. return null; // null since geometry could be something else than a torus...
  28832. }
  28833. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28834. if (BABYLON.Tags) {
  28835. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28836. }
  28837. scene.pushGeometry(torus, true);
  28838. return torus;
  28839. };
  28840. return Torus;
  28841. }(_Primitive));
  28842. Primitives.Torus = Torus;
  28843. var Ground = (function (_super) {
  28844. __extends(Ground, _super);
  28845. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28846. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28847. _this.width = width;
  28848. _this.height = height;
  28849. _this.subdivisions = subdivisions;
  28850. return _this;
  28851. }
  28852. Ground.prototype._regenerateVertexData = function () {
  28853. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28854. };
  28855. Ground.prototype.copy = function (id) {
  28856. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28857. };
  28858. Ground.prototype.serialize = function () {
  28859. var serializationObject = _super.prototype.serialize.call(this);
  28860. serializationObject.width = this.width;
  28861. serializationObject.height = this.height;
  28862. serializationObject.subdivisions = this.subdivisions;
  28863. return serializationObject;
  28864. };
  28865. Ground.Parse = function (parsedGround, scene) {
  28866. if (scene.getGeometryByID(parsedGround.id)) {
  28867. return null; // null since geometry could be something else than a ground...
  28868. }
  28869. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28870. if (BABYLON.Tags) {
  28871. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28872. }
  28873. scene.pushGeometry(ground, true);
  28874. return ground;
  28875. };
  28876. return Ground;
  28877. }(_Primitive));
  28878. Primitives.Ground = Ground;
  28879. var TiledGround = (function (_super) {
  28880. __extends(TiledGround, _super);
  28881. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28882. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28883. _this.xmin = xmin;
  28884. _this.zmin = zmin;
  28885. _this.xmax = xmax;
  28886. _this.zmax = zmax;
  28887. _this.subdivisions = subdivisions;
  28888. _this.precision = precision;
  28889. return _this;
  28890. }
  28891. TiledGround.prototype._regenerateVertexData = function () {
  28892. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28893. };
  28894. TiledGround.prototype.copy = function (id) {
  28895. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28896. };
  28897. return TiledGround;
  28898. }(_Primitive));
  28899. Primitives.TiledGround = TiledGround;
  28900. var Plane = (function (_super) {
  28901. __extends(Plane, _super);
  28902. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28903. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28904. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28905. _this.size = size;
  28906. _this.side = side;
  28907. return _this;
  28908. }
  28909. Plane.prototype._regenerateVertexData = function () {
  28910. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28911. };
  28912. Plane.prototype.copy = function (id) {
  28913. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28914. };
  28915. Plane.prototype.serialize = function () {
  28916. var serializationObject = _super.prototype.serialize.call(this);
  28917. serializationObject.size = this.size;
  28918. return serializationObject;
  28919. };
  28920. Plane.Parse = function (parsedPlane, scene) {
  28921. if (scene.getGeometryByID(parsedPlane.id)) {
  28922. return null; // null since geometry could be something else than a ground...
  28923. }
  28924. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28925. if (BABYLON.Tags) {
  28926. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28927. }
  28928. scene.pushGeometry(plane, true);
  28929. return plane;
  28930. };
  28931. return Plane;
  28932. }(_Primitive));
  28933. Primitives.Plane = Plane;
  28934. var TorusKnot = (function (_super) {
  28935. __extends(TorusKnot, _super);
  28936. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28937. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28938. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28939. _this.radius = radius;
  28940. _this.tube = tube;
  28941. _this.radialSegments = radialSegments;
  28942. _this.tubularSegments = tubularSegments;
  28943. _this.p = p;
  28944. _this.q = q;
  28945. _this.side = side;
  28946. return _this;
  28947. }
  28948. TorusKnot.prototype._regenerateVertexData = function () {
  28949. 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 });
  28950. };
  28951. TorusKnot.prototype.copy = function (id) {
  28952. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28953. };
  28954. TorusKnot.prototype.serialize = function () {
  28955. var serializationObject = _super.prototype.serialize.call(this);
  28956. serializationObject.radius = this.radius;
  28957. serializationObject.tube = this.tube;
  28958. serializationObject.radialSegments = this.radialSegments;
  28959. serializationObject.tubularSegments = this.tubularSegments;
  28960. serializationObject.p = this.p;
  28961. serializationObject.q = this.q;
  28962. return serializationObject;
  28963. };
  28964. ;
  28965. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28966. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28967. return null; // null since geometry could be something else than a ground...
  28968. }
  28969. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28970. if (BABYLON.Tags) {
  28971. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28972. }
  28973. scene.pushGeometry(torusKnot, true);
  28974. return torusKnot;
  28975. };
  28976. return TorusKnot;
  28977. }(_Primitive));
  28978. Primitives.TorusKnot = TorusKnot;
  28979. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28980. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28981. })(BABYLON || (BABYLON = {}));
  28982. //# sourceMappingURL=babylon.geometry.js.map
  28983. var BABYLON;
  28984. (function (BABYLON) {
  28985. var PostProcessManager = (function () {
  28986. function PostProcessManager(scene) {
  28987. this._vertexBuffers = {};
  28988. this._scene = scene;
  28989. }
  28990. PostProcessManager.prototype._prepareBuffers = function () {
  28991. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28992. return;
  28993. }
  28994. // VBO
  28995. var vertices = [];
  28996. vertices.push(1, 1);
  28997. vertices.push(-1, 1);
  28998. vertices.push(-1, -1);
  28999. vertices.push(1, -1);
  29000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29001. // Indices
  29002. var indices = [];
  29003. indices.push(0);
  29004. indices.push(1);
  29005. indices.push(2);
  29006. indices.push(0);
  29007. indices.push(2);
  29008. indices.push(3);
  29009. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29010. };
  29011. // Methods
  29012. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29013. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29014. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29015. return false;
  29016. }
  29017. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29018. return true;
  29019. };
  29020. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29021. var engine = this._scene.getEngine();
  29022. for (var index = 0; index < postProcesses.length; index++) {
  29023. if (index < postProcesses.length - 1) {
  29024. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29025. }
  29026. else {
  29027. if (targetTexture) {
  29028. engine.bindFramebuffer(targetTexture);
  29029. }
  29030. else {
  29031. engine.restoreDefaultFramebuffer();
  29032. }
  29033. }
  29034. var pp = postProcesses[index];
  29035. var effect = pp.apply();
  29036. if (effect) {
  29037. pp.onBeforeRenderObservable.notifyObservers(effect);
  29038. // VBOs
  29039. this._prepareBuffers();
  29040. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29041. // Draw order
  29042. engine.draw(true, 0, 6);
  29043. pp.onAfterRenderObservable.notifyObservers(effect);
  29044. }
  29045. }
  29046. // Restore depth buffer
  29047. engine.setDepthBuffer(true);
  29048. engine.setDepthWrite(true);
  29049. };
  29050. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29051. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29052. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29053. return;
  29054. }
  29055. var engine = this._scene.getEngine();
  29056. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29057. if (index < len - 1) {
  29058. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29059. }
  29060. else {
  29061. if (targetTexture) {
  29062. engine.bindFramebuffer(targetTexture, faceIndex);
  29063. }
  29064. else {
  29065. engine.restoreDefaultFramebuffer();
  29066. }
  29067. }
  29068. if (doNotPresent) {
  29069. break;
  29070. }
  29071. var pp = postProcesses[index];
  29072. var effect = pp.apply();
  29073. if (effect) {
  29074. pp.onBeforeRenderObservable.notifyObservers(effect);
  29075. // VBOs
  29076. this._prepareBuffers();
  29077. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29078. // Draw order
  29079. engine.draw(true, 0, 6);
  29080. pp.onAfterRenderObservable.notifyObservers(effect);
  29081. }
  29082. }
  29083. // Restore states
  29084. engine.setDepthBuffer(true);
  29085. engine.setDepthWrite(true);
  29086. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29087. };
  29088. PostProcessManager.prototype.dispose = function () {
  29089. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29090. if (buffer) {
  29091. buffer.dispose();
  29092. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29093. }
  29094. if (this._indexBuffer) {
  29095. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29096. this._indexBuffer = null;
  29097. }
  29098. };
  29099. return PostProcessManager;
  29100. }());
  29101. BABYLON.PostProcessManager = PostProcessManager;
  29102. })(BABYLON || (BABYLON = {}));
  29103. //# sourceMappingURL=babylon.postProcessManager.js.map
  29104. var BABYLON;
  29105. (function (BABYLON) {
  29106. /**
  29107. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29108. */
  29109. var PerformanceMonitor = (function () {
  29110. /**
  29111. * constructor
  29112. * @param frameSampleSize The number of samples required to saturate the sliding window
  29113. */
  29114. function PerformanceMonitor(frameSampleSize) {
  29115. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29116. this._enabled = true;
  29117. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29118. }
  29119. /**
  29120. * Samples current frame
  29121. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29122. */
  29123. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29124. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29125. if (!this._enabled)
  29126. return;
  29127. if (this._lastFrameTimeMs != null) {
  29128. var dt = timeMs - this._lastFrameTimeMs;
  29129. this._rollingFrameTime.add(dt);
  29130. }
  29131. this._lastFrameTimeMs = timeMs;
  29132. };
  29133. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29134. /**
  29135. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29136. * @return Average frame time in milliseconds
  29137. */
  29138. get: function () {
  29139. return this._rollingFrameTime.average;
  29140. },
  29141. enumerable: true,
  29142. configurable: true
  29143. });
  29144. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29145. /**
  29146. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29147. * @return Frame time variance in milliseconds squared
  29148. */
  29149. get: function () {
  29150. return this._rollingFrameTime.variance;
  29151. },
  29152. enumerable: true,
  29153. configurable: true
  29154. });
  29155. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29156. /**
  29157. * Returns the frame time of the most recent frame
  29158. * @return Frame time in milliseconds
  29159. */
  29160. get: function () {
  29161. return this._rollingFrameTime.history(0);
  29162. },
  29163. enumerable: true,
  29164. configurable: true
  29165. });
  29166. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29167. /**
  29168. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29169. * @return Framerate in frames per second
  29170. */
  29171. get: function () {
  29172. return 1000.0 / this._rollingFrameTime.average;
  29173. },
  29174. enumerable: true,
  29175. configurable: true
  29176. });
  29177. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29178. /**
  29179. * Returns the average framerate in frames per second using the most recent frame time
  29180. * @return Framerate in frames per second
  29181. */
  29182. get: function () {
  29183. return 1000.0 / this._rollingFrameTime.history(0);
  29184. },
  29185. enumerable: true,
  29186. configurable: true
  29187. });
  29188. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29189. /**
  29190. * Returns true if enough samples have been taken to completely fill the sliding window
  29191. * @return true if saturated
  29192. */
  29193. get: function () {
  29194. return this._rollingFrameTime.isSaturated();
  29195. },
  29196. enumerable: true,
  29197. configurable: true
  29198. });
  29199. /**
  29200. * Enables contributions to the sliding window sample set
  29201. */
  29202. PerformanceMonitor.prototype.enable = function () {
  29203. this._enabled = true;
  29204. };
  29205. /**
  29206. * Disables contributions to the sliding window sample set
  29207. * Samples will not be interpolated over the disabled period
  29208. */
  29209. PerformanceMonitor.prototype.disable = function () {
  29210. this._enabled = false;
  29211. //clear last sample to avoid interpolating over the disabled period when next enabled
  29212. this._lastFrameTimeMs = null;
  29213. this._lastChangeTimeMs = null;
  29214. };
  29215. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29216. /**
  29217. * Returns true if sampling is enabled
  29218. * @return true if enabled
  29219. */
  29220. get: function () {
  29221. return this._enabled;
  29222. },
  29223. enumerable: true,
  29224. configurable: true
  29225. });
  29226. /**
  29227. * Resets performance monitor
  29228. */
  29229. PerformanceMonitor.prototype.reset = function () {
  29230. //clear last sample to avoid interpolating over the disabled period when next enabled
  29231. this._lastFrameTimeMs = null;
  29232. this._lastChangeTimeMs = null;
  29233. //wipe record
  29234. this._rollingFrameTime.reset();
  29235. };
  29236. return PerformanceMonitor;
  29237. }());
  29238. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29239. /**
  29240. * RollingAverage
  29241. *
  29242. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29243. */
  29244. var RollingAverage = (function () {
  29245. /**
  29246. * constructor
  29247. * @param length The number of samples required to saturate the sliding window
  29248. */
  29249. function RollingAverage(length) {
  29250. this._samples = new Array(length);
  29251. this.reset();
  29252. }
  29253. /**
  29254. * Adds a sample to the sample set
  29255. * @param v The sample value
  29256. */
  29257. RollingAverage.prototype.add = function (v) {
  29258. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29259. var delta;
  29260. //we need to check if we've already wrapped round
  29261. if (this.isSaturated()) {
  29262. //remove bottom of stack from mean
  29263. var bottomValue = this._samples[this._pos];
  29264. delta = bottomValue - this.average;
  29265. this.average -= delta / (this._sampleCount - 1);
  29266. this._m2 -= delta * (bottomValue - this.average);
  29267. }
  29268. else {
  29269. this._sampleCount++;
  29270. }
  29271. //add new value to mean
  29272. delta = v - this.average;
  29273. this.average += delta / (this._sampleCount);
  29274. this._m2 += delta * (v - this.average);
  29275. //set the new variance
  29276. this.variance = this._m2 / (this._sampleCount - 1);
  29277. this._samples[this._pos] = v;
  29278. this._pos++;
  29279. this._pos %= this._samples.length; //positive wrap around
  29280. };
  29281. /**
  29282. * Returns previously added values or null if outside of history or outside the sliding window domain
  29283. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  29284. * @return Value previously recorded with add() or null if outside of range
  29285. */
  29286. RollingAverage.prototype.history = function (i) {
  29287. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  29288. return null;
  29289. }
  29290. var i0 = this._wrapPosition(this._pos - 1.0);
  29291. return this._samples[this._wrapPosition(i0 - i)];
  29292. };
  29293. /**
  29294. * Returns true if enough samples have been taken to completely fill the sliding window
  29295. * @return true if sample-set saturated
  29296. */
  29297. RollingAverage.prototype.isSaturated = function () {
  29298. return this._sampleCount >= this._samples.length;
  29299. };
  29300. /**
  29301. * Resets the rolling average (equivalent to 0 samples taken so far)
  29302. */
  29303. RollingAverage.prototype.reset = function () {
  29304. this.average = 0;
  29305. this.variance = 0;
  29306. this._sampleCount = 0;
  29307. this._pos = 0;
  29308. this._m2 = 0;
  29309. };
  29310. /**
  29311. * Wraps a value around the sample range boundaries
  29312. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  29313. * @return Wrapped position in sample range
  29314. */
  29315. RollingAverage.prototype._wrapPosition = function (i) {
  29316. var max = this._samples.length;
  29317. return ((i % max) + max) % max;
  29318. };
  29319. return RollingAverage;
  29320. }());
  29321. BABYLON.RollingAverage = RollingAverage;
  29322. })(BABYLON || (BABYLON = {}));
  29323. //# sourceMappingURL=babylon.performanceMonitor.js.map
  29324. var BABYLON;
  29325. (function (BABYLON) {
  29326. var StandardMaterialDefines = (function (_super) {
  29327. __extends(StandardMaterialDefines, _super);
  29328. function StandardMaterialDefines() {
  29329. var _this = _super.call(this) || this;
  29330. _this.MAINUV1 = false;
  29331. _this.MAINUV2 = false;
  29332. _this.DIFFUSE = false;
  29333. _this.DIFFUSEDIRECTUV = 0;
  29334. _this.AMBIENT = false;
  29335. _this.AMBIENTDIRECTUV = 0;
  29336. _this.OPACITY = false;
  29337. _this.OPACITYDIRECTUV = 0;
  29338. _this.OPACITYRGB = false;
  29339. _this.REFLECTION = false;
  29340. _this.EMISSIVE = false;
  29341. _this.EMISSIVEDIRECTUV = 0;
  29342. _this.SPECULAR = false;
  29343. _this.SPECULARDIRECTUV = 0;
  29344. _this.BUMP = false;
  29345. _this.BUMPDIRECTUV = 0;
  29346. _this.PARALLAX = false;
  29347. _this.PARALLAXOCCLUSION = false;
  29348. _this.SPECULAROVERALPHA = false;
  29349. _this.CLIPPLANE = false;
  29350. _this.ALPHATEST = false;
  29351. _this.ALPHAFROMDIFFUSE = false;
  29352. _this.POINTSIZE = false;
  29353. _this.FOG = false;
  29354. _this.SPECULARTERM = false;
  29355. _this.DIFFUSEFRESNEL = false;
  29356. _this.OPACITYFRESNEL = false;
  29357. _this.REFLECTIONFRESNEL = false;
  29358. _this.REFRACTIONFRESNEL = false;
  29359. _this.EMISSIVEFRESNEL = false;
  29360. _this.FRESNEL = false;
  29361. _this.NORMAL = false;
  29362. _this.UV1 = false;
  29363. _this.UV2 = false;
  29364. _this.VERTEXCOLOR = false;
  29365. _this.VERTEXALPHA = false;
  29366. _this.NUM_BONE_INFLUENCERS = 0;
  29367. _this.BonesPerMesh = 0;
  29368. _this.INSTANCES = false;
  29369. _this.GLOSSINESS = false;
  29370. _this.ROUGHNESS = false;
  29371. _this.EMISSIVEASILLUMINATION = false;
  29372. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29373. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29374. _this.LIGHTMAP = false;
  29375. _this.LIGHTMAPDIRECTUV = 0;
  29376. _this.USELIGHTMAPASSHADOWMAP = false;
  29377. _this.REFLECTIONMAP_3D = false;
  29378. _this.REFLECTIONMAP_SPHERICAL = false;
  29379. _this.REFLECTIONMAP_PLANAR = false;
  29380. _this.REFLECTIONMAP_CUBIC = false;
  29381. _this.REFLECTIONMAP_PROJECTION = false;
  29382. _this.REFLECTIONMAP_SKYBOX = false;
  29383. _this.REFLECTIONMAP_EXPLICIT = false;
  29384. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29385. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29386. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29387. _this.INVERTCUBICMAP = false;
  29388. _this.LOGARITHMICDEPTH = false;
  29389. _this.REFRACTION = false;
  29390. _this.REFRACTIONMAP_3D = false;
  29391. _this.REFLECTIONOVERALPHA = false;
  29392. _this.TWOSIDEDLIGHTING = false;
  29393. _this.SHADOWFLOAT = false;
  29394. _this.MORPHTARGETS = false;
  29395. _this.MORPHTARGETS_NORMAL = false;
  29396. _this.MORPHTARGETS_TANGENT = false;
  29397. _this.NUM_MORPH_INFLUENCERS = 0;
  29398. _this.USERIGHTHANDEDSYSTEM = false;
  29399. _this.IMAGEPROCESSING = false;
  29400. _this.VIGNETTE = false;
  29401. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  29402. _this.VIGNETTEBLENDMODEOPAQUE = false;
  29403. _this.TONEMAPPING = false;
  29404. _this.CONTRAST = false;
  29405. _this.COLORCURVES = false;
  29406. _this.COLORGRADING = false;
  29407. _this.SAMPLER3DGREENDEPTH = false;
  29408. _this.SAMPLER3DBGRMAP = false;
  29409. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  29410. _this.EXPOSURE = false;
  29411. _this.rebuild();
  29412. return _this;
  29413. }
  29414. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  29415. var modes = [
  29416. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  29417. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  29418. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  29419. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  29420. ];
  29421. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  29422. var mode = modes_1[_i];
  29423. this[mode] = (mode === modeToEnable);
  29424. }
  29425. };
  29426. return StandardMaterialDefines;
  29427. }(BABYLON.MaterialDefines));
  29428. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  29429. var StandardMaterial = (function (_super) {
  29430. __extends(StandardMaterial, _super);
  29431. function StandardMaterial(name, scene) {
  29432. var _this = _super.call(this, name, scene) || this;
  29433. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29434. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29435. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29436. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29437. _this.specularPower = 64;
  29438. _this._useAlphaFromDiffuseTexture = false;
  29439. _this._useEmissiveAsIllumination = false;
  29440. _this._linkEmissiveWithDiffuse = false;
  29441. _this._useSpecularOverAlpha = false;
  29442. _this._useReflectionOverAlpha = false;
  29443. _this._disableLighting = false;
  29444. _this._useParallax = false;
  29445. _this._useParallaxOcclusion = false;
  29446. _this.parallaxScaleBias = 0.05;
  29447. _this._roughness = 0;
  29448. _this.indexOfRefraction = 0.98;
  29449. _this.invertRefractionY = true;
  29450. _this._useLightmapAsShadowmap = false;
  29451. _this._useReflectionFresnelFromSpecular = false;
  29452. _this._useGlossinessFromSpecularMapAlpha = false;
  29453. _this._maxSimultaneousLights = 4;
  29454. /**
  29455. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29456. */
  29457. _this._invertNormalMapX = false;
  29458. /**
  29459. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29460. */
  29461. _this._invertNormalMapY = false;
  29462. /**
  29463. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  29464. */
  29465. _this._twoSidedLighting = false;
  29466. _this._renderTargets = new BABYLON.SmartArray(16);
  29467. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29468. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29469. // Setup the default processing configuration to the scene.
  29470. _this._attachImageProcessingConfiguration(null);
  29471. _this.getRenderTargetTextures = function () {
  29472. _this._renderTargets.reset();
  29473. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  29474. _this._renderTargets.push(_this._reflectionTexture);
  29475. }
  29476. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  29477. _this._renderTargets.push(_this._refractionTexture);
  29478. }
  29479. return _this._renderTargets;
  29480. };
  29481. return _this;
  29482. }
  29483. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  29484. /**
  29485. * Gets the image processing configuration used either in this material.
  29486. */
  29487. get: function () {
  29488. return this._imageProcessingConfiguration;
  29489. },
  29490. /**
  29491. * Sets the Default image processing configuration used either in the this material.
  29492. *
  29493. * If sets to null, the scene one is in use.
  29494. */
  29495. set: function (value) {
  29496. this._attachImageProcessingConfiguration(value);
  29497. // Ensure the effect will be rebuilt.
  29498. this._markAllSubMeshesAsTexturesDirty();
  29499. },
  29500. enumerable: true,
  29501. configurable: true
  29502. });
  29503. /**
  29504. * Attaches a new image processing configuration to the Standard Material.
  29505. * @param configuration
  29506. */
  29507. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  29508. var _this = this;
  29509. if (configuration === this._imageProcessingConfiguration) {
  29510. return;
  29511. }
  29512. // Detaches observer.
  29513. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  29514. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  29515. }
  29516. // Pick the scene configuration if needed.
  29517. if (!configuration) {
  29518. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  29519. }
  29520. else {
  29521. this._imageProcessingConfiguration = configuration;
  29522. }
  29523. // Attaches observer.
  29524. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  29525. _this._markAllSubMeshesAsImageProcessingDirty();
  29526. });
  29527. };
  29528. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  29529. /**
  29530. * Gets wether the color curves effect is enabled.
  29531. */
  29532. get: function () {
  29533. return this.imageProcessingConfiguration.colorCurvesEnabled;
  29534. },
  29535. /**
  29536. * Sets wether the color curves effect is enabled.
  29537. */
  29538. set: function (value) {
  29539. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  29540. },
  29541. enumerable: true,
  29542. configurable: true
  29543. });
  29544. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  29545. /**
  29546. * Gets wether the color grading effect is enabled.
  29547. */
  29548. get: function () {
  29549. return this.imageProcessingConfiguration.colorGradingEnabled;
  29550. },
  29551. /**
  29552. * Gets wether the color grading effect is enabled.
  29553. */
  29554. set: function (value) {
  29555. this.imageProcessingConfiguration.colorGradingEnabled = value;
  29556. },
  29557. enumerable: true,
  29558. configurable: true
  29559. });
  29560. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  29561. /**
  29562. * Gets wether tonemapping is enabled or not.
  29563. */
  29564. get: function () {
  29565. return this._imageProcessingConfiguration.toneMappingEnabled;
  29566. },
  29567. /**
  29568. * Sets wether tonemapping is enabled or not
  29569. */
  29570. set: function (value) {
  29571. this._imageProcessingConfiguration.toneMappingEnabled = value;
  29572. },
  29573. enumerable: true,
  29574. configurable: true
  29575. });
  29576. ;
  29577. ;
  29578. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  29579. /**
  29580. * The camera exposure used on this material.
  29581. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29582. * This corresponds to a photographic exposure.
  29583. */
  29584. get: function () {
  29585. return this._imageProcessingConfiguration.exposure;
  29586. },
  29587. /**
  29588. * The camera exposure used on this material.
  29589. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29590. * This corresponds to a photographic exposure.
  29591. */
  29592. set: function (value) {
  29593. this._imageProcessingConfiguration.exposure = value;
  29594. },
  29595. enumerable: true,
  29596. configurable: true
  29597. });
  29598. ;
  29599. ;
  29600. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  29601. /**
  29602. * Gets The camera contrast used on this material.
  29603. */
  29604. get: function () {
  29605. return this._imageProcessingConfiguration.contrast;
  29606. },
  29607. /**
  29608. * Sets The camera contrast used on this material.
  29609. */
  29610. set: function (value) {
  29611. this._imageProcessingConfiguration.contrast = value;
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  29617. /**
  29618. * Gets the Color Grading 2D Lookup Texture.
  29619. */
  29620. get: function () {
  29621. return this._imageProcessingConfiguration.colorGradingTexture;
  29622. },
  29623. /**
  29624. * Sets the Color Grading 2D Lookup Texture.
  29625. */
  29626. set: function (value) {
  29627. this._imageProcessingConfiguration.colorGradingTexture = value;
  29628. },
  29629. enumerable: true,
  29630. configurable: true
  29631. });
  29632. StandardMaterial.prototype.getClassName = function () {
  29633. return "StandardMaterial";
  29634. };
  29635. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  29636. get: function () {
  29637. return this._useLogarithmicDepth;
  29638. },
  29639. set: function (value) {
  29640. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29641. this._markAllSubMeshesAsMiscDirty();
  29642. },
  29643. enumerable: true,
  29644. configurable: true
  29645. });
  29646. StandardMaterial.prototype.needAlphaBlending = function () {
  29647. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  29648. };
  29649. StandardMaterial.prototype.needAlphaTesting = function () {
  29650. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  29651. };
  29652. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  29653. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  29654. };
  29655. StandardMaterial.prototype.getAlphaTestTexture = function () {
  29656. return this._diffuseTexture;
  29657. };
  29658. /**
  29659. * Child classes can use it to update shaders
  29660. */
  29661. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29662. if (this.isFrozen) {
  29663. if (this._wasPreviouslyReady && subMesh.effect) {
  29664. return true;
  29665. }
  29666. }
  29667. if (!subMesh._materialDefines) {
  29668. subMesh._materialDefines = new StandardMaterialDefines();
  29669. }
  29670. var scene = this.getScene();
  29671. var defines = subMesh._materialDefines;
  29672. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  29673. if (defines._renderId === scene.getRenderId()) {
  29674. return true;
  29675. }
  29676. }
  29677. var engine = scene.getEngine();
  29678. // Lights
  29679. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  29680. // Textures
  29681. if (defines._areTexturesDirty) {
  29682. defines._needUVs = false;
  29683. defines.MAINUV1 = false;
  29684. defines.MAINUV2 = false;
  29685. if (scene.texturesEnabled) {
  29686. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29687. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  29688. return false;
  29689. }
  29690. else {
  29691. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  29692. }
  29693. }
  29694. else {
  29695. defines.DIFFUSE = false;
  29696. }
  29697. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29698. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  29699. return false;
  29700. }
  29701. else {
  29702. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  29703. }
  29704. }
  29705. else {
  29706. defines.AMBIENT = false;
  29707. }
  29708. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29709. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  29710. return false;
  29711. }
  29712. else {
  29713. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  29714. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  29715. }
  29716. }
  29717. else {
  29718. defines.OPACITY = false;
  29719. }
  29720. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29721. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  29722. return false;
  29723. }
  29724. else {
  29725. defines._needNormals = true;
  29726. defines.REFLECTION = true;
  29727. defines.ROUGHNESS = (this._roughness > 0);
  29728. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  29729. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  29730. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  29731. switch (this._reflectionTexture.coordinatesMode) {
  29732. case BABYLON.Texture.CUBIC_MODE:
  29733. case BABYLON.Texture.INVCUBIC_MODE:
  29734. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  29735. break;
  29736. case BABYLON.Texture.EXPLICIT_MODE:
  29737. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  29738. break;
  29739. case BABYLON.Texture.PLANAR_MODE:
  29740. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  29741. break;
  29742. case BABYLON.Texture.PROJECTION_MODE:
  29743. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  29744. break;
  29745. case BABYLON.Texture.SKYBOX_MODE:
  29746. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  29747. break;
  29748. case BABYLON.Texture.SPHERICAL_MODE:
  29749. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  29750. break;
  29751. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29752. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  29753. break;
  29754. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29755. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  29756. break;
  29757. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  29758. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  29759. break;
  29760. }
  29761. }
  29762. }
  29763. else {
  29764. defines.REFLECTION = false;
  29765. }
  29766. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29767. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  29768. return false;
  29769. }
  29770. else {
  29771. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  29772. }
  29773. }
  29774. else {
  29775. defines.EMISSIVE = false;
  29776. }
  29777. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29778. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  29779. return false;
  29780. }
  29781. else {
  29782. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  29783. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  29784. }
  29785. }
  29786. else {
  29787. defines.LIGHTMAP = false;
  29788. }
  29789. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29790. if (!this._specularTexture.isReadyOrNotBlocking()) {
  29791. return false;
  29792. }
  29793. else {
  29794. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  29795. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  29796. }
  29797. }
  29798. else {
  29799. defines.SPECULAR = false;
  29800. }
  29801. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  29802. // Bump texure can not be not blocking.
  29803. if (!this._bumpTexture.isReady()) {
  29804. return false;
  29805. }
  29806. else {
  29807. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  29808. defines.PARALLAX = this._useParallax;
  29809. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  29810. }
  29811. }
  29812. else {
  29813. defines.BUMP = false;
  29814. }
  29815. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29816. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  29817. return false;
  29818. }
  29819. else {
  29820. defines._needUVs = true;
  29821. defines.REFRACTION = true;
  29822. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  29823. }
  29824. }
  29825. else {
  29826. defines.REFRACTION = false;
  29827. }
  29828. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  29829. }
  29830. else {
  29831. defines.DIFFUSE = false;
  29832. defines.AMBIENT = false;
  29833. defines.OPACITY = false;
  29834. defines.REFLECTION = false;
  29835. defines.EMISSIVE = false;
  29836. defines.LIGHTMAP = false;
  29837. defines.BUMP = false;
  29838. defines.REFRACTION = false;
  29839. }
  29840. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  29841. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  29842. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  29843. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  29844. }
  29845. if (defines._areImageProcessingDirty) {
  29846. if (!this._imageProcessingConfiguration.isReady()) {
  29847. return false;
  29848. }
  29849. this._imageProcessingConfiguration.prepareDefines(defines);
  29850. }
  29851. if (defines._areFresnelDirty) {
  29852. if (StandardMaterial.FresnelEnabled) {
  29853. // Fresnel
  29854. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  29855. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  29856. this._reflectionFresnelParameters) {
  29857. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  29858. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  29859. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  29860. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  29861. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  29862. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  29863. defines._needNormals = true;
  29864. defines.FRESNEL = true;
  29865. }
  29866. }
  29867. else {
  29868. defines.FRESNEL = false;
  29869. }
  29870. }
  29871. // Misc.
  29872. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  29873. // Attribs
  29874. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  29875. // Values that need to be evaluated on every frame
  29876. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  29877. // Get correct effect
  29878. if (defines.isDirty) {
  29879. defines.markAsProcessed();
  29880. scene.resetCachedMaterial();
  29881. // Fallbacks
  29882. var fallbacks = new BABYLON.EffectFallbacks();
  29883. if (defines.REFLECTION) {
  29884. fallbacks.addFallback(0, "REFLECTION");
  29885. }
  29886. if (defines.SPECULAR) {
  29887. fallbacks.addFallback(0, "SPECULAR");
  29888. }
  29889. if (defines.BUMP) {
  29890. fallbacks.addFallback(0, "BUMP");
  29891. }
  29892. if (defines.PARALLAX) {
  29893. fallbacks.addFallback(1, "PARALLAX");
  29894. }
  29895. if (defines.PARALLAXOCCLUSION) {
  29896. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29897. }
  29898. if (defines.SPECULAROVERALPHA) {
  29899. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29900. }
  29901. if (defines.FOG) {
  29902. fallbacks.addFallback(1, "FOG");
  29903. }
  29904. if (defines.POINTSIZE) {
  29905. fallbacks.addFallback(0, "POINTSIZE");
  29906. }
  29907. if (defines.LOGARITHMICDEPTH) {
  29908. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29909. }
  29910. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  29911. if (defines.SPECULARTERM) {
  29912. fallbacks.addFallback(0, "SPECULARTERM");
  29913. }
  29914. if (defines.DIFFUSEFRESNEL) {
  29915. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29916. }
  29917. if (defines.OPACITYFRESNEL) {
  29918. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29919. }
  29920. if (defines.REFLECTIONFRESNEL) {
  29921. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29922. }
  29923. if (defines.EMISSIVEFRESNEL) {
  29924. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29925. }
  29926. if (defines.FRESNEL) {
  29927. fallbacks.addFallback(4, "FRESNEL");
  29928. }
  29929. //Attributes
  29930. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29931. if (defines.NORMAL) {
  29932. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29933. }
  29934. if (defines.UV1) {
  29935. attribs.push(BABYLON.VertexBuffer.UVKind);
  29936. }
  29937. if (defines.UV2) {
  29938. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29939. }
  29940. if (defines.VERTEXCOLOR) {
  29941. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29942. }
  29943. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  29944. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  29945. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  29946. var shaderName = "default";
  29947. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29948. "vFogInfos", "vFogColor", "pointSize",
  29949. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29950. "mBones",
  29951. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29952. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29953. "logarithmicDepthConstant", "vNormalReoderParams"
  29954. ];
  29955. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29956. var uniformBuffers = ["Material", "Scene"];
  29957. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  29958. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  29959. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29960. uniformsNames: uniforms,
  29961. uniformBuffersNames: uniformBuffers,
  29962. samplers: samplers,
  29963. defines: defines,
  29964. maxSimultaneousLights: this._maxSimultaneousLights
  29965. });
  29966. if (this.customShaderNameResolve) {
  29967. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  29968. }
  29969. var join = defines.toString();
  29970. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  29971. attributes: attribs,
  29972. uniformsNames: uniforms,
  29973. uniformBuffersNames: uniformBuffers,
  29974. samplers: samplers,
  29975. defines: join,
  29976. fallbacks: fallbacks,
  29977. onCompiled: this.onCompiled,
  29978. onError: this.onError,
  29979. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  29980. }, engine), defines);
  29981. this.buildUniformLayout();
  29982. }
  29983. if (!subMesh.effect.isReady()) {
  29984. return false;
  29985. }
  29986. defines._renderId = scene.getRenderId();
  29987. this._wasPreviouslyReady = true;
  29988. return true;
  29989. };
  29990. StandardMaterial.prototype.buildUniformLayout = function () {
  29991. // Order is important !
  29992. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  29993. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  29994. this._uniformBuffer.addUniform("opacityParts", 4);
  29995. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  29996. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  29997. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  29998. this._uniformBuffer.addUniform("refractionRightColor", 4);
  29999. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30000. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30001. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  30002. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  30003. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30004. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30005. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30006. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30007. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  30008. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30009. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  30010. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30011. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30012. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30013. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30014. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30015. this._uniformBuffer.addUniform("specularMatrix", 16);
  30016. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30017. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  30018. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30019. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30020. this._uniformBuffer.addUniform("vSpecularColor", 4);
  30021. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30022. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  30023. this._uniformBuffer.addUniform("pointSize", 1);
  30024. this._uniformBuffer.create();
  30025. };
  30026. StandardMaterial.prototype.unbind = function () {
  30027. if (this._activeEffect) {
  30028. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30029. this._activeEffect.setTexture("reflection2DSampler", null);
  30030. }
  30031. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30032. this._activeEffect.setTexture("refraction2DSampler", null);
  30033. }
  30034. }
  30035. _super.prototype.unbind.call(this);
  30036. };
  30037. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30038. var scene = this.getScene();
  30039. var defines = subMesh._materialDefines;
  30040. if (!defines) {
  30041. return;
  30042. }
  30043. var effect = subMesh.effect;
  30044. this._activeEffect = effect;
  30045. // Matrices
  30046. this.bindOnlyWorldMatrix(world);
  30047. // Bones
  30048. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  30049. if (this._mustRebind(scene, effect, mesh.visibility)) {
  30050. this._uniformBuffer.bindToEffect(effect, "Material");
  30051. this.bindViewProjection(effect);
  30052. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30053. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  30054. // Fresnel
  30055. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30056. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30057. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30058. }
  30059. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30060. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30061. }
  30062. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30063. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30064. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30065. }
  30066. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30067. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30068. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30069. }
  30070. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30071. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30072. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30073. }
  30074. }
  30075. // Textures
  30076. if (scene.texturesEnabled) {
  30077. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30078. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  30079. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  30080. }
  30081. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30082. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  30083. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  30084. }
  30085. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30086. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30087. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  30088. }
  30089. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30090. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  30091. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  30092. }
  30093. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30094. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30095. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  30096. }
  30097. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30098. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30099. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  30100. }
  30101. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30102. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  30103. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  30104. }
  30105. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30106. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  30107. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  30108. if (scene._mirroredCameraPosition) {
  30109. 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);
  30110. }
  30111. else {
  30112. 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);
  30113. }
  30114. }
  30115. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30116. var depth = 1.0;
  30117. if (!this._refractionTexture.isCube) {
  30118. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30119. if (this._refractionTexture.depth) {
  30120. depth = this._refractionTexture.depth;
  30121. }
  30122. }
  30123. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30124. }
  30125. }
  30126. // Point size
  30127. if (this.pointsCloud) {
  30128. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30129. }
  30130. if (defines.SPECULARTERM) {
  30131. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  30132. }
  30133. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  30134. // Diffuse
  30135. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30136. }
  30137. // Textures
  30138. if (scene.texturesEnabled) {
  30139. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30140. effect.setTexture("diffuseSampler", this._diffuseTexture);
  30141. }
  30142. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30143. effect.setTexture("ambientSampler", this._ambientTexture);
  30144. }
  30145. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30146. effect.setTexture("opacitySampler", this._opacityTexture);
  30147. }
  30148. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30149. if (this._reflectionTexture.isCube) {
  30150. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  30151. }
  30152. else {
  30153. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  30154. }
  30155. }
  30156. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30157. effect.setTexture("emissiveSampler", this._emissiveTexture);
  30158. }
  30159. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30160. effect.setTexture("lightmapSampler", this._lightmapTexture);
  30161. }
  30162. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30163. effect.setTexture("specularSampler", this._specularTexture);
  30164. }
  30165. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30166. effect.setTexture("bumpSampler", this._bumpTexture);
  30167. }
  30168. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30169. var depth = 1.0;
  30170. if (this._refractionTexture.isCube) {
  30171. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  30172. }
  30173. else {
  30174. effect.setTexture("refraction2DSampler", this._refractionTexture);
  30175. }
  30176. }
  30177. }
  30178. // Clip plane
  30179. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  30180. // Colors
  30181. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30182. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  30183. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30184. }
  30185. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  30186. // Lights
  30187. if (scene.lightsEnabled && !this._disableLighting) {
  30188. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  30189. }
  30190. // View
  30191. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  30192. this.bindView(effect);
  30193. }
  30194. // Fog
  30195. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  30196. // Morph targets
  30197. if (defines.NUM_MORPH_INFLUENCERS) {
  30198. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  30199. }
  30200. // Log. depth
  30201. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  30202. // image processing
  30203. this._imageProcessingConfiguration.bind(this._activeEffect);
  30204. }
  30205. this._uniformBuffer.update();
  30206. this._afterBind(mesh, this._activeEffect);
  30207. };
  30208. StandardMaterial.prototype.getAnimatables = function () {
  30209. var results = [];
  30210. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  30211. results.push(this._diffuseTexture);
  30212. }
  30213. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30214. results.push(this._ambientTexture);
  30215. }
  30216. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30217. results.push(this._opacityTexture);
  30218. }
  30219. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30220. results.push(this._reflectionTexture);
  30221. }
  30222. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30223. results.push(this._emissiveTexture);
  30224. }
  30225. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  30226. results.push(this._specularTexture);
  30227. }
  30228. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30229. results.push(this._bumpTexture);
  30230. }
  30231. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30232. results.push(this._lightmapTexture);
  30233. }
  30234. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30235. results.push(this._refractionTexture);
  30236. }
  30237. return results;
  30238. };
  30239. StandardMaterial.prototype.getActiveTextures = function () {
  30240. var activeTextures = _super.prototype.getActiveTextures.call(this);
  30241. if (this._diffuseTexture) {
  30242. activeTextures.push(this._diffuseTexture);
  30243. }
  30244. if (this._ambientTexture) {
  30245. activeTextures.push(this._ambientTexture);
  30246. }
  30247. if (this._opacityTexture) {
  30248. activeTextures.push(this._opacityTexture);
  30249. }
  30250. if (this._reflectionTexture) {
  30251. activeTextures.push(this._reflectionTexture);
  30252. }
  30253. if (this._emissiveTexture) {
  30254. activeTextures.push(this._emissiveTexture);
  30255. }
  30256. if (this._specularTexture) {
  30257. activeTextures.push(this._specularTexture);
  30258. }
  30259. if (this._bumpTexture) {
  30260. activeTextures.push(this._bumpTexture);
  30261. }
  30262. if (this._lightmapTexture) {
  30263. activeTextures.push(this._lightmapTexture);
  30264. }
  30265. if (this._refractionTexture) {
  30266. activeTextures.push(this._refractionTexture);
  30267. }
  30268. return activeTextures;
  30269. };
  30270. StandardMaterial.prototype.hasTexture = function (texture) {
  30271. if (_super.prototype.hasTexture.call(this, texture)) {
  30272. return true;
  30273. }
  30274. if (this._diffuseTexture === texture) {
  30275. return true;
  30276. }
  30277. if (this._ambientTexture === texture) {
  30278. return true;
  30279. }
  30280. if (this._opacityTexture === texture) {
  30281. return true;
  30282. }
  30283. if (this._reflectionTexture === texture) {
  30284. return true;
  30285. }
  30286. if (this._emissiveTexture === texture) {
  30287. return true;
  30288. }
  30289. if (this._specularTexture === texture) {
  30290. return true;
  30291. }
  30292. if (this._bumpTexture === texture) {
  30293. return true;
  30294. }
  30295. if (this._lightmapTexture === texture) {
  30296. return true;
  30297. }
  30298. if (this._refractionTexture === texture) {
  30299. return true;
  30300. }
  30301. return false;
  30302. };
  30303. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30304. if (forceDisposeTextures) {
  30305. if (this._diffuseTexture) {
  30306. this._diffuseTexture.dispose();
  30307. }
  30308. if (this._ambientTexture) {
  30309. this._ambientTexture.dispose();
  30310. }
  30311. if (this._opacityTexture) {
  30312. this._opacityTexture.dispose();
  30313. }
  30314. if (this._reflectionTexture) {
  30315. this._reflectionTexture.dispose();
  30316. }
  30317. if (this._emissiveTexture) {
  30318. this._emissiveTexture.dispose();
  30319. }
  30320. if (this._specularTexture) {
  30321. this._specularTexture.dispose();
  30322. }
  30323. if (this._bumpTexture) {
  30324. this._bumpTexture.dispose();
  30325. }
  30326. if (this._lightmapTexture) {
  30327. this._lightmapTexture.dispose();
  30328. }
  30329. if (this._refractionTexture) {
  30330. this._refractionTexture.dispose();
  30331. }
  30332. }
  30333. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30334. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30335. }
  30336. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30337. };
  30338. StandardMaterial.prototype.clone = function (name) {
  30339. var _this = this;
  30340. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30341. result.name = name;
  30342. result.id = name;
  30343. return result;
  30344. };
  30345. StandardMaterial.prototype.serialize = function () {
  30346. return BABYLON.SerializationHelper.Serialize(this);
  30347. };
  30348. // Statics
  30349. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30350. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30351. };
  30352. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  30353. get: function () {
  30354. return StandardMaterial._DiffuseTextureEnabled;
  30355. },
  30356. set: function (value) {
  30357. if (StandardMaterial._DiffuseTextureEnabled === value) {
  30358. return;
  30359. }
  30360. StandardMaterial._DiffuseTextureEnabled = value;
  30361. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30362. },
  30363. enumerable: true,
  30364. configurable: true
  30365. });
  30366. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  30367. get: function () {
  30368. return StandardMaterial._AmbientTextureEnabled;
  30369. },
  30370. set: function (value) {
  30371. if (StandardMaterial._AmbientTextureEnabled === value) {
  30372. return;
  30373. }
  30374. StandardMaterial._AmbientTextureEnabled = value;
  30375. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30376. },
  30377. enumerable: true,
  30378. configurable: true
  30379. });
  30380. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  30381. get: function () {
  30382. return StandardMaterial._OpacityTextureEnabled;
  30383. },
  30384. set: function (value) {
  30385. if (StandardMaterial._OpacityTextureEnabled === value) {
  30386. return;
  30387. }
  30388. StandardMaterial._OpacityTextureEnabled = value;
  30389. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30390. },
  30391. enumerable: true,
  30392. configurable: true
  30393. });
  30394. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  30395. get: function () {
  30396. return StandardMaterial._ReflectionTextureEnabled;
  30397. },
  30398. set: function (value) {
  30399. if (StandardMaterial._ReflectionTextureEnabled === value) {
  30400. return;
  30401. }
  30402. StandardMaterial._ReflectionTextureEnabled = value;
  30403. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30404. },
  30405. enumerable: true,
  30406. configurable: true
  30407. });
  30408. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  30409. get: function () {
  30410. return StandardMaterial._EmissiveTextureEnabled;
  30411. },
  30412. set: function (value) {
  30413. if (StandardMaterial._EmissiveTextureEnabled === value) {
  30414. return;
  30415. }
  30416. StandardMaterial._EmissiveTextureEnabled = value;
  30417. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30418. },
  30419. enumerable: true,
  30420. configurable: true
  30421. });
  30422. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  30423. get: function () {
  30424. return StandardMaterial._SpecularTextureEnabled;
  30425. },
  30426. set: function (value) {
  30427. if (StandardMaterial._SpecularTextureEnabled === value) {
  30428. return;
  30429. }
  30430. StandardMaterial._SpecularTextureEnabled = value;
  30431. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30432. },
  30433. enumerable: true,
  30434. configurable: true
  30435. });
  30436. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  30437. get: function () {
  30438. return StandardMaterial._BumpTextureEnabled;
  30439. },
  30440. set: function (value) {
  30441. if (StandardMaterial._BumpTextureEnabled === value) {
  30442. return;
  30443. }
  30444. StandardMaterial._BumpTextureEnabled = value;
  30445. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  30451. get: function () {
  30452. return StandardMaterial._LightmapTextureEnabled;
  30453. },
  30454. set: function (value) {
  30455. if (StandardMaterial._LightmapTextureEnabled === value) {
  30456. return;
  30457. }
  30458. StandardMaterial._LightmapTextureEnabled = value;
  30459. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  30465. get: function () {
  30466. return StandardMaterial._RefractionTextureEnabled;
  30467. },
  30468. set: function (value) {
  30469. if (StandardMaterial._RefractionTextureEnabled === value) {
  30470. return;
  30471. }
  30472. StandardMaterial._RefractionTextureEnabled = value;
  30473. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30474. },
  30475. enumerable: true,
  30476. configurable: true
  30477. });
  30478. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  30479. get: function () {
  30480. return StandardMaterial._ColorGradingTextureEnabled;
  30481. },
  30482. set: function (value) {
  30483. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  30484. return;
  30485. }
  30486. StandardMaterial._ColorGradingTextureEnabled = value;
  30487. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30488. },
  30489. enumerable: true,
  30490. configurable: true
  30491. });
  30492. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  30493. get: function () {
  30494. return StandardMaterial._FresnelEnabled;
  30495. },
  30496. set: function (value) {
  30497. if (StandardMaterial._FresnelEnabled === value) {
  30498. return;
  30499. }
  30500. StandardMaterial._FresnelEnabled = value;
  30501. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  30502. },
  30503. enumerable: true,
  30504. configurable: true
  30505. });
  30506. return StandardMaterial;
  30507. }(BABYLON.PushMaterial));
  30508. // Flags used to enable or disable a type of texture for all Standard Materials
  30509. StandardMaterial._DiffuseTextureEnabled = true;
  30510. StandardMaterial._AmbientTextureEnabled = true;
  30511. StandardMaterial._OpacityTextureEnabled = true;
  30512. StandardMaterial._ReflectionTextureEnabled = true;
  30513. StandardMaterial._EmissiveTextureEnabled = true;
  30514. StandardMaterial._SpecularTextureEnabled = true;
  30515. StandardMaterial._BumpTextureEnabled = true;
  30516. StandardMaterial._LightmapTextureEnabled = true;
  30517. StandardMaterial._RefractionTextureEnabled = true;
  30518. StandardMaterial._ColorGradingTextureEnabled = true;
  30519. StandardMaterial._FresnelEnabled = true;
  30520. __decorate([
  30521. BABYLON.serializeAsTexture("diffuseTexture")
  30522. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  30523. __decorate([
  30524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30525. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30526. __decorate([
  30527. BABYLON.serializeAsTexture("ambientTexture")
  30528. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  30529. __decorate([
  30530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30531. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30532. __decorate([
  30533. BABYLON.serializeAsTexture("opacityTexture")
  30534. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  30535. __decorate([
  30536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30537. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30538. __decorate([
  30539. BABYLON.serializeAsTexture("reflectionTexture")
  30540. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  30541. __decorate([
  30542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30543. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30544. __decorate([
  30545. BABYLON.serializeAsTexture("emissiveTexture")
  30546. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  30547. __decorate([
  30548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30549. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30550. __decorate([
  30551. BABYLON.serializeAsTexture("specularTexture")
  30552. ], StandardMaterial.prototype, "_specularTexture", void 0);
  30553. __decorate([
  30554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30555. ], StandardMaterial.prototype, "specularTexture", void 0);
  30556. __decorate([
  30557. BABYLON.serializeAsTexture("bumpTexture")
  30558. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  30559. __decorate([
  30560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30561. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30562. __decorate([
  30563. BABYLON.serializeAsTexture("lightmapTexture")
  30564. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  30565. __decorate([
  30566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30567. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30568. __decorate([
  30569. BABYLON.serializeAsTexture("refractionTexture")
  30570. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  30571. __decorate([
  30572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30573. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30574. __decorate([
  30575. BABYLON.serializeAsColor3("ambient")
  30576. ], StandardMaterial.prototype, "ambientColor", void 0);
  30577. __decorate([
  30578. BABYLON.serializeAsColor3("diffuse")
  30579. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30580. __decorate([
  30581. BABYLON.serializeAsColor3("specular")
  30582. ], StandardMaterial.prototype, "specularColor", void 0);
  30583. __decorate([
  30584. BABYLON.serializeAsColor3("emissive")
  30585. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30586. __decorate([
  30587. BABYLON.serialize()
  30588. ], StandardMaterial.prototype, "specularPower", void 0);
  30589. __decorate([
  30590. BABYLON.serialize("useAlphaFromDiffuseTexture")
  30591. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  30592. __decorate([
  30593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30594. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30595. __decorate([
  30596. BABYLON.serialize("useEmissiveAsIllumination")
  30597. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  30598. __decorate([
  30599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30600. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30601. __decorate([
  30602. BABYLON.serialize("linkEmissiveWithDiffuse")
  30603. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  30604. __decorate([
  30605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30606. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30607. __decorate([
  30608. BABYLON.serialize("useSpecularOverAlpha")
  30609. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  30610. __decorate([
  30611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30612. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30613. __decorate([
  30614. BABYLON.serialize("useReflectionOverAlpha")
  30615. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  30616. __decorate([
  30617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30618. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30619. __decorate([
  30620. BABYLON.serialize("disableLighting")
  30621. ], StandardMaterial.prototype, "_disableLighting", void 0);
  30622. __decorate([
  30623. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30624. ], StandardMaterial.prototype, "disableLighting", void 0);
  30625. __decorate([
  30626. BABYLON.serialize("useParallax")
  30627. ], StandardMaterial.prototype, "_useParallax", void 0);
  30628. __decorate([
  30629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30630. ], StandardMaterial.prototype, "useParallax", void 0);
  30631. __decorate([
  30632. BABYLON.serialize("useParallaxOcclusion")
  30633. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  30634. __decorate([
  30635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30636. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30637. __decorate([
  30638. BABYLON.serialize()
  30639. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30640. __decorate([
  30641. BABYLON.serialize("roughness")
  30642. ], StandardMaterial.prototype, "_roughness", void 0);
  30643. __decorate([
  30644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30645. ], StandardMaterial.prototype, "roughness", void 0);
  30646. __decorate([
  30647. BABYLON.serialize()
  30648. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30649. __decorate([
  30650. BABYLON.serialize()
  30651. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30652. __decorate([
  30653. BABYLON.serialize("useLightmapAsShadowmap")
  30654. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  30655. __decorate([
  30656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30657. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30658. __decorate([
  30659. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  30660. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  30661. __decorate([
  30662. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30663. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30664. __decorate([
  30665. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  30666. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  30667. __decorate([
  30668. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30669. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30670. __decorate([
  30671. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  30672. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  30673. __decorate([
  30674. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30675. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30676. __decorate([
  30677. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  30678. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  30679. __decorate([
  30680. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30681. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30682. __decorate([
  30683. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  30684. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  30685. __decorate([
  30686. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30687. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30688. __decorate([
  30689. BABYLON.serialize("useReflectionFresnelFromSpecular")
  30690. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  30691. __decorate([
  30692. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30693. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30694. __decorate([
  30695. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  30696. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  30697. __decorate([
  30698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30699. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30700. __decorate([
  30701. BABYLON.serialize("maxSimultaneousLights")
  30702. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  30703. __decorate([
  30704. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30705. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30706. __decorate([
  30707. BABYLON.serialize("invertNormalMapX")
  30708. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  30709. __decorate([
  30710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30711. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30712. __decorate([
  30713. BABYLON.serialize("invertNormalMapY")
  30714. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  30715. __decorate([
  30716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30717. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30718. __decorate([
  30719. BABYLON.serialize("twoSidedLighting")
  30720. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  30721. __decorate([
  30722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30723. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  30724. __decorate([
  30725. BABYLON.serialize()
  30726. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30727. BABYLON.StandardMaterial = StandardMaterial;
  30728. })(BABYLON || (BABYLON = {}));
  30729. //# sourceMappingURL=babylon.standardMaterial.js.map
  30730. var BABYLON;
  30731. (function (BABYLON) {
  30732. var PBRMaterialDefines = (function (_super) {
  30733. __extends(PBRMaterialDefines, _super);
  30734. function PBRMaterialDefines() {
  30735. var _this = _super.call(this) || this;
  30736. _this.PBR = true;
  30737. _this.MAINUV1 = false;
  30738. _this.MAINUV2 = false;
  30739. _this.UV1 = false;
  30740. _this.UV2 = false;
  30741. _this.ALBEDO = false;
  30742. _this.ALBEDODIRECTUV = 0;
  30743. _this.VERTEXCOLOR = false;
  30744. _this.AMBIENT = false;
  30745. _this.AMBIENTDIRECTUV = 0;
  30746. _this.AMBIENTINGRAYSCALE = false;
  30747. _this.OPACITY = false;
  30748. _this.VERTEXALPHA = false;
  30749. _this.OPACITYDIRECTUV = 0;
  30750. _this.OPACITYRGB = false;
  30751. _this.ALPHATEST = false;
  30752. _this.ALPHABLEND = false;
  30753. _this.ALPHAFROMALBEDO = false;
  30754. _this.ALPHATESTVALUE = 0.5;
  30755. _this.SPECULAROVERALPHA = false;
  30756. _this.RADIANCEOVERALPHA = false;
  30757. _this.ALPHAFRESNEL = false;
  30758. _this.PREMULTIPLYALPHA = false;
  30759. _this.EMISSIVE = false;
  30760. _this.EMISSIVEDIRECTUV = 0;
  30761. _this.REFLECTIVITY = false;
  30762. _this.REFLECTIVITYDIRECTUV = 0;
  30763. _this.SPECULARTERM = false;
  30764. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  30765. _this.MICROSURFACEAUTOMATIC = false;
  30766. _this.LODBASEDMICROSFURACE = false;
  30767. _this.MICROSURFACEMAP = false;
  30768. _this.MICROSURFACEMAPDIRECTUV = 0;
  30769. _this.METALLICWORKFLOW = false;
  30770. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  30771. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  30772. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  30773. _this.AOSTOREINMETALMAPRED = false;
  30774. _this.ENVIRONMENTBRDF = false;
  30775. _this.NORMAL = false;
  30776. _this.TANGENT = false;
  30777. _this.BUMP = false;
  30778. _this.BUMPDIRECTUV = 0;
  30779. _this.PARALLAX = false;
  30780. _this.PARALLAXOCCLUSION = false;
  30781. _this.NORMALXYSCALE = true;
  30782. _this.LIGHTMAP = false;
  30783. _this.LIGHTMAPDIRECTUV = 0;
  30784. _this.USELIGHTMAPASSHADOWMAP = false;
  30785. _this.REFLECTION = false;
  30786. _this.REFLECTIONMAP_3D = false;
  30787. _this.REFLECTIONMAP_SPHERICAL = false;
  30788. _this.REFLECTIONMAP_PLANAR = false;
  30789. _this.REFLECTIONMAP_CUBIC = false;
  30790. _this.REFLECTIONMAP_PROJECTION = false;
  30791. _this.REFLECTIONMAP_SKYBOX = false;
  30792. _this.REFLECTIONMAP_EXPLICIT = false;
  30793. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30794. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30795. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30796. _this.INVERTCUBICMAP = false;
  30797. _this.USESPHERICALFROMREFLECTIONMAP = false;
  30798. _this.USESPHERICALINFRAGMENT = false;
  30799. _this.REFLECTIONMAP_OPPOSITEZ = false;
  30800. _this.LODINREFLECTIONALPHA = false;
  30801. _this.GAMMAREFLECTION = false;
  30802. _this.REFRACTION = false;
  30803. _this.REFRACTIONMAP_3D = false;
  30804. _this.REFRACTIONMAP_OPPOSITEZ = false;
  30805. _this.LODINREFRACTIONALPHA = false;
  30806. _this.GAMMAREFRACTION = false;
  30807. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  30808. _this.INSTANCES = false;
  30809. _this.NUM_BONE_INFLUENCERS = 0;
  30810. _this.BonesPerMesh = 0;
  30811. _this.MORPHTARGETS = false;
  30812. _this.MORPHTARGETS_NORMAL = false;
  30813. _this.MORPHTARGETS_TANGENT = false;
  30814. _this.NUM_MORPH_INFLUENCERS = 0;
  30815. _this.IMAGEPROCESSING = false;
  30816. _this.VIGNETTE = false;
  30817. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30818. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30819. _this.TONEMAPPING = false;
  30820. _this.CONTRAST = false;
  30821. _this.COLORCURVES = false;
  30822. _this.COLORGRADING = false;
  30823. _this.SAMPLER3DGREENDEPTH = false;
  30824. _this.SAMPLER3DBGRMAP = false;
  30825. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30826. _this.EXPOSURE = false;
  30827. _this.USEPHYSICALLIGHTFALLOFF = false;
  30828. _this.TWOSIDEDLIGHTING = false;
  30829. _this.SHADOWFLOAT = false;
  30830. _this.USERIGHTHANDEDSYSTEM = false;
  30831. _this.CLIPPLANE = false;
  30832. _this.POINTSIZE = false;
  30833. _this.FOG = false;
  30834. _this.LOGARITHMICDEPTH = false;
  30835. _this.FORCENORMALFORWARD = false;
  30836. _this.rebuild();
  30837. return _this;
  30838. }
  30839. PBRMaterialDefines.prototype.reset = function () {
  30840. _super.prototype.reset.call(this);
  30841. this.ALPHATESTVALUE = 0.5;
  30842. this.PBR = true;
  30843. };
  30844. return PBRMaterialDefines;
  30845. }(BABYLON.MaterialDefines));
  30846. /**
  30847. * The Physically based material base class of BJS.
  30848. *
  30849. * This offers the main features of a standard PBR material.
  30850. * For more information, please refer to the documentation :
  30851. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  30852. */
  30853. var PBRBaseMaterial = (function (_super) {
  30854. __extends(PBRBaseMaterial, _super);
  30855. /**
  30856. * Instantiates a new PBRMaterial instance.
  30857. *
  30858. * @param name The material name
  30859. * @param scene The scene the material will be use in.
  30860. */
  30861. function PBRBaseMaterial(name, scene) {
  30862. var _this = _super.call(this, name, scene) || this;
  30863. /**
  30864. * Intensity of the direct lights e.g. the four lights available in your scene.
  30865. * This impacts both the direct diffuse and specular highlights.
  30866. */
  30867. _this._directIntensity = 1.0;
  30868. /**
  30869. * Intensity of the emissive part of the material.
  30870. * This helps controlling the emissive effect without modifying the emissive color.
  30871. */
  30872. _this._emissiveIntensity = 1.0;
  30873. /**
  30874. * Intensity of the environment e.g. how much the environment will light the object
  30875. * either through harmonics for rough material or through the refelction for shiny ones.
  30876. */
  30877. _this._environmentIntensity = 1.0;
  30878. /**
  30879. * This is a special control allowing the reduction of the specular highlights coming from the
  30880. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  30881. */
  30882. _this._specularIntensity = 1.0;
  30883. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  30884. /**
  30885. * Debug Control allowing disabling the bump map on this material.
  30886. */
  30887. _this._disableBumpMap = false;
  30888. /**
  30889. * AKA Occlusion Texture Intensity in other nomenclature.
  30890. */
  30891. _this._ambientTextureStrength = 1.0;
  30892. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  30893. /**
  30894. * AKA Diffuse Color in other nomenclature.
  30895. */
  30896. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  30897. /**
  30898. * AKA Specular Color in other nomenclature.
  30899. */
  30900. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  30901. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  30902. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  30903. /**
  30904. * AKA Glossiness in other nomenclature.
  30905. */
  30906. _this._microSurface = 0.9;
  30907. /**
  30908. * source material index of refraction (IOR)' / 'destination material IOR.
  30909. */
  30910. _this._indexOfRefraction = 0.66;
  30911. /**
  30912. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  30913. */
  30914. _this._invertRefractionY = false;
  30915. /**
  30916. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  30917. * Materials half opaque for instance using refraction could benefit from this control.
  30918. */
  30919. _this._linkRefractionWithTransparency = false;
  30920. _this._useLightmapAsShadowmap = false;
  30921. /**
  30922. * Specifies that the alpha is coming form the albedo channel alpha channel.
  30923. */
  30924. _this._useAlphaFromAlbedoTexture = false;
  30925. /**
  30926. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  30927. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  30928. */
  30929. _this._useSpecularOverAlpha = true;
  30930. /**
  30931. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  30932. */
  30933. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  30934. /**
  30935. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  30936. */
  30937. _this._useRoughnessFromMetallicTextureAlpha = true;
  30938. /**
  30939. * Specifies if the metallic texture contains the roughness information in its green channel.
  30940. */
  30941. _this._useRoughnessFromMetallicTextureGreen = false;
  30942. /**
  30943. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30944. */
  30945. _this._useMetallnessFromMetallicTextureBlue = false;
  30946. /**
  30947. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30948. */
  30949. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  30950. /**
  30951. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30952. */
  30953. _this._useAmbientInGrayScale = false;
  30954. /**
  30955. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30956. * The material will try to infer what glossiness each pixel should be.
  30957. */
  30958. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  30959. /**
  30960. * BJS is using an harcoded light falloff based on a manually sets up range.
  30961. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30962. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30963. */
  30964. _this._usePhysicalLightFalloff = true;
  30965. /**
  30966. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30967. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30968. */
  30969. _this._useRadianceOverAlpha = true;
  30970. /**
  30971. * Allows using the bump map in parallax mode.
  30972. */
  30973. _this._useParallax = false;
  30974. /**
  30975. * Allows using the bump map in parallax occlusion mode.
  30976. */
  30977. _this._useParallaxOcclusion = false;
  30978. /**
  30979. * Controls the scale bias of the parallax mode.
  30980. */
  30981. _this._parallaxScaleBias = 0.05;
  30982. /**
  30983. * If sets to true, disables all the lights affecting the material.
  30984. */
  30985. _this._disableLighting = false;
  30986. /**
  30987. * Number of Simultaneous lights allowed on the material.
  30988. */
  30989. _this._maxSimultaneousLights = 4;
  30990. /**
  30991. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  30992. */
  30993. _this._invertNormalMapX = false;
  30994. /**
  30995. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  30996. */
  30997. _this._invertNormalMapY = false;
  30998. /**
  30999. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31000. */
  31001. _this._twoSidedLighting = false;
  31002. /**
  31003. * Defines the alpha limits in alpha test mode.
  31004. */
  31005. _this._alphaCutOff = 0.4;
  31006. /**
  31007. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  31008. */
  31009. _this._forceAlphaTest = false;
  31010. /**
  31011. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31012. * in your scene composition.
  31013. */
  31014. _this._preMultiplyAlpha = false;
  31015. /**
  31016. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31017. * And/Or occlude the blended part.
  31018. */
  31019. _this._useAlphaFresnel = false;
  31020. /**
  31021. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  31022. * from cos thetav and roughness:
  31023. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  31024. */
  31025. _this._environmentBRDFTexture = null;
  31026. /**
  31027. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  31028. */
  31029. _this._forceIrradianceInFragment = false;
  31030. /**
  31031. * Force normal to face away from face.
  31032. * (Temporary internal fix to remove before 3.1)
  31033. */
  31034. _this._forceNormalForward = false;
  31035. _this._renderTargets = new BABYLON.SmartArray(16);
  31036. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  31037. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  31038. _this._tempColor = new BABYLON.Color3();
  31039. // Setup the default processing configuration to the scene.
  31040. _this._attachImageProcessingConfiguration(null);
  31041. _this.getRenderTargetTextures = function () {
  31042. _this._renderTargets.reset();
  31043. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  31044. _this._renderTargets.push(_this._reflectionTexture);
  31045. }
  31046. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  31047. _this._renderTargets.push(_this._refractionTexture);
  31048. }
  31049. return _this._renderTargets;
  31050. };
  31051. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  31052. return _this;
  31053. }
  31054. /**
  31055. * Attaches a new image processing configuration to the PBR Material.
  31056. * @param configuration
  31057. */
  31058. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  31059. var _this = this;
  31060. if (configuration === this._imageProcessingConfiguration) {
  31061. return;
  31062. }
  31063. // Detaches observer.
  31064. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31065. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31066. }
  31067. // Pick the scene configuration if needed.
  31068. if (!configuration) {
  31069. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  31070. }
  31071. else {
  31072. this._imageProcessingConfiguration = configuration;
  31073. }
  31074. // Attaches observer.
  31075. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  31076. _this._markAllSubMeshesAsImageProcessingDirty();
  31077. });
  31078. };
  31079. PBRBaseMaterial.prototype.getClassName = function () {
  31080. return "PBRBaseMaterial";
  31081. };
  31082. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  31083. get: function () {
  31084. return this._useLogarithmicDepth;
  31085. },
  31086. set: function (value) {
  31087. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  31088. },
  31089. enumerable: true,
  31090. configurable: true
  31091. });
  31092. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  31093. if (this._linkRefractionWithTransparency) {
  31094. return false;
  31095. }
  31096. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  31097. };
  31098. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  31099. if (this._forceAlphaTest) {
  31100. return true;
  31101. }
  31102. if (this._linkRefractionWithTransparency) {
  31103. return false;
  31104. }
  31105. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  31106. };
  31107. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  31108. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  31109. };
  31110. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  31111. return this._albedoTexture;
  31112. };
  31113. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31114. if (this.isFrozen) {
  31115. if (this._wasPreviouslyReady) {
  31116. return true;
  31117. }
  31118. }
  31119. if (!subMesh._materialDefines) {
  31120. subMesh._materialDefines = new PBRMaterialDefines();
  31121. }
  31122. var scene = this.getScene();
  31123. var defines = subMesh._materialDefines;
  31124. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31125. if (defines._renderId === scene.getRenderId()) {
  31126. return true;
  31127. }
  31128. }
  31129. var engine = scene.getEngine();
  31130. // Lights
  31131. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  31132. defines._needNormals = true;
  31133. // Textures
  31134. if (defines._areTexturesDirty) {
  31135. defines._needUVs = false;
  31136. if (scene.texturesEnabled) {
  31137. if (scene.getEngine().getCaps().textureLOD) {
  31138. defines.LODBASEDMICROSFURACE = true;
  31139. }
  31140. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31141. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  31142. return false;
  31143. }
  31144. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  31145. }
  31146. else {
  31147. defines.ALBEDO = false;
  31148. }
  31149. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31150. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  31151. return false;
  31152. }
  31153. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  31154. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  31155. }
  31156. else {
  31157. defines.AMBIENT = false;
  31158. }
  31159. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31160. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  31161. return false;
  31162. }
  31163. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  31164. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31165. }
  31166. else {
  31167. defines.OPACITY = false;
  31168. }
  31169. var reflectionTexture = this._getReflectionTexture();
  31170. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31171. if (!reflectionTexture.isReadyOrNotBlocking()) {
  31172. return false;
  31173. }
  31174. defines.REFLECTION = true;
  31175. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  31176. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  31177. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31178. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  31179. defines.INVERTCUBICMAP = true;
  31180. }
  31181. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  31182. switch (reflectionTexture.coordinatesMode) {
  31183. case BABYLON.Texture.CUBIC_MODE:
  31184. case BABYLON.Texture.INVCUBIC_MODE:
  31185. defines.REFLECTIONMAP_CUBIC = true;
  31186. break;
  31187. case BABYLON.Texture.EXPLICIT_MODE:
  31188. defines.REFLECTIONMAP_EXPLICIT = true;
  31189. break;
  31190. case BABYLON.Texture.PLANAR_MODE:
  31191. defines.REFLECTIONMAP_PLANAR = true;
  31192. break;
  31193. case BABYLON.Texture.PROJECTION_MODE:
  31194. defines.REFLECTIONMAP_PROJECTION = true;
  31195. break;
  31196. case BABYLON.Texture.SKYBOX_MODE:
  31197. defines.REFLECTIONMAP_SKYBOX = true;
  31198. break;
  31199. case BABYLON.Texture.SPHERICAL_MODE:
  31200. defines.REFLECTIONMAP_SPHERICAL = true;
  31201. break;
  31202. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31203. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  31204. break;
  31205. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31206. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  31207. break;
  31208. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31209. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  31210. break;
  31211. }
  31212. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  31213. if (reflectionTexture.sphericalPolynomial) {
  31214. defines.USESPHERICALFROMREFLECTIONMAP = true;
  31215. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  31216. defines.USESPHERICALINFRAGMENT = true;
  31217. }
  31218. }
  31219. }
  31220. }
  31221. else {
  31222. defines.REFLECTION = false;
  31223. defines.REFLECTIONMAP_3D = false;
  31224. defines.REFLECTIONMAP_SPHERICAL = false;
  31225. defines.REFLECTIONMAP_PLANAR = false;
  31226. defines.REFLECTIONMAP_CUBIC = false;
  31227. defines.REFLECTIONMAP_PROJECTION = false;
  31228. defines.REFLECTIONMAP_SKYBOX = false;
  31229. defines.REFLECTIONMAP_EXPLICIT = false;
  31230. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31231. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31232. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31233. defines.INVERTCUBICMAP = false;
  31234. defines.USESPHERICALFROMREFLECTIONMAP = false;
  31235. defines.USESPHERICALINFRAGMENT = false;
  31236. defines.REFLECTIONMAP_OPPOSITEZ = false;
  31237. defines.LODINREFLECTIONALPHA = false;
  31238. defines.GAMMAREFLECTION = false;
  31239. }
  31240. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31241. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  31242. return false;
  31243. }
  31244. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  31245. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31246. }
  31247. else {
  31248. defines.LIGHTMAP = false;
  31249. }
  31250. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31251. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  31252. return false;
  31253. }
  31254. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  31255. }
  31256. else {
  31257. defines.EMISSIVE = false;
  31258. }
  31259. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31260. if (this._metallicTexture) {
  31261. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  31262. return false;
  31263. }
  31264. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  31265. defines.METALLICWORKFLOW = true;
  31266. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  31267. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  31268. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  31269. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  31270. }
  31271. else if (this._reflectivityTexture) {
  31272. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  31273. return false;
  31274. }
  31275. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  31276. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  31277. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  31278. }
  31279. else {
  31280. defines.REFLECTIVITY = false;
  31281. }
  31282. if (this._microSurfaceTexture) {
  31283. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  31284. return false;
  31285. }
  31286. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  31287. }
  31288. else {
  31289. defines.MICROSURFACEMAP = false;
  31290. }
  31291. }
  31292. else {
  31293. defines.REFLECTIVITY = false;
  31294. defines.MICROSURFACEMAP = false;
  31295. }
  31296. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31297. // Bump texure can not be none blocking.
  31298. if (!this._bumpTexture.isReady()) {
  31299. return false;
  31300. }
  31301. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  31302. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31303. defines.PARALLAX = true;
  31304. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  31305. }
  31306. else {
  31307. defines.PARALLAX = false;
  31308. }
  31309. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  31310. }
  31311. else {
  31312. defines.BUMP = false;
  31313. }
  31314. var refractionTexture = this._getRefractionTexture();
  31315. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31316. if (!refractionTexture.isReadyOrNotBlocking()) {
  31317. return false;
  31318. }
  31319. defines.REFRACTION = true;
  31320. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  31321. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  31322. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  31323. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31324. if (this._linkRefractionWithTransparency) {
  31325. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  31326. }
  31327. }
  31328. else {
  31329. defines.REFRACTION = false;
  31330. }
  31331. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31332. // This is blocking.
  31333. if (!this._environmentBRDFTexture.isReady()) {
  31334. return false;
  31335. }
  31336. defines.ENVIRONMENTBRDF = true;
  31337. }
  31338. if (this._shouldUseAlphaFromAlbedoTexture()) {
  31339. defines.ALPHAFROMALBEDO = true;
  31340. }
  31341. }
  31342. if (this._useSpecularOverAlpha) {
  31343. defines.SPECULAROVERALPHA = true;
  31344. }
  31345. if (this._usePhysicalLightFalloff) {
  31346. defines.USEPHYSICALLIGHTFALLOFF = true;
  31347. }
  31348. if (this._useRadianceOverAlpha) {
  31349. defines.RADIANCEOVERALPHA = true;
  31350. }
  31351. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  31352. defines.METALLICWORKFLOW = true;
  31353. }
  31354. if (!this.backFaceCulling && this._twoSidedLighting) {
  31355. defines.TWOSIDEDLIGHTING = true;
  31356. }
  31357. defines.ALPHATESTVALUE = this._alphaCutOff;
  31358. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  31359. defines.ALPHABLEND = this.needAlphaBlending();
  31360. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  31361. }
  31362. if (defines._areImageProcessingDirty) {
  31363. if (!this._imageProcessingConfiguration.isReady()) {
  31364. return false;
  31365. }
  31366. this._imageProcessingConfiguration.prepareDefines(defines);
  31367. }
  31368. defines.FORCENORMALFORWARD = this._forceNormalForward;
  31369. // Misc.
  31370. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31371. // Values that need to be evaluated on every frame
  31372. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  31373. // Attribs
  31374. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  31375. if (mesh) {
  31376. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31377. mesh.createNormals(true);
  31378. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  31379. }
  31380. }
  31381. }
  31382. // Get correct effect
  31383. if (defines.isDirty) {
  31384. defines.markAsProcessed();
  31385. scene.resetCachedMaterial();
  31386. // Fallbacks
  31387. var fallbacks = new BABYLON.EffectFallbacks();
  31388. if (defines.ENVIRONMENTBRDF) {
  31389. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  31390. }
  31391. if (defines.REFLECTION) {
  31392. fallbacks.addFallback(0, "REFLECTION");
  31393. }
  31394. if (defines.REFRACTION) {
  31395. fallbacks.addFallback(0, "REFRACTION");
  31396. }
  31397. if (defines.REFLECTIVITY) {
  31398. fallbacks.addFallback(0, "REFLECTIVITY");
  31399. }
  31400. if (defines.BUMP) {
  31401. fallbacks.addFallback(0, "BUMP");
  31402. }
  31403. if (defines.PARALLAX) {
  31404. fallbacks.addFallback(1, "PARALLAX");
  31405. }
  31406. if (defines.PARALLAXOCCLUSION) {
  31407. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31408. }
  31409. if (defines.SPECULAROVERALPHA) {
  31410. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31411. }
  31412. if (defines.FOG) {
  31413. fallbacks.addFallback(1, "FOG");
  31414. }
  31415. if (defines.POINTSIZE) {
  31416. fallbacks.addFallback(0, "POINTSIZE");
  31417. }
  31418. if (defines.LOGARITHMICDEPTH) {
  31419. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31420. }
  31421. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31422. if (defines.SPECULARTERM) {
  31423. fallbacks.addFallback(0, "SPECULARTERM");
  31424. }
  31425. if (defines.NUM_BONE_INFLUENCERS > 0) {
  31426. fallbacks.addCPUSkinningFallback(0, mesh);
  31427. }
  31428. //Attributes
  31429. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31430. if (defines.NORMAL) {
  31431. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31432. }
  31433. if (defines.TANGENT) {
  31434. attribs.push(BABYLON.VertexBuffer.TangentKind);
  31435. }
  31436. if (defines.UV1) {
  31437. attribs.push(BABYLON.VertexBuffer.UVKind);
  31438. }
  31439. if (defines.UV2) {
  31440. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31441. }
  31442. if (defines.VERTEXCOLOR) {
  31443. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31444. }
  31445. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31446. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31447. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31448. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  31449. "vFogInfos", "vFogColor", "pointSize",
  31450. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31451. "mBones",
  31452. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31453. "vLightingIntensity",
  31454. "logarithmicDepthConstant",
  31455. "vSphericalX", "vSphericalY", "vSphericalZ",
  31456. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  31457. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  31458. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  31459. "vNormalReoderParams"
  31460. ];
  31461. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  31462. "bumpSampler", "lightmapSampler", "opacitySampler",
  31463. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  31464. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  31465. "microSurfaceSampler", "environmentBrdfSampler"];
  31466. var uniformBuffers = ["Material", "Scene"];
  31467. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31468. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31469. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31470. uniformsNames: uniforms,
  31471. uniformBuffersNames: uniformBuffers,
  31472. samplers: samplers,
  31473. defines: defines,
  31474. maxSimultaneousLights: this._maxSimultaneousLights
  31475. });
  31476. var onCompiled = function (effect) {
  31477. if (this.onCompiled) {
  31478. this.onCompiled(effect);
  31479. }
  31480. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  31481. }.bind(this);
  31482. var join = defines.toString();
  31483. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  31484. attributes: attribs,
  31485. uniformsNames: uniforms,
  31486. uniformBuffersNames: uniformBuffers,
  31487. samplers: samplers,
  31488. defines: join,
  31489. fallbacks: fallbacks,
  31490. onCompiled: onCompiled,
  31491. onError: this.onError,
  31492. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31493. }, engine), defines);
  31494. this.buildUniformLayout();
  31495. }
  31496. if (!subMesh.effect.isReady()) {
  31497. return false;
  31498. }
  31499. defines._renderId = scene.getRenderId();
  31500. this._wasPreviouslyReady = true;
  31501. return true;
  31502. };
  31503. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  31504. // Order is important !
  31505. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  31506. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  31507. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31508. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31509. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31510. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  31511. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  31512. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31513. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31514. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31515. this._uniformBuffer.addUniform("albedoMatrix", 16);
  31516. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31517. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31518. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31519. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31520. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  31521. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  31522. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31523. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  31524. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31525. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31526. this._uniformBuffer.addUniform("vReflectionColor", 3);
  31527. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  31528. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  31529. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  31530. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  31531. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  31532. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31533. this._uniformBuffer.addUniform("pointSize", 1);
  31534. this._uniformBuffer.create();
  31535. };
  31536. PBRBaseMaterial.prototype.unbind = function () {
  31537. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31538. this._uniformBuffer.setTexture("reflectionSampler", null);
  31539. }
  31540. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31541. this._uniformBuffer.setTexture("refractionSampler", null);
  31542. }
  31543. _super.prototype.unbind.call(this);
  31544. };
  31545. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  31546. this._activeEffect.setMatrix("world", world);
  31547. };
  31548. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31549. var scene = this.getScene();
  31550. var defines = subMesh._materialDefines;
  31551. if (!defines) {
  31552. return;
  31553. }
  31554. var effect = subMesh.effect;
  31555. this._activeEffect = effect;
  31556. // Matrices
  31557. this.bindOnlyWorldMatrix(world);
  31558. // Bones
  31559. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  31560. if (this._mustRebind(scene, effect, mesh.visibility)) {
  31561. this._uniformBuffer.bindToEffect(effect, "Material");
  31562. this.bindViewProjection(effect);
  31563. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31564. // Texture uniforms
  31565. if (scene.texturesEnabled) {
  31566. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31567. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  31568. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  31569. }
  31570. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31571. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  31572. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31573. }
  31574. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31575. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31576. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31577. }
  31578. var reflectionTexture = this._getReflectionTexture();
  31579. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31580. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  31581. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  31582. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  31583. var polynomials = reflectionTexture.sphericalPolynomial;
  31584. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  31585. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  31586. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  31587. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  31588. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  31589. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  31590. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  31591. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  31592. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  31593. }
  31594. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  31595. }
  31596. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31597. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31598. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31599. }
  31600. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31601. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31602. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31603. }
  31604. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31605. if (this._metallicTexture) {
  31606. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  31607. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  31608. }
  31609. else if (this._reflectivityTexture) {
  31610. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  31611. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  31612. }
  31613. if (this._microSurfaceTexture) {
  31614. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  31615. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  31616. }
  31617. }
  31618. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31619. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  31620. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31621. if (scene._mirroredCameraPosition) {
  31622. 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);
  31623. }
  31624. else {
  31625. 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);
  31626. }
  31627. }
  31628. var refractionTexture = this._getRefractionTexture();
  31629. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31630. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  31631. var depth = 1.0;
  31632. if (!refractionTexture.isCube) {
  31633. if (refractionTexture.depth) {
  31634. depth = refractionTexture.depth;
  31635. }
  31636. }
  31637. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  31638. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  31639. }
  31640. }
  31641. // Point size
  31642. if (this.pointsCloud) {
  31643. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31644. }
  31645. // Colors
  31646. if (defines.METALLICWORKFLOW) {
  31647. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  31648. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  31649. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  31650. }
  31651. else {
  31652. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  31653. }
  31654. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  31655. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  31656. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  31657. // Misc
  31658. this._lightingInfos.x = this._directIntensity;
  31659. this._lightingInfos.y = this._emissiveIntensity;
  31660. this._lightingInfos.z = this._environmentIntensity;
  31661. this._lightingInfos.w = this._specularIntensity;
  31662. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  31663. }
  31664. // Textures
  31665. if (scene.texturesEnabled) {
  31666. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31667. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  31668. }
  31669. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31670. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  31671. }
  31672. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31673. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  31674. }
  31675. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31676. if (defines.LODBASEDMICROSFURACE) {
  31677. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  31678. }
  31679. else {
  31680. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  31681. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  31682. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  31683. }
  31684. }
  31685. if (defines.ENVIRONMENTBRDF) {
  31686. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  31687. }
  31688. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31689. if (defines.LODBASEDMICROSFURACE) {
  31690. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  31691. }
  31692. else {
  31693. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  31694. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  31695. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  31696. }
  31697. }
  31698. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31699. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  31700. }
  31701. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31702. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  31703. }
  31704. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31705. if (this._metallicTexture) {
  31706. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  31707. }
  31708. else if (this._reflectivityTexture) {
  31709. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  31710. }
  31711. if (this._microSurfaceTexture) {
  31712. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  31713. }
  31714. }
  31715. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31716. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  31717. }
  31718. }
  31719. // Clip plane
  31720. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  31721. // Colors
  31722. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  31723. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  31724. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  31725. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31726. }
  31727. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  31728. // Lights
  31729. if (scene.lightsEnabled && !this._disableLighting) {
  31730. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  31731. }
  31732. // View
  31733. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  31734. this.bindView(effect);
  31735. }
  31736. // Fog
  31737. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  31738. // Morph targets
  31739. if (defines.NUM_MORPH_INFLUENCERS) {
  31740. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  31741. }
  31742. // image processing
  31743. this._imageProcessingConfiguration.bind(this._activeEffect);
  31744. // Log. depth
  31745. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  31746. }
  31747. this._uniformBuffer.update();
  31748. this._afterBind(mesh);
  31749. scene = null;
  31750. };
  31751. PBRBaseMaterial.prototype.getAnimatables = function () {
  31752. var results = [];
  31753. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  31754. results.push(this._albedoTexture);
  31755. }
  31756. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31757. results.push(this._ambientTexture);
  31758. }
  31759. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31760. results.push(this._opacityTexture);
  31761. }
  31762. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31763. results.push(this._reflectionTexture);
  31764. }
  31765. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31766. results.push(this._emissiveTexture);
  31767. }
  31768. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  31769. results.push(this._metallicTexture);
  31770. }
  31771. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  31772. results.push(this._reflectivityTexture);
  31773. }
  31774. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31775. results.push(this._bumpTexture);
  31776. }
  31777. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31778. results.push(this._lightmapTexture);
  31779. }
  31780. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31781. results.push(this._refractionTexture);
  31782. }
  31783. return results;
  31784. };
  31785. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  31786. if (this._reflectionTexture) {
  31787. return this._reflectionTexture;
  31788. }
  31789. return this.getScene().environmentTexture;
  31790. };
  31791. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  31792. if (this._refractionTexture) {
  31793. return this._refractionTexture;
  31794. }
  31795. if (this._linkRefractionWithTransparency) {
  31796. return this.getScene().environmentTexture;
  31797. }
  31798. return null;
  31799. };
  31800. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31801. if (forceDisposeTextures) {
  31802. if (this._albedoTexture) {
  31803. this._albedoTexture.dispose();
  31804. }
  31805. if (this._ambientTexture) {
  31806. this._ambientTexture.dispose();
  31807. }
  31808. if (this._opacityTexture) {
  31809. this._opacityTexture.dispose();
  31810. }
  31811. if (this._reflectionTexture) {
  31812. this._reflectionTexture.dispose();
  31813. }
  31814. if (this._environmentBRDFTexture) {
  31815. this._environmentBRDFTexture.dispose();
  31816. }
  31817. if (this._emissiveTexture) {
  31818. this._emissiveTexture.dispose();
  31819. }
  31820. if (this._metallicTexture) {
  31821. this._metallicTexture.dispose();
  31822. }
  31823. if (this._reflectivityTexture) {
  31824. this._reflectivityTexture.dispose();
  31825. }
  31826. if (this._bumpTexture) {
  31827. this._bumpTexture.dispose();
  31828. }
  31829. if (this._lightmapTexture) {
  31830. this._lightmapTexture.dispose();
  31831. }
  31832. if (this._refractionTexture) {
  31833. this._refractionTexture.dispose();
  31834. }
  31835. }
  31836. this._renderTargets.dispose();
  31837. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31838. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31839. }
  31840. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31841. };
  31842. return PBRBaseMaterial;
  31843. }(BABYLON.PushMaterial));
  31844. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  31845. __decorate([
  31846. BABYLON.serializeAsImageProcessingConfiguration()
  31847. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  31848. __decorate([
  31849. BABYLON.serialize()
  31850. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  31851. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  31852. })(BABYLON || (BABYLON = {}));
  31853. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  31854. var BABYLON;
  31855. (function (BABYLON) {
  31856. var Internals;
  31857. (function (Internals) {
  31858. /**
  31859. * The Physically based simple base material of BJS.
  31860. *
  31861. * This enables better naming and convention enforcements on top of the pbrMaterial.
  31862. * It is used as the base class for both the specGloss and metalRough conventions.
  31863. */
  31864. var PBRBaseSimpleMaterial = (function (_super) {
  31865. __extends(PBRBaseSimpleMaterial, _super);
  31866. /**
  31867. * Instantiates a new PBRMaterial instance.
  31868. *
  31869. * @param name The material name
  31870. * @param scene The scene the material will be use in.
  31871. */
  31872. function PBRBaseSimpleMaterial(name, scene) {
  31873. var _this = _super.call(this, name, scene) || this;
  31874. /**
  31875. * Number of Simultaneous lights allowed on the material.
  31876. */
  31877. _this.maxSimultaneousLights = 4;
  31878. /**
  31879. * If sets to true, disables all the lights affecting the material.
  31880. */
  31881. _this.disableLighting = false;
  31882. /**
  31883. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  31884. */
  31885. _this.invertNormalMapX = false;
  31886. /**
  31887. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  31888. */
  31889. _this.invertNormalMapY = false;
  31890. /**
  31891. * Emissivie color used to self-illuminate the model.
  31892. */
  31893. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  31894. /**
  31895. * Occlusion Channel Strenght.
  31896. */
  31897. _this.occlusionStrength = 1.0;
  31898. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  31899. _this._useAmbientInGrayScale = true;
  31900. return _this;
  31901. }
  31902. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  31903. /**
  31904. * Gets the current transparency mode.
  31905. */
  31906. get: function () {
  31907. return this._transparencyMode;
  31908. },
  31909. /**
  31910. * Sets the transparency mode of the material.
  31911. */
  31912. set: function (value) {
  31913. if (this._transparencyMode === value) {
  31914. return;
  31915. }
  31916. this._transparencyMode = value;
  31917. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  31918. this._forceAlphaTest = true;
  31919. }
  31920. else {
  31921. this._forceAlphaTest = false;
  31922. }
  31923. this._markAllSubMeshesAsTexturesDirty();
  31924. },
  31925. enumerable: true,
  31926. configurable: true
  31927. });
  31928. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  31929. /**
  31930. * Gets the current double sided mode.
  31931. */
  31932. get: function () {
  31933. return this._twoSidedLighting;
  31934. },
  31935. /**
  31936. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31937. */
  31938. set: function (value) {
  31939. if (this._twoSidedLighting === value) {
  31940. return;
  31941. }
  31942. this._twoSidedLighting = value;
  31943. this.backFaceCulling = !value;
  31944. this._markAllSubMeshesAsTexturesDirty();
  31945. },
  31946. enumerable: true,
  31947. configurable: true
  31948. });
  31949. /**
  31950. * Specifies wether or not the alpha value of the albedo texture should be used.
  31951. */
  31952. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  31953. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  31954. };
  31955. /**
  31956. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  31957. */
  31958. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  31959. if (this._linkRefractionWithTransparency) {
  31960. return false;
  31961. }
  31962. return (this.alpha < 1.0) ||
  31963. (this._shouldUseAlphaFromAlbedoTexture() &&
  31964. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  31965. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  31966. };
  31967. /**
  31968. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  31969. */
  31970. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  31971. if (this._linkRefractionWithTransparency) {
  31972. return false;
  31973. }
  31974. return this._shouldUseAlphaFromAlbedoTexture() &&
  31975. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  31976. };
  31977. /**
  31978. * Return the active textures of the material.
  31979. */
  31980. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  31981. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31982. if (this.environmentTexture) {
  31983. activeTextures.push(this.environmentTexture);
  31984. }
  31985. if (this.normalTexture) {
  31986. activeTextures.push(this.normalTexture);
  31987. }
  31988. if (this.emissiveTexture) {
  31989. activeTextures.push(this.emissiveTexture);
  31990. }
  31991. if (this.occlusionTexture) {
  31992. activeTextures.push(this.occlusionTexture);
  31993. }
  31994. return activeTextures;
  31995. };
  31996. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  31997. return "PBRBaseSimpleMaterial";
  31998. };
  31999. return PBRBaseSimpleMaterial;
  32000. }(BABYLON.PBRBaseMaterial));
  32001. __decorate([
  32002. BABYLON.serialize(),
  32003. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32004. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  32005. __decorate([
  32006. BABYLON.serialize(),
  32007. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32008. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  32009. __decorate([
  32010. BABYLON.serializeAsTexture(),
  32011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  32012. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  32013. __decorate([
  32014. BABYLON.serialize(),
  32015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32016. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  32017. __decorate([
  32018. BABYLON.serialize(),
  32019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32020. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  32021. __decorate([
  32022. BABYLON.serializeAsTexture(),
  32023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  32024. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  32025. __decorate([
  32026. BABYLON.serializeAsColor3("emissive"),
  32027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32028. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  32029. __decorate([
  32030. BABYLON.serializeAsTexture(),
  32031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32032. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  32033. __decorate([
  32034. BABYLON.serialize(),
  32035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  32036. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  32037. __decorate([
  32038. BABYLON.serializeAsTexture(),
  32039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  32040. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  32041. __decorate([
  32042. BABYLON.serialize(),
  32043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  32044. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  32045. __decorate([
  32046. BABYLON.serialize()
  32047. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  32048. __decorate([
  32049. BABYLON.serialize()
  32050. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  32051. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  32052. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32053. })(BABYLON || (BABYLON = {}));
  32054. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  32055. var BABYLON;
  32056. (function (BABYLON) {
  32057. /**
  32058. * The Physically based material of BJS.
  32059. *
  32060. * This offers the main features of a standard PBR material.
  32061. * For more information, please refer to the documentation :
  32062. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32063. */
  32064. var PBRMaterial = (function (_super) {
  32065. __extends(PBRMaterial, _super);
  32066. /**
  32067. * Instantiates a new PBRMaterial instance.
  32068. *
  32069. * @param name The material name
  32070. * @param scene The scene the material will be use in.
  32071. */
  32072. function PBRMaterial(name, scene) {
  32073. var _this = _super.call(this, name, scene) || this;
  32074. /**
  32075. * Intensity of the direct lights e.g. the four lights available in your scene.
  32076. * This impacts both the direct diffuse and specular highlights.
  32077. */
  32078. _this.directIntensity = 1.0;
  32079. /**
  32080. * Intensity of the emissive part of the material.
  32081. * This helps controlling the emissive effect without modifying the emissive color.
  32082. */
  32083. _this.emissiveIntensity = 1.0;
  32084. /**
  32085. * Intensity of the environment e.g. how much the environment will light the object
  32086. * either through harmonics for rough material or through the refelction for shiny ones.
  32087. */
  32088. _this.environmentIntensity = 1.0;
  32089. /**
  32090. * This is a special control allowing the reduction of the specular highlights coming from the
  32091. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32092. */
  32093. _this.specularIntensity = 1.0;
  32094. /**
  32095. * Debug Control allowing disabling the bump map on this material.
  32096. */
  32097. _this.disableBumpMap = false;
  32098. /**
  32099. * AKA Occlusion Texture Intensity in other nomenclature.
  32100. */
  32101. _this.ambientTextureStrength = 1.0;
  32102. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32103. /**
  32104. * AKA Diffuse Color in other nomenclature.
  32105. */
  32106. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  32107. /**
  32108. * AKA Specular Color in other nomenclature.
  32109. */
  32110. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32111. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  32112. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32113. /**
  32114. * AKA Glossiness in other nomenclature.
  32115. */
  32116. _this.microSurface = 1.0;
  32117. /**
  32118. * source material index of refraction (IOR)' / 'destination material IOR.
  32119. */
  32120. _this.indexOfRefraction = 0.66;
  32121. /**
  32122. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32123. */
  32124. _this.invertRefractionY = false;
  32125. /**
  32126. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32127. * Materials half opaque for instance using refraction could benefit from this control.
  32128. */
  32129. _this.linkRefractionWithTransparency = false;
  32130. _this.useLightmapAsShadowmap = false;
  32131. /**
  32132. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32133. */
  32134. _this.useAlphaFromAlbedoTexture = false;
  32135. /**
  32136. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32137. */
  32138. _this.forceAlphaTest = false;
  32139. /**
  32140. * Defines the alpha limits in alpha test mode.
  32141. */
  32142. _this.alphaCutOff = 0.4;
  32143. /**
  32144. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32145. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32146. */
  32147. _this.useSpecularOverAlpha = true;
  32148. /**
  32149. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32150. */
  32151. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  32152. /**
  32153. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32154. */
  32155. _this.useRoughnessFromMetallicTextureAlpha = true;
  32156. /**
  32157. * Specifies if the metallic texture contains the roughness information in its green channel.
  32158. */
  32159. _this.useRoughnessFromMetallicTextureGreen = false;
  32160. /**
  32161. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32162. */
  32163. _this.useMetallnessFromMetallicTextureBlue = false;
  32164. /**
  32165. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32166. */
  32167. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  32168. /**
  32169. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32170. */
  32171. _this.useAmbientInGrayScale = false;
  32172. /**
  32173. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32174. * The material will try to infer what glossiness each pixel should be.
  32175. */
  32176. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  32177. /**
  32178. * BJS is using an harcoded light falloff based on a manually sets up range.
  32179. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32180. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32181. */
  32182. _this.usePhysicalLightFalloff = true;
  32183. /**
  32184. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32185. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32186. */
  32187. _this.useRadianceOverAlpha = true;
  32188. /**
  32189. * Allows using the bump map in parallax mode.
  32190. */
  32191. _this.useParallax = false;
  32192. /**
  32193. * Allows using the bump map in parallax occlusion mode.
  32194. */
  32195. _this.useParallaxOcclusion = false;
  32196. /**
  32197. * Controls the scale bias of the parallax mode.
  32198. */
  32199. _this.parallaxScaleBias = 0.05;
  32200. /**
  32201. * If sets to true, disables all the lights affecting the material.
  32202. */
  32203. _this.disableLighting = false;
  32204. /**
  32205. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32206. */
  32207. _this.forceIrradianceInFragment = false;
  32208. /**
  32209. * Number of Simultaneous lights allowed on the material.
  32210. */
  32211. _this.maxSimultaneousLights = 4;
  32212. /**
  32213. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32214. */
  32215. _this.invertNormalMapX = false;
  32216. /**
  32217. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32218. */
  32219. _this.invertNormalMapY = false;
  32220. /**
  32221. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32222. */
  32223. _this.twoSidedLighting = false;
  32224. /**
  32225. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32226. * in your scene composition.
  32227. */
  32228. _this.preMultiplyAlpha = false;
  32229. /**
  32230. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32231. * And/Or occlude the blended part.
  32232. */
  32233. _this.useAlphaFresnel = false;
  32234. /**
  32235. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32236. * And/Or occlude the blended part.
  32237. */
  32238. _this.environmentBRDFTexture = null;
  32239. /**
  32240. * Force normal to face away from face.
  32241. * (Temporary internal fix to remove before 3.1)
  32242. */
  32243. _this.forceNormalForward = false;
  32244. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32245. return _this;
  32246. }
  32247. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  32248. /**
  32249. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  32250. */
  32251. get: function () {
  32252. return this._PBRMATERIAL_OPAQUE;
  32253. },
  32254. enumerable: true,
  32255. configurable: true
  32256. });
  32257. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  32258. /**
  32259. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  32260. */
  32261. get: function () {
  32262. return this._PBRMATERIAL_ALPHATEST;
  32263. },
  32264. enumerable: true,
  32265. configurable: true
  32266. });
  32267. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  32268. /**
  32269. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32270. */
  32271. get: function () {
  32272. return this._PBRMATERIAL_ALPHABLEND;
  32273. },
  32274. enumerable: true,
  32275. configurable: true
  32276. });
  32277. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  32278. /**
  32279. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32280. * They are also discarded below the alpha cutoff threshold to improve performances.
  32281. */
  32282. get: function () {
  32283. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  32284. },
  32285. enumerable: true,
  32286. configurable: true
  32287. });
  32288. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  32289. /**
  32290. * Gets the image processing configuration used either in this material.
  32291. */
  32292. get: function () {
  32293. return this._imageProcessingConfiguration;
  32294. },
  32295. /**
  32296. * Sets the Default image processing configuration used either in the this material.
  32297. *
  32298. * If sets to null, the scene one is in use.
  32299. */
  32300. set: function (value) {
  32301. this._attachImageProcessingConfiguration(value);
  32302. // Ensure the effect will be rebuilt.
  32303. this._markAllSubMeshesAsTexturesDirty();
  32304. },
  32305. enumerable: true,
  32306. configurable: true
  32307. });
  32308. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  32309. /**
  32310. * Gets wether the color curves effect is enabled.
  32311. */
  32312. get: function () {
  32313. return this.imageProcessingConfiguration.colorCurvesEnabled;
  32314. },
  32315. /**
  32316. * Sets wether the color curves effect is enabled.
  32317. */
  32318. set: function (value) {
  32319. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  32320. },
  32321. enumerable: true,
  32322. configurable: true
  32323. });
  32324. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  32325. /**
  32326. * Gets wether the color grading effect is enabled.
  32327. */
  32328. get: function () {
  32329. return this.imageProcessingConfiguration.colorGradingEnabled;
  32330. },
  32331. /**
  32332. * Gets wether the color grading effect is enabled.
  32333. */
  32334. set: function (value) {
  32335. this.imageProcessingConfiguration.colorGradingEnabled = value;
  32336. },
  32337. enumerable: true,
  32338. configurable: true
  32339. });
  32340. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  32341. /**
  32342. * Gets wether tonemapping is enabled or not.
  32343. */
  32344. get: function () {
  32345. return this._imageProcessingConfiguration.toneMappingEnabled;
  32346. },
  32347. /**
  32348. * Sets wether tonemapping is enabled or not
  32349. */
  32350. set: function (value) {
  32351. this._imageProcessingConfiguration.toneMappingEnabled = value;
  32352. },
  32353. enumerable: true,
  32354. configurable: true
  32355. });
  32356. ;
  32357. ;
  32358. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  32359. /**
  32360. * The camera exposure used on this material.
  32361. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32362. * This corresponds to a photographic exposure.
  32363. */
  32364. get: function () {
  32365. return this._imageProcessingConfiguration.exposure;
  32366. },
  32367. /**
  32368. * The camera exposure used on this material.
  32369. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32370. * This corresponds to a photographic exposure.
  32371. */
  32372. set: function (value) {
  32373. this._imageProcessingConfiguration.exposure = value;
  32374. },
  32375. enumerable: true,
  32376. configurable: true
  32377. });
  32378. ;
  32379. ;
  32380. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  32381. /**
  32382. * Gets The camera contrast used on this material.
  32383. */
  32384. get: function () {
  32385. return this._imageProcessingConfiguration.contrast;
  32386. },
  32387. /**
  32388. * Sets The camera contrast used on this material.
  32389. */
  32390. set: function (value) {
  32391. this._imageProcessingConfiguration.contrast = value;
  32392. },
  32393. enumerable: true,
  32394. configurable: true
  32395. });
  32396. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  32397. /**
  32398. * Gets the Color Grading 2D Lookup Texture.
  32399. */
  32400. get: function () {
  32401. return this._imageProcessingConfiguration.colorGradingTexture;
  32402. },
  32403. /**
  32404. * Sets the Color Grading 2D Lookup Texture.
  32405. */
  32406. set: function (value) {
  32407. this._imageProcessingConfiguration.colorGradingTexture = value;
  32408. },
  32409. enumerable: true,
  32410. configurable: true
  32411. });
  32412. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  32413. /**
  32414. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32415. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32416. * 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;
  32417. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32418. */
  32419. get: function () {
  32420. return this._imageProcessingConfiguration.colorCurves;
  32421. },
  32422. /**
  32423. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32424. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32425. * 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;
  32426. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32427. */
  32428. set: function (value) {
  32429. this._imageProcessingConfiguration.colorCurves = value;
  32430. },
  32431. enumerable: true,
  32432. configurable: true
  32433. });
  32434. PBRMaterial.prototype.getClassName = function () {
  32435. return "PBRMaterial";
  32436. };
  32437. PBRMaterial.prototype.getActiveTextures = function () {
  32438. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32439. if (this._albedoTexture) {
  32440. activeTextures.push(this._albedoTexture);
  32441. }
  32442. if (this._ambientTexture) {
  32443. activeTextures.push(this._ambientTexture);
  32444. }
  32445. if (this._opacityTexture) {
  32446. activeTextures.push(this._opacityTexture);
  32447. }
  32448. if (this._reflectionTexture) {
  32449. activeTextures.push(this._reflectionTexture);
  32450. }
  32451. if (this._emissiveTexture) {
  32452. activeTextures.push(this._emissiveTexture);
  32453. }
  32454. if (this._reflectivityTexture) {
  32455. activeTextures.push(this._reflectivityTexture);
  32456. }
  32457. if (this._metallicTexture) {
  32458. activeTextures.push(this._metallicTexture);
  32459. }
  32460. if (this._microSurfaceTexture) {
  32461. activeTextures.push(this._microSurfaceTexture);
  32462. }
  32463. if (this._bumpTexture) {
  32464. activeTextures.push(this._bumpTexture);
  32465. }
  32466. if (this._lightmapTexture) {
  32467. activeTextures.push(this._lightmapTexture);
  32468. }
  32469. if (this._refractionTexture) {
  32470. activeTextures.push(this._refractionTexture);
  32471. }
  32472. return activeTextures;
  32473. };
  32474. PBRMaterial.prototype.hasTexture = function (texture) {
  32475. if (_super.prototype.hasTexture.call(this, texture)) {
  32476. return true;
  32477. }
  32478. if (this._albedoTexture === texture) {
  32479. return true;
  32480. }
  32481. if (this._ambientTexture === texture) {
  32482. return true;
  32483. }
  32484. if (this._opacityTexture === texture) {
  32485. return true;
  32486. }
  32487. if (this._reflectionTexture === texture) {
  32488. return true;
  32489. }
  32490. if (this._reflectivityTexture === texture) {
  32491. return true;
  32492. }
  32493. if (this._metallicTexture === texture) {
  32494. return true;
  32495. }
  32496. if (this._microSurfaceTexture === texture) {
  32497. return true;
  32498. }
  32499. if (this._bumpTexture === texture) {
  32500. return true;
  32501. }
  32502. if (this._lightmapTexture === texture) {
  32503. return true;
  32504. }
  32505. if (this._refractionTexture === texture) {
  32506. return true;
  32507. }
  32508. return false;
  32509. };
  32510. PBRMaterial.prototype.clone = function (name) {
  32511. var _this = this;
  32512. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  32513. };
  32514. PBRMaterial.prototype.serialize = function () {
  32515. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32516. serializationObject.customType = "BABYLON.PBRMaterial";
  32517. return serializationObject;
  32518. };
  32519. // Statics
  32520. PBRMaterial.Parse = function (source, scene, rootUrl) {
  32521. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  32522. };
  32523. return PBRMaterial;
  32524. }(BABYLON.PBRBaseMaterial));
  32525. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  32526. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  32527. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  32528. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  32529. __decorate([
  32530. BABYLON.serialize(),
  32531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32532. ], PBRMaterial.prototype, "directIntensity", void 0);
  32533. __decorate([
  32534. BABYLON.serialize(),
  32535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32536. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  32537. __decorate([
  32538. BABYLON.serialize(),
  32539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32540. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  32541. __decorate([
  32542. BABYLON.serialize(),
  32543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32544. ], PBRMaterial.prototype, "specularIntensity", void 0);
  32545. __decorate([
  32546. BABYLON.serialize(),
  32547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32548. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  32549. __decorate([
  32550. BABYLON.serializeAsTexture(),
  32551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32552. ], PBRMaterial.prototype, "albedoTexture", void 0);
  32553. __decorate([
  32554. BABYLON.serializeAsTexture(),
  32555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32556. ], PBRMaterial.prototype, "ambientTexture", void 0);
  32557. __decorate([
  32558. BABYLON.serialize(),
  32559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32560. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  32561. __decorate([
  32562. BABYLON.serializeAsTexture(),
  32563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32564. ], PBRMaterial.prototype, "opacityTexture", void 0);
  32565. __decorate([
  32566. BABYLON.serializeAsTexture(),
  32567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32568. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  32569. __decorate([
  32570. BABYLON.serializeAsTexture(),
  32571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32572. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  32573. __decorate([
  32574. BABYLON.serializeAsTexture(),
  32575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32576. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  32577. __decorate([
  32578. BABYLON.serializeAsTexture(),
  32579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32580. ], PBRMaterial.prototype, "metallicTexture", void 0);
  32581. __decorate([
  32582. BABYLON.serialize(),
  32583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32584. ], PBRMaterial.prototype, "metallic", void 0);
  32585. __decorate([
  32586. BABYLON.serialize(),
  32587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32588. ], PBRMaterial.prototype, "roughness", void 0);
  32589. __decorate([
  32590. BABYLON.serializeAsTexture(),
  32591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32592. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  32593. __decorate([
  32594. BABYLON.serializeAsTexture(),
  32595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32596. ], PBRMaterial.prototype, "bumpTexture", void 0);
  32597. __decorate([
  32598. BABYLON.serializeAsTexture(),
  32599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  32600. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  32601. __decorate([
  32602. BABYLON.serializeAsTexture(),
  32603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32604. ], PBRMaterial.prototype, "refractionTexture", void 0);
  32605. __decorate([
  32606. BABYLON.serializeAsColor3("ambient"),
  32607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32608. ], PBRMaterial.prototype, "ambientColor", void 0);
  32609. __decorate([
  32610. BABYLON.serializeAsColor3("albedo"),
  32611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32612. ], PBRMaterial.prototype, "albedoColor", void 0);
  32613. __decorate([
  32614. BABYLON.serializeAsColor3("reflectivity"),
  32615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32616. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  32617. __decorate([
  32618. BABYLON.serializeAsColor3("reflection"),
  32619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32620. ], PBRMaterial.prototype, "reflectionColor", void 0);
  32621. __decorate([
  32622. BABYLON.serializeAsColor3("emissive"),
  32623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32624. ], PBRMaterial.prototype, "emissiveColor", void 0);
  32625. __decorate([
  32626. BABYLON.serialize(),
  32627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32628. ], PBRMaterial.prototype, "microSurface", void 0);
  32629. __decorate([
  32630. BABYLON.serialize(),
  32631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32632. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  32633. __decorate([
  32634. BABYLON.serialize(),
  32635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32636. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  32637. __decorate([
  32638. BABYLON.serialize(),
  32639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32640. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  32641. __decorate([
  32642. BABYLON.serialize(),
  32643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32644. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  32645. __decorate([
  32646. BABYLON.serialize(),
  32647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32648. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  32649. __decorate([
  32650. BABYLON.serialize(),
  32651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32652. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  32653. __decorate([
  32654. BABYLON.serialize(),
  32655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32656. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  32657. __decorate([
  32658. BABYLON.serialize(),
  32659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32660. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  32661. __decorate([
  32662. BABYLON.serialize(),
  32663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32664. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  32665. __decorate([
  32666. BABYLON.serialize(),
  32667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32668. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  32669. __decorate([
  32670. BABYLON.serialize(),
  32671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32672. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  32673. __decorate([
  32674. BABYLON.serialize(),
  32675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32676. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  32677. __decorate([
  32678. BABYLON.serialize(),
  32679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32680. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  32681. __decorate([
  32682. BABYLON.serialize(),
  32683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32684. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  32685. __decorate([
  32686. BABYLON.serialize(),
  32687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32688. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  32689. __decorate([
  32690. BABYLON.serialize(),
  32691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32692. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  32693. __decorate([
  32694. BABYLON.serialize(),
  32695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32696. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  32697. __decorate([
  32698. BABYLON.serialize(),
  32699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32700. ], PBRMaterial.prototype, "useParallax", void 0);
  32701. __decorate([
  32702. BABYLON.serialize(),
  32703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32704. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  32705. __decorate([
  32706. BABYLON.serialize(),
  32707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32708. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  32709. __decorate([
  32710. BABYLON.serialize(),
  32711. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32712. ], PBRMaterial.prototype, "disableLighting", void 0);
  32713. __decorate([
  32714. BABYLON.serialize(),
  32715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32716. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  32717. __decorate([
  32718. BABYLON.serialize(),
  32719. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32720. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  32721. __decorate([
  32722. BABYLON.serialize(),
  32723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32724. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  32725. __decorate([
  32726. BABYLON.serialize(),
  32727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32728. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  32729. __decorate([
  32730. BABYLON.serialize(),
  32731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32732. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  32733. __decorate([
  32734. BABYLON.serialize(),
  32735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32736. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  32737. __decorate([
  32738. BABYLON.serialize(),
  32739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32740. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  32741. __decorate([
  32742. BABYLON.serializeAsTexture(),
  32743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32744. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  32745. __decorate([
  32746. BABYLON.serialize(),
  32747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32748. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  32749. BABYLON.PBRMaterial = PBRMaterial;
  32750. })(BABYLON || (BABYLON = {}));
  32751. //# sourceMappingURL=babylon.pbrMaterial.js.map
  32752. var BABYLON;
  32753. (function (BABYLON) {
  32754. /**
  32755. * The PBR material of BJS following the metal roughness convention.
  32756. *
  32757. * This fits to the PBR convention in the GLTF definition:
  32758. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  32759. */
  32760. var PBRMetallicRoughnessMaterial = (function (_super) {
  32761. __extends(PBRMetallicRoughnessMaterial, _super);
  32762. /**
  32763. * Instantiates a new PBRMetalRoughnessMaterial instance.
  32764. *
  32765. * @param name The material name
  32766. * @param scene The scene the material will be use in.
  32767. */
  32768. function PBRMetallicRoughnessMaterial(name, scene) {
  32769. var _this = _super.call(this, name, scene) || this;
  32770. _this._useRoughnessFromMetallicTextureAlpha = false;
  32771. _this._useRoughnessFromMetallicTextureGreen = true;
  32772. _this._useMetallnessFromMetallicTextureBlue = true;
  32773. return _this;
  32774. }
  32775. /**
  32776. * Return the currrent class name of the material.
  32777. */
  32778. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  32779. return "PBRMetallicRoughnessMaterial";
  32780. };
  32781. /**
  32782. * Return the active textures of the material.
  32783. */
  32784. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  32785. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32786. if (this.baseTexture) {
  32787. activeTextures.push(this.baseTexture);
  32788. }
  32789. if (this.metallicRoughnessTexture) {
  32790. activeTextures.push(this.metallicRoughnessTexture);
  32791. }
  32792. return activeTextures;
  32793. };
  32794. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  32795. if (_super.prototype.hasTexture.call(this, texture)) {
  32796. return true;
  32797. }
  32798. if (this.baseTexture === texture) {
  32799. return true;
  32800. }
  32801. if (this.metallicRoughnessTexture === texture) {
  32802. return true;
  32803. }
  32804. return false;
  32805. };
  32806. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  32807. var _this = this;
  32808. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  32809. };
  32810. /**
  32811. * Serialize the material to a parsable JSON object.
  32812. */
  32813. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  32814. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32815. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  32816. return serializationObject;
  32817. };
  32818. /**
  32819. * Parses a JSON object correponding to the serialize function.
  32820. */
  32821. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  32822. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  32823. };
  32824. return PBRMetallicRoughnessMaterial;
  32825. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  32826. __decorate([
  32827. BABYLON.serializeAsColor3(),
  32828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  32829. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  32830. __decorate([
  32831. BABYLON.serializeAsTexture(),
  32832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  32833. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  32834. __decorate([
  32835. BABYLON.serialize(),
  32836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32837. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  32838. __decorate([
  32839. BABYLON.serialize(),
  32840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32841. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  32842. __decorate([
  32843. BABYLON.serializeAsTexture(),
  32844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  32845. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  32846. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  32847. })(BABYLON || (BABYLON = {}));
  32848. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  32849. var BABYLON;
  32850. (function (BABYLON) {
  32851. /**
  32852. * The PBR material of BJS following the specular glossiness convention.
  32853. *
  32854. * This fits to the PBR convention in the GLTF definition:
  32855. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  32856. */
  32857. var PBRSpecularGlossinessMaterial = (function (_super) {
  32858. __extends(PBRSpecularGlossinessMaterial, _super);
  32859. /**
  32860. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  32861. *
  32862. * @param name The material name
  32863. * @param scene The scene the material will be use in.
  32864. */
  32865. function PBRSpecularGlossinessMaterial(name, scene) {
  32866. var _this = _super.call(this, name, scene) || this;
  32867. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  32868. return _this;
  32869. }
  32870. /**
  32871. * Return the currrent class name of the material.
  32872. */
  32873. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  32874. return "PBRSpecularGlossinessMaterial";
  32875. };
  32876. /**
  32877. * Return the active textures of the material.
  32878. */
  32879. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  32880. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32881. if (this.diffuseTexture) {
  32882. activeTextures.push(this.diffuseTexture);
  32883. }
  32884. if (this.specularGlossinessTexture) {
  32885. activeTextures.push(this.specularGlossinessTexture);
  32886. }
  32887. return activeTextures;
  32888. };
  32889. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  32890. if (_super.prototype.hasTexture.call(this, texture)) {
  32891. return true;
  32892. }
  32893. if (this.diffuseTexture === texture) {
  32894. return true;
  32895. }
  32896. if (this.specularGlossinessTexture === texture) {
  32897. return true;
  32898. }
  32899. return false;
  32900. };
  32901. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  32902. var _this = this;
  32903. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  32904. };
  32905. /**
  32906. * Serialize the material to a parsable JSON object.
  32907. */
  32908. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  32909. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32910. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  32911. return serializationObject;
  32912. };
  32913. /**
  32914. * Parses a JSON object correponding to the serialize function.
  32915. */
  32916. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  32917. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  32918. };
  32919. return PBRSpecularGlossinessMaterial;
  32920. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  32921. __decorate([
  32922. BABYLON.serializeAsColor3("diffuse"),
  32923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  32924. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  32925. __decorate([
  32926. BABYLON.serializeAsTexture(),
  32927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  32928. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  32929. __decorate([
  32930. BABYLON.serializeAsColor3("specular"),
  32931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  32932. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  32933. __decorate([
  32934. BABYLON.serialize(),
  32935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  32936. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  32937. __decorate([
  32938. BABYLON.serializeAsTexture(),
  32939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  32940. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  32941. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  32942. })(BABYLON || (BABYLON = {}));
  32943. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  32944. var BABYLON;
  32945. (function (BABYLON) {
  32946. BABYLON.CameraInputTypes = {};
  32947. var CameraInputsManager = (function () {
  32948. function CameraInputsManager(camera) {
  32949. this.attached = {};
  32950. this.camera = camera;
  32951. this.checkInputs = function () { };
  32952. }
  32953. CameraInputsManager.prototype.add = function (input) {
  32954. var type = input.getSimpleName();
  32955. if (this.attached[type]) {
  32956. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  32957. return;
  32958. }
  32959. this.attached[type] = input;
  32960. input.camera = this.camera;
  32961. //for checkInputs, we are dynamically creating a function
  32962. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  32963. if (input.checkInputs) {
  32964. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  32965. }
  32966. if (this.attachedElement) {
  32967. input.attachControl(this.attachedElement);
  32968. }
  32969. };
  32970. CameraInputsManager.prototype.remove = function (inputToRemove) {
  32971. for (var cam in this.attached) {
  32972. var input = this.attached[cam];
  32973. if (input === inputToRemove) {
  32974. input.detachControl(this.attachedElement);
  32975. delete this.attached[cam];
  32976. this.rebuildInputCheck();
  32977. }
  32978. }
  32979. };
  32980. CameraInputsManager.prototype.removeByType = function (inputType) {
  32981. for (var cam in this.attached) {
  32982. var input = this.attached[cam];
  32983. if (input.getClassName() === inputType) {
  32984. input.detachControl(this.attachedElement);
  32985. delete this.attached[cam];
  32986. this.rebuildInputCheck();
  32987. }
  32988. }
  32989. };
  32990. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  32991. var current = this.checkInputs;
  32992. return function () {
  32993. current();
  32994. fn();
  32995. };
  32996. };
  32997. CameraInputsManager.prototype.attachInput = function (input) {
  32998. input.attachControl(this.attachedElement, this.noPreventDefault);
  32999. };
  33000. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  33001. if (this.attachedElement) {
  33002. return;
  33003. }
  33004. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33005. this.attachedElement = element;
  33006. this.noPreventDefault = noPreventDefault;
  33007. for (var cam in this.attached) {
  33008. var input = this.attached[cam];
  33009. this.attached[cam].attachControl(element, noPreventDefault);
  33010. }
  33011. };
  33012. CameraInputsManager.prototype.detachElement = function (element) {
  33013. if (this.attachedElement !== element) {
  33014. return;
  33015. }
  33016. for (var cam in this.attached) {
  33017. var input = this.attached[cam];
  33018. this.attached[cam].detachControl(element);
  33019. }
  33020. this.attachedElement = null;
  33021. };
  33022. CameraInputsManager.prototype.rebuildInputCheck = function () {
  33023. this.checkInputs = function () { };
  33024. for (var cam in this.attached) {
  33025. var input = this.attached[cam];
  33026. if (input.checkInputs) {
  33027. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33028. }
  33029. }
  33030. };
  33031. CameraInputsManager.prototype.clear = function () {
  33032. if (this.attachedElement) {
  33033. this.detachElement(this.attachedElement);
  33034. }
  33035. this.attached = {};
  33036. this.attachedElement = null;
  33037. this.checkInputs = function () { };
  33038. };
  33039. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  33040. var inputs = {};
  33041. for (var cam in this.attached) {
  33042. var input = this.attached[cam];
  33043. var res = BABYLON.SerializationHelper.Serialize(input);
  33044. inputs[input.getClassName()] = res;
  33045. }
  33046. serializedCamera.inputsmgr = inputs;
  33047. };
  33048. CameraInputsManager.prototype.parse = function (parsedCamera) {
  33049. var parsedInputs = parsedCamera.inputsmgr;
  33050. if (parsedInputs) {
  33051. this.clear();
  33052. for (var n in parsedInputs) {
  33053. var construct = BABYLON.CameraInputTypes[n];
  33054. if (construct) {
  33055. var parsedinput = parsedInputs[n];
  33056. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  33057. this.add(input);
  33058. }
  33059. }
  33060. }
  33061. else {
  33062. //2016-03-08 this part is for managing backward compatibility
  33063. for (var n in this.attached) {
  33064. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  33065. if (construct) {
  33066. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  33067. this.remove(this.attached[n]);
  33068. this.add(input);
  33069. }
  33070. }
  33071. }
  33072. };
  33073. return CameraInputsManager;
  33074. }());
  33075. BABYLON.CameraInputsManager = CameraInputsManager;
  33076. })(BABYLON || (BABYLON = {}));
  33077. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  33078. var BABYLON;
  33079. (function (BABYLON) {
  33080. var FreeCameraMouseInput = (function () {
  33081. function FreeCameraMouseInput(touchEnabled) {
  33082. if (touchEnabled === void 0) { touchEnabled = true; }
  33083. this.touchEnabled = touchEnabled;
  33084. this.buttons = [0, 1, 2];
  33085. this.angularSensibility = 2000.0;
  33086. }
  33087. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  33088. var _this = this;
  33089. var engine = this.camera.getEngine();
  33090. if (!this._pointerInput) {
  33091. this._pointerInput = function (p, s) {
  33092. var evt = p.event;
  33093. if (!_this.touchEnabled && evt.pointerType === "touch") {
  33094. return;
  33095. }
  33096. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  33097. return;
  33098. }
  33099. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  33100. try {
  33101. evt.srcElement.setPointerCapture(evt.pointerId);
  33102. }
  33103. catch (e) {
  33104. //Nothing to do with the error. Execution will continue.
  33105. }
  33106. _this.previousPosition = {
  33107. x: evt.clientX,
  33108. y: evt.clientY
  33109. };
  33110. if (!noPreventDefault) {
  33111. evt.preventDefault();
  33112. element.focus();
  33113. }
  33114. }
  33115. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  33116. try {
  33117. evt.srcElement.releasePointerCapture(evt.pointerId);
  33118. }
  33119. catch (e) {
  33120. //Nothing to do with the error.
  33121. }
  33122. _this.previousPosition = null;
  33123. if (!noPreventDefault) {
  33124. evt.preventDefault();
  33125. }
  33126. }
  33127. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  33128. if (!_this.previousPosition || engine.isPointerLock) {
  33129. return;
  33130. }
  33131. var offsetX = evt.clientX - _this.previousPosition.x;
  33132. var offsetY = evt.clientY - _this.previousPosition.y;
  33133. if (_this.camera.getScene().useRightHandedSystem) {
  33134. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33135. }
  33136. else {
  33137. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33138. }
  33139. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33140. _this.previousPosition = {
  33141. x: evt.clientX,
  33142. y: evt.clientY
  33143. };
  33144. if (!noPreventDefault) {
  33145. evt.preventDefault();
  33146. }
  33147. }
  33148. };
  33149. }
  33150. this._onMouseMove = function (evt) {
  33151. if (!engine.isPointerLock) {
  33152. return;
  33153. }
  33154. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  33155. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  33156. if (_this.camera.getScene().useRightHandedSystem) {
  33157. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33158. }
  33159. else {
  33160. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33161. }
  33162. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33163. _this.previousPosition = null;
  33164. if (!noPreventDefault) {
  33165. evt.preventDefault();
  33166. }
  33167. };
  33168. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  33169. element.addEventListener("mousemove", this._onMouseMove, false);
  33170. };
  33171. FreeCameraMouseInput.prototype.detachControl = function (element) {
  33172. if (this._observer && element) {
  33173. this.camera.getScene().onPointerObservable.remove(this._observer);
  33174. element.removeEventListener("mousemove", this._onMouseMove);
  33175. this._observer = null;
  33176. this._onMouseMove = null;
  33177. this.previousPosition = null;
  33178. }
  33179. };
  33180. FreeCameraMouseInput.prototype.getClassName = function () {
  33181. return "FreeCameraMouseInput";
  33182. };
  33183. FreeCameraMouseInput.prototype.getSimpleName = function () {
  33184. return "mouse";
  33185. };
  33186. return FreeCameraMouseInput;
  33187. }());
  33188. __decorate([
  33189. BABYLON.serialize()
  33190. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  33191. __decorate([
  33192. BABYLON.serialize()
  33193. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  33194. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  33195. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  33196. })(BABYLON || (BABYLON = {}));
  33197. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  33198. var BABYLON;
  33199. (function (BABYLON) {
  33200. var FreeCameraKeyboardMoveInput = (function () {
  33201. function FreeCameraKeyboardMoveInput() {
  33202. this._keys = [];
  33203. this.keysUp = [38];
  33204. this.keysDown = [40];
  33205. this.keysLeft = [37];
  33206. this.keysRight = [39];
  33207. }
  33208. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  33209. var _this = this;
  33210. if (!this._onKeyDown) {
  33211. element.tabIndex = 1;
  33212. this._onKeyDown = function (evt) {
  33213. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33214. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33215. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33216. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33217. var index = _this._keys.indexOf(evt.keyCode);
  33218. if (index === -1) {
  33219. _this._keys.push(evt.keyCode);
  33220. }
  33221. if (!noPreventDefault) {
  33222. evt.preventDefault();
  33223. }
  33224. }
  33225. };
  33226. this._onKeyUp = function (evt) {
  33227. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33228. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33229. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33230. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33231. var index = _this._keys.indexOf(evt.keyCode);
  33232. if (index >= 0) {
  33233. _this._keys.splice(index, 1);
  33234. }
  33235. if (!noPreventDefault) {
  33236. evt.preventDefault();
  33237. }
  33238. }
  33239. };
  33240. element.addEventListener("keydown", this._onKeyDown, false);
  33241. element.addEventListener("keyup", this._onKeyUp, false);
  33242. BABYLON.Tools.RegisterTopRootEvents([
  33243. { name: "blur", handler: this._onLostFocus }
  33244. ]);
  33245. }
  33246. };
  33247. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  33248. if (this._onKeyDown) {
  33249. element.removeEventListener("keydown", this._onKeyDown);
  33250. element.removeEventListener("keyup", this._onKeyUp);
  33251. BABYLON.Tools.UnregisterTopRootEvents([
  33252. { name: "blur", handler: this._onLostFocus }
  33253. ]);
  33254. this._keys = [];
  33255. this._onKeyDown = null;
  33256. this._onKeyUp = null;
  33257. }
  33258. };
  33259. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  33260. if (this._onKeyDown) {
  33261. var camera = this.camera;
  33262. // Keyboard
  33263. for (var index = 0; index < this._keys.length; index++) {
  33264. var keyCode = this._keys[index];
  33265. var speed = camera._computeLocalCameraSpeed();
  33266. if (this.keysLeft.indexOf(keyCode) !== -1) {
  33267. camera._localDirection.copyFromFloats(-speed, 0, 0);
  33268. }
  33269. else if (this.keysUp.indexOf(keyCode) !== -1) {
  33270. camera._localDirection.copyFromFloats(0, 0, speed);
  33271. }
  33272. else if (this.keysRight.indexOf(keyCode) !== -1) {
  33273. camera._localDirection.copyFromFloats(speed, 0, 0);
  33274. }
  33275. else if (this.keysDown.indexOf(keyCode) !== -1) {
  33276. camera._localDirection.copyFromFloats(0, 0, -speed);
  33277. }
  33278. if (camera.getScene().useRightHandedSystem) {
  33279. camera._localDirection.z *= -1;
  33280. }
  33281. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  33282. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  33283. camera.cameraDirection.addInPlace(camera._transformedDirection);
  33284. }
  33285. }
  33286. };
  33287. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  33288. return "FreeCameraKeyboardMoveInput";
  33289. };
  33290. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  33291. this._keys = [];
  33292. };
  33293. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  33294. return "keyboard";
  33295. };
  33296. return FreeCameraKeyboardMoveInput;
  33297. }());
  33298. __decorate([
  33299. BABYLON.serialize()
  33300. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  33301. __decorate([
  33302. BABYLON.serialize()
  33303. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  33304. __decorate([
  33305. BABYLON.serialize()
  33306. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  33307. __decorate([
  33308. BABYLON.serialize()
  33309. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  33310. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  33311. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  33312. })(BABYLON || (BABYLON = {}));
  33313. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  33314. var BABYLON;
  33315. (function (BABYLON) {
  33316. var FreeCameraInputsManager = (function (_super) {
  33317. __extends(FreeCameraInputsManager, _super);
  33318. function FreeCameraInputsManager(camera) {
  33319. return _super.call(this, camera) || this;
  33320. }
  33321. FreeCameraInputsManager.prototype.addKeyboard = function () {
  33322. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  33323. return this;
  33324. };
  33325. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  33326. if (touchEnabled === void 0) { touchEnabled = true; }
  33327. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  33328. return this;
  33329. };
  33330. FreeCameraInputsManager.prototype.addGamepad = function () {
  33331. this.add(new BABYLON.FreeCameraGamepadInput());
  33332. return this;
  33333. };
  33334. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  33335. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  33336. return this;
  33337. };
  33338. FreeCameraInputsManager.prototype.addTouch = function () {
  33339. this.add(new BABYLON.FreeCameraTouchInput());
  33340. return this;
  33341. };
  33342. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  33343. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  33344. return this;
  33345. };
  33346. return FreeCameraInputsManager;
  33347. }(BABYLON.CameraInputsManager));
  33348. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  33349. })(BABYLON || (BABYLON = {}));
  33350. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  33351. /// <reference path="babylon.camera.ts" />
  33352. var BABYLON;
  33353. (function (BABYLON) {
  33354. var TargetCamera = (function (_super) {
  33355. __extends(TargetCamera, _super);
  33356. function TargetCamera(name, position, scene) {
  33357. var _this = _super.call(this, name, position, scene) || this;
  33358. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  33359. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  33360. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  33361. _this.speed = 2.0;
  33362. _this.noRotationConstraint = false;
  33363. _this.lockedTarget = null;
  33364. _this._currentTarget = BABYLON.Vector3.Zero();
  33365. _this._viewMatrix = BABYLON.Matrix.Zero();
  33366. _this._camMatrix = BABYLON.Matrix.Zero();
  33367. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  33368. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  33369. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  33370. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  33371. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  33372. _this._lookAtTemp = BABYLON.Matrix.Zero();
  33373. _this._tempMatrix = BABYLON.Matrix.Zero();
  33374. return _this;
  33375. }
  33376. TargetCamera.prototype.getFrontPosition = function (distance) {
  33377. var direction = this.getTarget().subtract(this.position);
  33378. direction.normalize();
  33379. direction.scaleInPlace(distance);
  33380. return this.globalPosition.add(direction);
  33381. };
  33382. TargetCamera.prototype._getLockedTargetPosition = function () {
  33383. if (!this.lockedTarget) {
  33384. return null;
  33385. }
  33386. if (this.lockedTarget.absolutePosition) {
  33387. this.lockedTarget.computeWorldMatrix();
  33388. }
  33389. return this.lockedTarget.absolutePosition || this.lockedTarget;
  33390. };
  33391. // Cache
  33392. TargetCamera.prototype._initCache = function () {
  33393. _super.prototype._initCache.call(this);
  33394. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33395. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33396. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33397. };
  33398. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  33399. if (!ignoreParentClass) {
  33400. _super.prototype._updateCache.call(this);
  33401. }
  33402. var lockedTargetPosition = this._getLockedTargetPosition();
  33403. if (!lockedTargetPosition) {
  33404. this._cache.lockedTarget = null;
  33405. }
  33406. else {
  33407. if (!this._cache.lockedTarget) {
  33408. this._cache.lockedTarget = lockedTargetPosition.clone();
  33409. }
  33410. else {
  33411. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  33412. }
  33413. }
  33414. this._cache.rotation.copyFrom(this.rotation);
  33415. if (this.rotationQuaternion)
  33416. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33417. };
  33418. // Synchronized
  33419. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  33420. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  33421. return false;
  33422. }
  33423. var lockedTargetPosition = this._getLockedTargetPosition();
  33424. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  33425. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  33426. };
  33427. // Methods
  33428. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  33429. var engine = this.getEngine();
  33430. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  33431. };
  33432. // Target
  33433. TargetCamera.prototype.setTarget = function (target) {
  33434. this.upVector.normalize();
  33435. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  33436. this._camMatrix.invert();
  33437. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  33438. var vDir = target.subtract(this.position);
  33439. if (vDir.x >= 0.0) {
  33440. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  33441. }
  33442. else {
  33443. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  33444. }
  33445. this.rotation.z = 0;
  33446. if (isNaN(this.rotation.x)) {
  33447. this.rotation.x = 0;
  33448. }
  33449. if (isNaN(this.rotation.y)) {
  33450. this.rotation.y = 0;
  33451. }
  33452. if (isNaN(this.rotation.z)) {
  33453. this.rotation.z = 0;
  33454. }
  33455. if (this.rotationQuaternion) {
  33456. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  33457. }
  33458. };
  33459. /**
  33460. * Return the current target position of the camera. This value is expressed in local space.
  33461. */
  33462. TargetCamera.prototype.getTarget = function () {
  33463. return this._currentTarget;
  33464. };
  33465. TargetCamera.prototype._decideIfNeedsToMove = function () {
  33466. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  33467. };
  33468. TargetCamera.prototype._updatePosition = function () {
  33469. if (this.parent) {
  33470. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  33471. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  33472. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  33473. return;
  33474. }
  33475. this.position.addInPlace(this.cameraDirection);
  33476. };
  33477. TargetCamera.prototype._checkInputs = function () {
  33478. var needToMove = this._decideIfNeedsToMove();
  33479. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  33480. // Move
  33481. if (needToMove) {
  33482. this._updatePosition();
  33483. }
  33484. // Rotate
  33485. if (needToRotate) {
  33486. this.rotation.x += this.cameraRotation.x;
  33487. this.rotation.y += this.cameraRotation.y;
  33488. //rotate, if quaternion is set and rotation was used
  33489. if (this.rotationQuaternion) {
  33490. var len = this.rotation.lengthSquared();
  33491. if (len) {
  33492. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  33493. }
  33494. }
  33495. if (!this.noRotationConstraint) {
  33496. var limit = (Math.PI / 2) * 0.95;
  33497. if (this.rotation.x > limit)
  33498. this.rotation.x = limit;
  33499. if (this.rotation.x < -limit)
  33500. this.rotation.x = -limit;
  33501. }
  33502. }
  33503. // Inertia
  33504. if (needToMove) {
  33505. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  33506. this.cameraDirection.x = 0;
  33507. }
  33508. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  33509. this.cameraDirection.y = 0;
  33510. }
  33511. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  33512. this.cameraDirection.z = 0;
  33513. }
  33514. this.cameraDirection.scaleInPlace(this.inertia);
  33515. }
  33516. if (needToRotate) {
  33517. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  33518. this.cameraRotation.x = 0;
  33519. }
  33520. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  33521. this.cameraRotation.y = 0;
  33522. }
  33523. this.cameraRotation.scaleInPlace(this.inertia);
  33524. }
  33525. _super.prototype._checkInputs.call(this);
  33526. };
  33527. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  33528. if (this.rotationQuaternion) {
  33529. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  33530. //update the up vector!
  33531. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  33532. }
  33533. else {
  33534. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  33535. }
  33536. };
  33537. TargetCamera.prototype._getViewMatrix = function () {
  33538. if (!this.lockedTarget) {
  33539. // Compute
  33540. this._updateCameraRotationMatrix();
  33541. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  33542. // Computing target and final matrix
  33543. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  33544. }
  33545. else {
  33546. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  33547. }
  33548. if (this.getScene().useRightHandedSystem) {
  33549. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  33550. }
  33551. else {
  33552. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  33553. }
  33554. return this._viewMatrix;
  33555. };
  33556. /**
  33557. * @override
  33558. * Override Camera.createRigCamera
  33559. */
  33560. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33561. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  33562. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  33563. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  33564. if (!this.rotationQuaternion) {
  33565. this.rotationQuaternion = new BABYLON.Quaternion();
  33566. }
  33567. rigCamera._cameraRigParams = {};
  33568. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  33569. }
  33570. return rigCamera;
  33571. }
  33572. return null;
  33573. };
  33574. /**
  33575. * @override
  33576. * Override Camera._updateRigCameras
  33577. */
  33578. TargetCamera.prototype._updateRigCameras = function () {
  33579. var camLeft = this._rigCameras[0];
  33580. var camRight = this._rigCameras[1];
  33581. switch (this.cameraRigMode) {
  33582. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33583. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33585. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33586. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  33587. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  33588. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  33589. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  33590. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  33591. camLeft.setTarget(this.getTarget());
  33592. camRight.setTarget(this.getTarget());
  33593. break;
  33594. case BABYLON.Camera.RIG_MODE_VR:
  33595. if (camLeft.rotationQuaternion) {
  33596. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33597. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33598. }
  33599. else {
  33600. camLeft.rotation.copyFrom(this.rotation);
  33601. camRight.rotation.copyFrom(this.rotation);
  33602. }
  33603. camLeft.position.copyFrom(this.position);
  33604. camRight.position.copyFrom(this.position);
  33605. break;
  33606. }
  33607. _super.prototype._updateRigCameras.call(this);
  33608. };
  33609. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  33610. if (!this._rigCamTransformMatrix) {
  33611. this._rigCamTransformMatrix = new BABYLON.Matrix();
  33612. }
  33613. var target = this.getTarget();
  33614. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  33615. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  33616. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  33617. };
  33618. TargetCamera.prototype.getClassName = function () {
  33619. return "TargetCamera";
  33620. };
  33621. return TargetCamera;
  33622. }(BABYLON.Camera));
  33623. __decorate([
  33624. BABYLON.serializeAsVector3()
  33625. ], TargetCamera.prototype, "rotation", void 0);
  33626. __decorate([
  33627. BABYLON.serialize()
  33628. ], TargetCamera.prototype, "speed", void 0);
  33629. __decorate([
  33630. BABYLON.serializeAsMeshReference("lockedTargetId")
  33631. ], TargetCamera.prototype, "lockedTarget", void 0);
  33632. BABYLON.TargetCamera = TargetCamera;
  33633. })(BABYLON || (BABYLON = {}));
  33634. //# sourceMappingURL=babylon.targetCamera.js.map
  33635. var BABYLON;
  33636. (function (BABYLON) {
  33637. var FreeCamera = (function (_super) {
  33638. __extends(FreeCamera, _super);
  33639. function FreeCamera(name, position, scene) {
  33640. var _this = _super.call(this, name, position, scene) || this;
  33641. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  33642. _this.checkCollisions = false;
  33643. _this.applyGravity = false;
  33644. _this._needMoveForGravity = false;
  33645. _this._oldPosition = BABYLON.Vector3.Zero();
  33646. _this._diffPosition = BABYLON.Vector3.Zero();
  33647. _this._newPosition = BABYLON.Vector3.Zero();
  33648. // Collisions
  33649. _this._collisionMask = -1;
  33650. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  33651. if (collidedMesh === void 0) { collidedMesh = null; }
  33652. //TODO move this to the collision coordinator!
  33653. if (_this.getScene().workerCollisions)
  33654. newPosition.multiplyInPlace(_this._collider.radius);
  33655. var updatePosition = function (newPos) {
  33656. _this._newPosition.copyFrom(newPos);
  33657. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  33658. var oldPosition = _this.position.clone();
  33659. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  33660. _this.position.addInPlace(_this._diffPosition);
  33661. if (_this.onCollide && collidedMesh) {
  33662. _this.onCollide(collidedMesh);
  33663. }
  33664. }
  33665. };
  33666. updatePosition(newPosition);
  33667. };
  33668. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  33669. _this.inputs.addKeyboard().addMouse();
  33670. return _this;
  33671. }
  33672. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  33673. //-- begin properties for backward compatibility for inputs
  33674. get: function () {
  33675. var mouse = this.inputs.attached["mouse"];
  33676. if (mouse)
  33677. return mouse.angularSensibility;
  33678. },
  33679. set: function (value) {
  33680. var mouse = this.inputs.attached["mouse"];
  33681. if (mouse)
  33682. mouse.angularSensibility = value;
  33683. },
  33684. enumerable: true,
  33685. configurable: true
  33686. });
  33687. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  33688. get: function () {
  33689. var keyboard = this.inputs.attached["keyboard"];
  33690. if (keyboard)
  33691. return keyboard.keysUp;
  33692. },
  33693. set: function (value) {
  33694. var keyboard = this.inputs.attached["keyboard"];
  33695. if (keyboard)
  33696. keyboard.keysUp = value;
  33697. },
  33698. enumerable: true,
  33699. configurable: true
  33700. });
  33701. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  33702. get: function () {
  33703. var keyboard = this.inputs.attached["keyboard"];
  33704. if (keyboard)
  33705. return keyboard.keysDown;
  33706. },
  33707. set: function (value) {
  33708. var keyboard = this.inputs.attached["keyboard"];
  33709. if (keyboard)
  33710. keyboard.keysDown = value;
  33711. },
  33712. enumerable: true,
  33713. configurable: true
  33714. });
  33715. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  33716. get: function () {
  33717. var keyboard = this.inputs.attached["keyboard"];
  33718. if (keyboard)
  33719. return keyboard.keysLeft;
  33720. },
  33721. set: function (value) {
  33722. var keyboard = this.inputs.attached["keyboard"];
  33723. if (keyboard)
  33724. keyboard.keysLeft = value;
  33725. },
  33726. enumerable: true,
  33727. configurable: true
  33728. });
  33729. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  33730. get: function () {
  33731. var keyboard = this.inputs.attached["keyboard"];
  33732. if (keyboard)
  33733. return keyboard.keysRight;
  33734. },
  33735. set: function (value) {
  33736. var keyboard = this.inputs.attached["keyboard"];
  33737. if (keyboard)
  33738. keyboard.keysRight = value;
  33739. },
  33740. enumerable: true,
  33741. configurable: true
  33742. });
  33743. // Controls
  33744. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33745. this.inputs.attachElement(element, noPreventDefault);
  33746. };
  33747. FreeCamera.prototype.detachControl = function (element) {
  33748. this.inputs.detachElement(element);
  33749. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  33750. this.cameraRotation = new BABYLON.Vector2(0, 0);
  33751. };
  33752. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  33753. get: function () {
  33754. return this._collisionMask;
  33755. },
  33756. set: function (mask) {
  33757. this._collisionMask = !isNaN(mask) ? mask : -1;
  33758. },
  33759. enumerable: true,
  33760. configurable: true
  33761. });
  33762. FreeCamera.prototype._collideWithWorld = function (velocity) {
  33763. var globalPosition;
  33764. if (this.parent) {
  33765. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  33766. }
  33767. else {
  33768. globalPosition = this.position;
  33769. }
  33770. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  33771. if (!this._collider) {
  33772. this._collider = new BABYLON.Collider();
  33773. }
  33774. this._collider.radius = this.ellipsoid;
  33775. this._collider.collisionMask = this._collisionMask;
  33776. //no need for clone, as long as gravity is not on.
  33777. var actualVelocity = velocity;
  33778. //add gravity to the velocity to prevent the dual-collision checking
  33779. if (this.applyGravity) {
  33780. //this prevents mending with cameraDirection, a global variable of the free camera class.
  33781. actualVelocity = velocity.add(this.getScene().gravity);
  33782. }
  33783. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33784. };
  33785. FreeCamera.prototype._checkInputs = function () {
  33786. if (!this._localDirection) {
  33787. this._localDirection = BABYLON.Vector3.Zero();
  33788. this._transformedDirection = BABYLON.Vector3.Zero();
  33789. }
  33790. this.inputs.checkInputs();
  33791. _super.prototype._checkInputs.call(this);
  33792. };
  33793. FreeCamera.prototype._decideIfNeedsToMove = function () {
  33794. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  33795. };
  33796. FreeCamera.prototype._updatePosition = function () {
  33797. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  33798. this._collideWithWorld(this.cameraDirection);
  33799. }
  33800. else {
  33801. _super.prototype._updatePosition.call(this);
  33802. }
  33803. };
  33804. FreeCamera.prototype.dispose = function () {
  33805. this.inputs.clear();
  33806. _super.prototype.dispose.call(this);
  33807. };
  33808. FreeCamera.prototype.getClassName = function () {
  33809. return "FreeCamera";
  33810. };
  33811. return FreeCamera;
  33812. }(BABYLON.TargetCamera));
  33813. __decorate([
  33814. BABYLON.serializeAsVector3()
  33815. ], FreeCamera.prototype, "ellipsoid", void 0);
  33816. __decorate([
  33817. BABYLON.serialize()
  33818. ], FreeCamera.prototype, "checkCollisions", void 0);
  33819. __decorate([
  33820. BABYLON.serialize()
  33821. ], FreeCamera.prototype, "applyGravity", void 0);
  33822. BABYLON.FreeCamera = FreeCamera;
  33823. })(BABYLON || (BABYLON = {}));
  33824. //# sourceMappingURL=babylon.freeCamera.js.map
  33825. var BABYLON;
  33826. (function (BABYLON) {
  33827. var ArcRotateCameraKeyboardMoveInput = (function () {
  33828. function ArcRotateCameraKeyboardMoveInput() {
  33829. this._keys = [];
  33830. this.keysUp = [38];
  33831. this.keysDown = [40];
  33832. this.keysLeft = [37];
  33833. this.keysRight = [39];
  33834. }
  33835. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  33836. var _this = this;
  33837. element.tabIndex = 1;
  33838. this._onKeyDown = function (evt) {
  33839. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33840. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33841. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33842. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33843. var index = _this._keys.indexOf(evt.keyCode);
  33844. if (index === -1) {
  33845. _this._keys.push(evt.keyCode);
  33846. }
  33847. if (evt.preventDefault) {
  33848. if (!noPreventDefault) {
  33849. evt.preventDefault();
  33850. }
  33851. }
  33852. }
  33853. };
  33854. this._onKeyUp = function (evt) {
  33855. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33856. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33857. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33858. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33859. var index = _this._keys.indexOf(evt.keyCode);
  33860. if (index >= 0) {
  33861. _this._keys.splice(index, 1);
  33862. }
  33863. if (evt.preventDefault) {
  33864. if (!noPreventDefault) {
  33865. evt.preventDefault();
  33866. }
  33867. }
  33868. }
  33869. };
  33870. this._onLostFocus = function () {
  33871. _this._keys = [];
  33872. };
  33873. element.addEventListener("keydown", this._onKeyDown, false);
  33874. element.addEventListener("keyup", this._onKeyUp, false);
  33875. BABYLON.Tools.RegisterTopRootEvents([
  33876. { name: "blur", handler: this._onLostFocus }
  33877. ]);
  33878. };
  33879. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  33880. if (element) {
  33881. element.removeEventListener("keydown", this._onKeyDown);
  33882. element.removeEventListener("keyup", this._onKeyUp);
  33883. }
  33884. BABYLON.Tools.UnregisterTopRootEvents([
  33885. { name: "blur", handler: this._onLostFocus }
  33886. ]);
  33887. this._keys = [];
  33888. this._onKeyDown = null;
  33889. this._onKeyUp = null;
  33890. this._onLostFocus = null;
  33891. };
  33892. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  33893. if (this._onKeyDown) {
  33894. var camera = this.camera;
  33895. for (var index = 0; index < this._keys.length; index++) {
  33896. var keyCode = this._keys[index];
  33897. if (this.keysLeft.indexOf(keyCode) !== -1) {
  33898. camera.inertialAlphaOffset -= 0.01;
  33899. }
  33900. else if (this.keysUp.indexOf(keyCode) !== -1) {
  33901. camera.inertialBetaOffset -= 0.01;
  33902. }
  33903. else if (this.keysRight.indexOf(keyCode) !== -1) {
  33904. camera.inertialAlphaOffset += 0.01;
  33905. }
  33906. else if (this.keysDown.indexOf(keyCode) !== -1) {
  33907. camera.inertialBetaOffset += 0.01;
  33908. }
  33909. }
  33910. }
  33911. };
  33912. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  33913. return "ArcRotateCameraKeyboardMoveInput";
  33914. };
  33915. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  33916. return "keyboard";
  33917. };
  33918. return ArcRotateCameraKeyboardMoveInput;
  33919. }());
  33920. __decorate([
  33921. BABYLON.serialize()
  33922. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  33923. __decorate([
  33924. BABYLON.serialize()
  33925. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  33926. __decorate([
  33927. BABYLON.serialize()
  33928. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  33929. __decorate([
  33930. BABYLON.serialize()
  33931. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  33932. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  33933. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  33934. })(BABYLON || (BABYLON = {}));
  33935. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  33936. var BABYLON;
  33937. (function (BABYLON) {
  33938. var ArcRotateCameraMouseWheelInput = (function () {
  33939. function ArcRotateCameraMouseWheelInput() {
  33940. this.wheelPrecision = 3.0;
  33941. }
  33942. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  33943. var _this = this;
  33944. this._wheel = function (p, s) {
  33945. //sanity check - this should be a PointerWheel event.
  33946. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  33947. return;
  33948. var event = p.event;
  33949. var delta = 0;
  33950. if (event.wheelDelta) {
  33951. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  33952. }
  33953. else if (event.detail) {
  33954. delta = -event.detail / _this.wheelPrecision;
  33955. }
  33956. if (delta)
  33957. _this.camera.inertialRadiusOffset += delta;
  33958. if (event.preventDefault) {
  33959. if (!noPreventDefault) {
  33960. event.preventDefault();
  33961. }
  33962. }
  33963. };
  33964. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  33965. };
  33966. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  33967. if (this._observer && element) {
  33968. this.camera.getScene().onPointerObservable.remove(this._observer);
  33969. this._observer = null;
  33970. this._wheel = null;
  33971. }
  33972. };
  33973. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  33974. return "ArcRotateCameraMouseWheelInput";
  33975. };
  33976. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  33977. return "mousewheel";
  33978. };
  33979. return ArcRotateCameraMouseWheelInput;
  33980. }());
  33981. __decorate([
  33982. BABYLON.serialize()
  33983. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  33984. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  33985. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  33986. })(BABYLON || (BABYLON = {}));
  33987. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  33988. var BABYLON;
  33989. (function (BABYLON) {
  33990. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  33991. var ArcRotateCameraPointersInput = (function () {
  33992. function ArcRotateCameraPointersInput() {
  33993. this.buttons = [0, 1, 2];
  33994. this.angularSensibilityX = 1000.0;
  33995. this.angularSensibilityY = 1000.0;
  33996. this.pinchPrecision = 6.0;
  33997. this.panningSensibility = 50.0;
  33998. this._isPanClick = false;
  33999. this.pinchInwards = true;
  34000. }
  34001. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  34002. var _this = this;
  34003. var engine = this.camera.getEngine();
  34004. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  34005. var pointA, pointB;
  34006. var previousPinchDistance = 0;
  34007. this._pointerInput = function (p, s) {
  34008. var evt = p.event;
  34009. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34010. return;
  34011. }
  34012. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34013. try {
  34014. evt.srcElement.setPointerCapture(evt.pointerId);
  34015. }
  34016. catch (e) {
  34017. //Nothing to do with the error. Execution will continue.
  34018. }
  34019. // Manage panning with pan button click
  34020. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  34021. // manage pointers
  34022. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  34023. if (pointA === undefined) {
  34024. pointA = cacheSoloPointer;
  34025. }
  34026. else if (pointB === undefined) {
  34027. pointB = cacheSoloPointer;
  34028. }
  34029. if (!noPreventDefault) {
  34030. evt.preventDefault();
  34031. element.focus();
  34032. }
  34033. }
  34034. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34035. try {
  34036. evt.srcElement.releasePointerCapture(evt.pointerId);
  34037. }
  34038. catch (e) {
  34039. //Nothing to do with the error.
  34040. }
  34041. cacheSoloPointer = null;
  34042. previousPinchDistance = 0;
  34043. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  34044. //but emptying completly pointers collection is required to fix a bug on iPhone :
  34045. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  34046. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  34047. pointA = pointB = undefined;
  34048. if (!noPreventDefault) {
  34049. evt.preventDefault();
  34050. }
  34051. }
  34052. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34053. if (!noPreventDefault) {
  34054. evt.preventDefault();
  34055. }
  34056. // One button down
  34057. if (pointA && pointB === undefined) {
  34058. if (_this.panningSensibility !== 0 &&
  34059. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  34060. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  34061. _this.camera
  34062. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  34063. _this.camera
  34064. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  34065. }
  34066. else {
  34067. var offsetX = evt.clientX - cacheSoloPointer.x;
  34068. var offsetY = evt.clientY - cacheSoloPointer.y;
  34069. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34070. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34071. }
  34072. cacheSoloPointer.x = evt.clientX;
  34073. cacheSoloPointer.y = evt.clientY;
  34074. }
  34075. else if (pointA && pointB) {
  34076. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  34077. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  34078. ed.x = evt.clientX;
  34079. ed.y = evt.clientY;
  34080. var direction = _this.pinchInwards ? 1 : -1;
  34081. var distX = pointA.x - pointB.x;
  34082. var distY = pointA.y - pointB.y;
  34083. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  34084. if (previousPinchDistance === 0) {
  34085. previousPinchDistance = pinchSquaredDistance;
  34086. return;
  34087. }
  34088. if (pinchSquaredDistance !== previousPinchDistance) {
  34089. _this.camera
  34090. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  34091. (_this.pinchPrecision *
  34092. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  34093. direction);
  34094. previousPinchDistance = pinchSquaredDistance;
  34095. }
  34096. }
  34097. }
  34098. };
  34099. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34100. this._onContextMenu = function (evt) {
  34101. evt.preventDefault();
  34102. };
  34103. if (!this.camera._useCtrlForPanning) {
  34104. element.addEventListener("contextmenu", this._onContextMenu, false);
  34105. }
  34106. this._onLostFocus = function () {
  34107. //this._keys = [];
  34108. pointA = pointB = undefined;
  34109. previousPinchDistance = 0;
  34110. cacheSoloPointer = null;
  34111. };
  34112. this._onMouseMove = function (evt) {
  34113. if (!engine.isPointerLock) {
  34114. return;
  34115. }
  34116. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34117. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34118. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34119. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34120. if (!noPreventDefault) {
  34121. evt.preventDefault();
  34122. }
  34123. };
  34124. this._onGestureStart = function (e) {
  34125. if (window.MSGesture === undefined) {
  34126. return;
  34127. }
  34128. if (!_this._MSGestureHandler) {
  34129. _this._MSGestureHandler = new MSGesture();
  34130. _this._MSGestureHandler.target = element;
  34131. }
  34132. _this._MSGestureHandler.addPointer(e.pointerId);
  34133. };
  34134. this._onGesture = function (e) {
  34135. _this.camera.radius *= e.scale;
  34136. if (e.preventDefault) {
  34137. if (!noPreventDefault) {
  34138. e.stopPropagation();
  34139. e.preventDefault();
  34140. }
  34141. }
  34142. };
  34143. element.addEventListener("mousemove", this._onMouseMove, false);
  34144. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  34145. element.addEventListener("MSGestureChange", this._onGesture, false);
  34146. BABYLON.Tools.RegisterTopRootEvents([
  34147. { name: "blur", handler: this._onLostFocus }
  34148. ]);
  34149. };
  34150. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  34151. if (element && this._observer) {
  34152. this.camera.getScene().onPointerObservable.remove(this._observer);
  34153. this._observer = null;
  34154. element.removeEventListener("contextmenu", this._onContextMenu);
  34155. element.removeEventListener("mousemove", this._onMouseMove);
  34156. element.removeEventListener("MSPointerDown", this._onGestureStart);
  34157. element.removeEventListener("MSGestureChange", this._onGesture);
  34158. this._isPanClick = false;
  34159. this.pinchInwards = true;
  34160. this._onMouseMove = null;
  34161. this._onGestureStart = null;
  34162. this._onGesture = null;
  34163. this._MSGestureHandler = null;
  34164. this._onLostFocus = null;
  34165. this._onContextMenu = null;
  34166. }
  34167. BABYLON.Tools.UnregisterTopRootEvents([
  34168. { name: "blur", handler: this._onLostFocus }
  34169. ]);
  34170. };
  34171. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  34172. return "ArcRotateCameraPointersInput";
  34173. };
  34174. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  34175. return "pointers";
  34176. };
  34177. return ArcRotateCameraPointersInput;
  34178. }());
  34179. __decorate([
  34180. BABYLON.serialize()
  34181. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  34182. __decorate([
  34183. BABYLON.serialize()
  34184. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  34185. __decorate([
  34186. BABYLON.serialize()
  34187. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  34188. __decorate([
  34189. BABYLON.serialize()
  34190. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  34191. __decorate([
  34192. BABYLON.serialize()
  34193. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  34194. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  34195. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  34196. })(BABYLON || (BABYLON = {}));
  34197. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  34198. /// <reference path="babylon.targetCamera.ts" />
  34199. /// <reference path="..\Tools\babylon.tools.ts" />
  34200. var BABYLON;
  34201. (function (BABYLON) {
  34202. var ArcRotateCamera = (function (_super) {
  34203. __extends(ArcRotateCamera, _super);
  34204. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  34205. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  34206. _this.inertialAlphaOffset = 0;
  34207. _this.inertialBetaOffset = 0;
  34208. _this.inertialRadiusOffset = 0;
  34209. _this.lowerAlphaLimit = null;
  34210. _this.upperAlphaLimit = null;
  34211. _this.lowerBetaLimit = 0.01;
  34212. _this.upperBetaLimit = Math.PI;
  34213. _this.lowerRadiusLimit = null;
  34214. _this.upperRadiusLimit = null;
  34215. _this.inertialPanningX = 0;
  34216. _this.inertialPanningY = 0;
  34217. _this.panningInertia = 0.9;
  34218. //-- end properties for backward compatibility for inputs
  34219. _this.zoomOnFactor = 1;
  34220. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  34221. _this.allowUpsideDown = true;
  34222. _this._viewMatrix = new BABYLON.Matrix();
  34223. // Panning
  34224. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  34225. _this.checkCollisions = false;
  34226. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  34227. _this._previousPosition = BABYLON.Vector3.Zero();
  34228. _this._collisionVelocity = BABYLON.Vector3.Zero();
  34229. _this._newPosition = BABYLON.Vector3.Zero();
  34230. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34231. if (collidedMesh === void 0) { collidedMesh = null; }
  34232. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  34233. newPosition.multiplyInPlace(_this._collider.radius);
  34234. }
  34235. if (!collidedMesh) {
  34236. _this._previousPosition.copyFrom(_this.position);
  34237. }
  34238. else {
  34239. _this.setPosition(newPosition);
  34240. if (_this.onCollide) {
  34241. _this.onCollide(collidedMesh);
  34242. }
  34243. }
  34244. // Recompute because of constraints
  34245. var cosa = Math.cos(_this.alpha);
  34246. var sina = Math.sin(_this.alpha);
  34247. var cosb = Math.cos(_this.beta);
  34248. var sinb = Math.sin(_this.beta);
  34249. if (sinb === 0) {
  34250. sinb = 0.0001;
  34251. }
  34252. var target = _this._getTargetPosition();
  34253. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  34254. _this.position.copyFrom(_this._newPosition);
  34255. var up = _this.upVector;
  34256. if (_this.allowUpsideDown && _this.beta < 0) {
  34257. up = up.clone();
  34258. up = up.negate();
  34259. }
  34260. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  34261. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  34262. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  34263. _this._collisionTriggered = false;
  34264. };
  34265. _this._target = BABYLON.Vector3.Zero();
  34266. if (target) {
  34267. _this.setTarget(target);
  34268. }
  34269. _this.alpha = alpha;
  34270. _this.beta = beta;
  34271. _this.radius = radius;
  34272. _this.getViewMatrix();
  34273. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  34274. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  34275. return _this;
  34276. }
  34277. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  34278. get: function () {
  34279. return this._target;
  34280. },
  34281. set: function (value) {
  34282. this.setTarget(value);
  34283. },
  34284. enumerable: true,
  34285. configurable: true
  34286. });
  34287. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  34288. //-- begin properties for backward compatibility for inputs
  34289. get: function () {
  34290. var pointers = this.inputs.attached["pointers"];
  34291. if (pointers)
  34292. return pointers.angularSensibilityX;
  34293. },
  34294. set: function (value) {
  34295. var pointers = this.inputs.attached["pointers"];
  34296. if (pointers) {
  34297. pointers.angularSensibilityX = value;
  34298. }
  34299. },
  34300. enumerable: true,
  34301. configurable: true
  34302. });
  34303. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  34304. get: function () {
  34305. var pointers = this.inputs.attached["pointers"];
  34306. if (pointers)
  34307. return pointers.angularSensibilityY;
  34308. },
  34309. set: function (value) {
  34310. var pointers = this.inputs.attached["pointers"];
  34311. if (pointers) {
  34312. pointers.angularSensibilityY = value;
  34313. }
  34314. },
  34315. enumerable: true,
  34316. configurable: true
  34317. });
  34318. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  34319. get: function () {
  34320. var pointers = this.inputs.attached["pointers"];
  34321. if (pointers)
  34322. return pointers.pinchPrecision;
  34323. },
  34324. set: function (value) {
  34325. var pointers = this.inputs.attached["pointers"];
  34326. if (pointers) {
  34327. pointers.pinchPrecision = value;
  34328. }
  34329. },
  34330. enumerable: true,
  34331. configurable: true
  34332. });
  34333. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  34334. get: function () {
  34335. var pointers = this.inputs.attached["pointers"];
  34336. if (pointers)
  34337. return pointers.panningSensibility;
  34338. },
  34339. set: function (value) {
  34340. var pointers = this.inputs.attached["pointers"];
  34341. if (pointers) {
  34342. pointers.panningSensibility = value;
  34343. }
  34344. },
  34345. enumerable: true,
  34346. configurable: true
  34347. });
  34348. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  34349. get: function () {
  34350. var keyboard = this.inputs.attached["keyboard"];
  34351. if (keyboard)
  34352. return keyboard.keysUp;
  34353. },
  34354. set: function (value) {
  34355. var keyboard = this.inputs.attached["keyboard"];
  34356. if (keyboard)
  34357. keyboard.keysUp = value;
  34358. },
  34359. enumerable: true,
  34360. configurable: true
  34361. });
  34362. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  34363. get: function () {
  34364. var keyboard = this.inputs.attached["keyboard"];
  34365. if (keyboard)
  34366. return keyboard.keysDown;
  34367. },
  34368. set: function (value) {
  34369. var keyboard = this.inputs.attached["keyboard"];
  34370. if (keyboard)
  34371. keyboard.keysDown = value;
  34372. },
  34373. enumerable: true,
  34374. configurable: true
  34375. });
  34376. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  34377. get: function () {
  34378. var keyboard = this.inputs.attached["keyboard"];
  34379. if (keyboard)
  34380. return keyboard.keysLeft;
  34381. },
  34382. set: function (value) {
  34383. var keyboard = this.inputs.attached["keyboard"];
  34384. if (keyboard)
  34385. keyboard.keysLeft = value;
  34386. },
  34387. enumerable: true,
  34388. configurable: true
  34389. });
  34390. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  34391. get: function () {
  34392. var keyboard = this.inputs.attached["keyboard"];
  34393. if (keyboard)
  34394. return keyboard.keysRight;
  34395. },
  34396. set: function (value) {
  34397. var keyboard = this.inputs.attached["keyboard"];
  34398. if (keyboard)
  34399. keyboard.keysRight = value;
  34400. },
  34401. enumerable: true,
  34402. configurable: true
  34403. });
  34404. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  34405. get: function () {
  34406. var mousewheel = this.inputs.attached["mousewheel"];
  34407. if (mousewheel)
  34408. return mousewheel.wheelPrecision;
  34409. },
  34410. set: function (value) {
  34411. var mousewheel = this.inputs.attached["mousewheel"];
  34412. if (mousewheel)
  34413. mousewheel.wheelPrecision = value;
  34414. },
  34415. enumerable: true,
  34416. configurable: true
  34417. });
  34418. // Cache
  34419. ArcRotateCamera.prototype._initCache = function () {
  34420. _super.prototype._initCache.call(this);
  34421. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34422. this._cache.alpha = undefined;
  34423. this._cache.beta = undefined;
  34424. this._cache.radius = undefined;
  34425. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  34426. };
  34427. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  34428. if (!ignoreParentClass) {
  34429. _super.prototype._updateCache.call(this);
  34430. }
  34431. this._cache._target.copyFrom(this._getTargetPosition());
  34432. this._cache.alpha = this.alpha;
  34433. this._cache.beta = this.beta;
  34434. this._cache.radius = this.radius;
  34435. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  34436. };
  34437. ArcRotateCamera.prototype._getTargetPosition = function () {
  34438. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  34439. var pos = this._targetHost.getAbsolutePosition();
  34440. if (this._targetBoundingCenter) {
  34441. pos.addToRef(this._targetBoundingCenter, this._target);
  34442. }
  34443. else {
  34444. this._target.copyFrom(pos);
  34445. }
  34446. }
  34447. var lockedTargetPosition = this._getLockedTargetPosition();
  34448. if (lockedTargetPosition) {
  34449. return lockedTargetPosition;
  34450. }
  34451. return this._target;
  34452. };
  34453. // Synchronized
  34454. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  34455. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  34456. return false;
  34457. return this._cache._target.equals(this._getTargetPosition())
  34458. && this._cache.alpha === this.alpha
  34459. && this._cache.beta === this.beta
  34460. && this._cache.radius === this.radius
  34461. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  34462. };
  34463. // Methods
  34464. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  34465. var _this = this;
  34466. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  34467. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  34468. this._useCtrlForPanning = useCtrlForPanning;
  34469. this._panningMouseButton = panningMouseButton;
  34470. this.inputs.attachElement(element, noPreventDefault);
  34471. this._reset = function () {
  34472. _this.inertialAlphaOffset = 0;
  34473. _this.inertialBetaOffset = 0;
  34474. _this.inertialRadiusOffset = 0;
  34475. };
  34476. };
  34477. ArcRotateCamera.prototype.detachControl = function (element) {
  34478. this.inputs.detachElement(element);
  34479. if (this._reset) {
  34480. this._reset();
  34481. }
  34482. };
  34483. ArcRotateCamera.prototype._checkInputs = function () {
  34484. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  34485. if (this._collisionTriggered) {
  34486. return;
  34487. }
  34488. this.inputs.checkInputs();
  34489. // Inertia
  34490. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  34491. if (this.getScene().useRightHandedSystem) {
  34492. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  34493. }
  34494. else {
  34495. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  34496. }
  34497. this.beta += this.inertialBetaOffset;
  34498. this.radius -= this.inertialRadiusOffset;
  34499. this.inertialAlphaOffset *= this.inertia;
  34500. this.inertialBetaOffset *= this.inertia;
  34501. this.inertialRadiusOffset *= this.inertia;
  34502. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  34503. this.inertialAlphaOffset = 0;
  34504. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  34505. this.inertialBetaOffset = 0;
  34506. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  34507. this.inertialRadiusOffset = 0;
  34508. }
  34509. // Panning inertia
  34510. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  34511. if (!this._localDirection) {
  34512. this._localDirection = BABYLON.Vector3.Zero();
  34513. this._transformedDirection = BABYLON.Vector3.Zero();
  34514. }
  34515. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  34516. this._localDirection.multiplyInPlace(this.panningAxis);
  34517. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  34518. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  34519. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  34520. if (!this.panningAxis.y) {
  34521. this._transformedDirection.y = 0;
  34522. }
  34523. if (!this._targetHost) {
  34524. this._target.addInPlace(this._transformedDirection);
  34525. }
  34526. this.inertialPanningX *= this.panningInertia;
  34527. this.inertialPanningY *= this.panningInertia;
  34528. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  34529. this.inertialPanningX = 0;
  34530. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  34531. this.inertialPanningY = 0;
  34532. }
  34533. // Limits
  34534. this._checkLimits();
  34535. _super.prototype._checkInputs.call(this);
  34536. };
  34537. ArcRotateCamera.prototype._checkLimits = function () {
  34538. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  34539. if (this.allowUpsideDown && this.beta > Math.PI) {
  34540. this.beta = this.beta - (2 * Math.PI);
  34541. }
  34542. }
  34543. else {
  34544. if (this.beta < this.lowerBetaLimit) {
  34545. this.beta = this.lowerBetaLimit;
  34546. }
  34547. }
  34548. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  34549. if (this.allowUpsideDown && this.beta < -Math.PI) {
  34550. this.beta = this.beta + (2 * Math.PI);
  34551. }
  34552. }
  34553. else {
  34554. if (this.beta > this.upperBetaLimit) {
  34555. this.beta = this.upperBetaLimit;
  34556. }
  34557. }
  34558. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  34559. this.alpha = this.lowerAlphaLimit;
  34560. }
  34561. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  34562. this.alpha = this.upperAlphaLimit;
  34563. }
  34564. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  34565. this.radius = this.lowerRadiusLimit;
  34566. }
  34567. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  34568. this.radius = this.upperRadiusLimit;
  34569. }
  34570. };
  34571. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  34572. var radiusv3 = this.position.subtract(this._getTargetPosition());
  34573. this.radius = radiusv3.length();
  34574. // Alpha
  34575. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  34576. if (radiusv3.z < 0) {
  34577. this.alpha = 2 * Math.PI - this.alpha;
  34578. }
  34579. // Beta
  34580. this.beta = Math.acos(radiusv3.y / this.radius);
  34581. this._checkLimits();
  34582. };
  34583. ArcRotateCamera.prototype.setPosition = function (position) {
  34584. if (this.position.equals(position)) {
  34585. return;
  34586. }
  34587. this.position.copyFrom(position);
  34588. this.rebuildAnglesAndRadius();
  34589. };
  34590. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  34591. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  34592. if (allowSamePosition === void 0) { allowSamePosition = false; }
  34593. if (target.getBoundingInfo) {
  34594. if (toBoundingCenter) {
  34595. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  34596. }
  34597. else {
  34598. this._targetBoundingCenter = null;
  34599. }
  34600. this._targetHost = target;
  34601. this._target = this._getTargetPosition();
  34602. }
  34603. else {
  34604. var newTarget = target;
  34605. var currentTarget = this._getTargetPosition();
  34606. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  34607. return;
  34608. }
  34609. this._target = newTarget;
  34610. this._targetBoundingCenter = null;
  34611. }
  34612. this.rebuildAnglesAndRadius();
  34613. };
  34614. ArcRotateCamera.prototype._getViewMatrix = function () {
  34615. // Compute
  34616. var cosa = Math.cos(this.alpha);
  34617. var sina = Math.sin(this.alpha);
  34618. var cosb = Math.cos(this.beta);
  34619. var sinb = Math.sin(this.beta);
  34620. if (sinb === 0) {
  34621. sinb = 0.0001;
  34622. }
  34623. var target = this._getTargetPosition();
  34624. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  34625. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  34626. if (!this._collider) {
  34627. this._collider = new BABYLON.Collider();
  34628. }
  34629. this._collider.radius = this.collisionRadius;
  34630. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  34631. this._collisionTriggered = true;
  34632. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34633. }
  34634. else {
  34635. this.position.copyFrom(this._newPosition);
  34636. var up = this.upVector;
  34637. if (this.allowUpsideDown && sinb < 0) {
  34638. up = up.clone();
  34639. up = up.negate();
  34640. }
  34641. if (this.getScene().useRightHandedSystem) {
  34642. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  34643. }
  34644. else {
  34645. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  34646. }
  34647. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  34648. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  34649. }
  34650. this._currentTarget = target;
  34651. return this._viewMatrix;
  34652. };
  34653. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  34654. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  34655. meshes = meshes || this.getScene().meshes;
  34656. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  34657. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  34658. this.radius = distance * this.zoomOnFactor;
  34659. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  34660. };
  34661. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  34662. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  34663. var meshesOrMinMaxVector;
  34664. var distance;
  34665. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  34666. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  34667. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  34668. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  34669. }
  34670. else {
  34671. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  34672. distance = meshesOrMinMaxVectorAndDistance.distance;
  34673. }
  34674. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  34675. if (!doNotUpdateMaxZ) {
  34676. this.maxZ = distance * 2;
  34677. }
  34678. };
  34679. /**
  34680. * @override
  34681. * Override Camera.createRigCamera
  34682. */
  34683. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34684. var alphaShift;
  34685. switch (this.cameraRigMode) {
  34686. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34689. case BABYLON.Camera.RIG_MODE_VR:
  34690. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  34691. break;
  34692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34693. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  34694. break;
  34695. }
  34696. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  34697. rigCam._cameraRigParams = {};
  34698. return rigCam;
  34699. };
  34700. /**
  34701. * @override
  34702. * Override Camera._updateRigCameras
  34703. */
  34704. ArcRotateCamera.prototype._updateRigCameras = function () {
  34705. var camLeft = this._rigCameras[0];
  34706. var camRight = this._rigCameras[1];
  34707. camLeft.beta = camRight.beta = this.beta;
  34708. camLeft.radius = camRight.radius = this.radius;
  34709. switch (this.cameraRigMode) {
  34710. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34713. case BABYLON.Camera.RIG_MODE_VR:
  34714. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  34715. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  34716. break;
  34717. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34718. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  34719. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  34720. break;
  34721. }
  34722. _super.prototype._updateRigCameras.call(this);
  34723. };
  34724. ArcRotateCamera.prototype.dispose = function () {
  34725. this.inputs.clear();
  34726. _super.prototype.dispose.call(this);
  34727. };
  34728. ArcRotateCamera.prototype.getClassName = function () {
  34729. return "ArcRotateCamera";
  34730. };
  34731. return ArcRotateCamera;
  34732. }(BABYLON.TargetCamera));
  34733. __decorate([
  34734. BABYLON.serialize()
  34735. ], ArcRotateCamera.prototype, "alpha", void 0);
  34736. __decorate([
  34737. BABYLON.serialize()
  34738. ], ArcRotateCamera.prototype, "beta", void 0);
  34739. __decorate([
  34740. BABYLON.serialize()
  34741. ], ArcRotateCamera.prototype, "radius", void 0);
  34742. __decorate([
  34743. BABYLON.serializeAsVector3("target")
  34744. ], ArcRotateCamera.prototype, "_target", void 0);
  34745. __decorate([
  34746. BABYLON.serialize()
  34747. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  34748. __decorate([
  34749. BABYLON.serialize()
  34750. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  34751. __decorate([
  34752. BABYLON.serialize()
  34753. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  34754. __decorate([
  34755. BABYLON.serialize()
  34756. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  34757. __decorate([
  34758. BABYLON.serialize()
  34759. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  34760. __decorate([
  34761. BABYLON.serialize()
  34762. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  34763. __decorate([
  34764. BABYLON.serialize()
  34765. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  34766. __decorate([
  34767. BABYLON.serialize()
  34768. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  34769. __decorate([
  34770. BABYLON.serialize()
  34771. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  34772. __decorate([
  34773. BABYLON.serialize()
  34774. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  34775. __decorate([
  34776. BABYLON.serialize()
  34777. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  34778. __decorate([
  34779. BABYLON.serialize()
  34780. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  34781. __decorate([
  34782. BABYLON.serialize()
  34783. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  34784. __decorate([
  34785. BABYLON.serialize()
  34786. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  34787. BABYLON.ArcRotateCamera = ArcRotateCamera;
  34788. })(BABYLON || (BABYLON = {}));
  34789. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  34790. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  34791. var BABYLON;
  34792. (function (BABYLON) {
  34793. var ArcRotateCameraInputsManager = (function (_super) {
  34794. __extends(ArcRotateCameraInputsManager, _super);
  34795. function ArcRotateCameraInputsManager(camera) {
  34796. return _super.call(this, camera) || this;
  34797. }
  34798. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  34799. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  34800. return this;
  34801. };
  34802. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  34803. this.add(new BABYLON.ArcRotateCameraPointersInput());
  34804. return this;
  34805. };
  34806. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  34807. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  34808. return this;
  34809. };
  34810. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  34811. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  34812. return this;
  34813. };
  34814. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  34815. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  34816. return this;
  34817. };
  34818. return ArcRotateCameraInputsManager;
  34819. }(BABYLON.CameraInputsManager));
  34820. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  34821. })(BABYLON || (BABYLON = {}));
  34822. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  34823. var BABYLON;
  34824. (function (BABYLON) {
  34825. var HemisphericLight = (function (_super) {
  34826. __extends(HemisphericLight, _super);
  34827. /**
  34828. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  34829. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  34830. * The HemisphericLight can't cast shadows.
  34831. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34832. */
  34833. function HemisphericLight(name, direction, scene) {
  34834. var _this = _super.call(this, name, scene) || this;
  34835. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  34836. _this.direction = direction || BABYLON.Vector3.Up();
  34837. return _this;
  34838. }
  34839. HemisphericLight.prototype._buildUniformLayout = function () {
  34840. this._uniformBuffer.addUniform("vLightData", 4);
  34841. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34842. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34843. this._uniformBuffer.addUniform("vLightGround", 3);
  34844. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34845. this._uniformBuffer.addUniform("depthValues", 2);
  34846. this._uniformBuffer.create();
  34847. };
  34848. /**
  34849. * Returns the string "HemisphericLight".
  34850. */
  34851. HemisphericLight.prototype.getClassName = function () {
  34852. return "HemisphericLight";
  34853. };
  34854. /**
  34855. * Sets the HemisphericLight direction towards the passed target (Vector3).
  34856. * Returns the updated direction.
  34857. */
  34858. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  34859. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  34860. return this.direction;
  34861. };
  34862. HemisphericLight.prototype.getShadowGenerator = function () {
  34863. return null;
  34864. };
  34865. /**
  34866. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  34867. * Returns the HemisphericLight.
  34868. */
  34869. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  34870. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34871. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  34872. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  34873. return this;
  34874. };
  34875. HemisphericLight.prototype._getWorldMatrix = function () {
  34876. if (!this._worldMatrix) {
  34877. this._worldMatrix = BABYLON.Matrix.Identity();
  34878. }
  34879. return this._worldMatrix;
  34880. };
  34881. /**
  34882. * Returns the integer 3.
  34883. */
  34884. HemisphericLight.prototype.getTypeID = function () {
  34885. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  34886. };
  34887. return HemisphericLight;
  34888. }(BABYLON.Light));
  34889. __decorate([
  34890. BABYLON.serializeAsColor3()
  34891. ], HemisphericLight.prototype, "groundColor", void 0);
  34892. __decorate([
  34893. BABYLON.serializeAsVector3()
  34894. ], HemisphericLight.prototype, "direction", void 0);
  34895. BABYLON.HemisphericLight = HemisphericLight;
  34896. })(BABYLON || (BABYLON = {}));
  34897. //# sourceMappingURL=babylon.hemisphericLight.js.map
  34898. var BABYLON;
  34899. (function (BABYLON) {
  34900. var ShadowLight = (function (_super) {
  34901. __extends(ShadowLight, _super);
  34902. function ShadowLight() {
  34903. var _this = _super !== null && _super.apply(this, arguments) || this;
  34904. _this._needProjectionMatrixCompute = true;
  34905. return _this;
  34906. }
  34907. Object.defineProperty(ShadowLight.prototype, "direction", {
  34908. get: function () {
  34909. return this._direction;
  34910. },
  34911. set: function (value) {
  34912. this._direction = value;
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  34918. get: function () {
  34919. return this._shadowMinZ;
  34920. },
  34921. set: function (value) {
  34922. this._shadowMinZ = value;
  34923. this.forceProjectionMatrixCompute();
  34924. },
  34925. enumerable: true,
  34926. configurable: true
  34927. });
  34928. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  34929. get: function () {
  34930. return this._shadowMaxZ;
  34931. },
  34932. set: function (value) {
  34933. this._shadowMaxZ = value;
  34934. this.forceProjectionMatrixCompute();
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. /**
  34940. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  34941. */
  34942. ShadowLight.prototype.computeTransformedInformation = function () {
  34943. if (this.parent && this.parent.getWorldMatrix) {
  34944. if (!this.transformedPosition) {
  34945. this.transformedPosition = BABYLON.Vector3.Zero();
  34946. }
  34947. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  34948. // In case the direction is present.
  34949. if (this.direction) {
  34950. if (!this.transformedDirection) {
  34951. this.transformedDirection = BABYLON.Vector3.Zero();
  34952. }
  34953. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  34954. }
  34955. return true;
  34956. }
  34957. return false;
  34958. };
  34959. /**
  34960. * Return the depth scale used for the shadow map.
  34961. */
  34962. ShadowLight.prototype.getDepthScale = function () {
  34963. return 50.0;
  34964. };
  34965. /**
  34966. * Returns the light direction (Vector3) for any passed face index.
  34967. */
  34968. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  34969. return this.transformedDirection ? this.transformedDirection : this.direction;
  34970. };
  34971. /**
  34972. * Returns the DirectionalLight absolute position in the World.
  34973. */
  34974. ShadowLight.prototype.getAbsolutePosition = function () {
  34975. return this.transformedPosition ? this.transformedPosition : this.position;
  34976. };
  34977. /**
  34978. * Sets the DirectionalLight direction toward the passed target (Vector3).
  34979. * Returns the updated DirectionalLight direction (Vector3).
  34980. */
  34981. ShadowLight.prototype.setDirectionToTarget = function (target) {
  34982. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  34983. return this.direction;
  34984. };
  34985. /**
  34986. * Returns the light rotation (Vector3).
  34987. */
  34988. ShadowLight.prototype.getRotation = function () {
  34989. this.direction.normalize();
  34990. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  34991. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  34992. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  34993. };
  34994. /**
  34995. * Boolean : false by default.
  34996. */
  34997. ShadowLight.prototype.needCube = function () {
  34998. return false;
  34999. };
  35000. /**
  35001. * Specifies wether or not the projection matrix should be recomputed this frame.
  35002. */
  35003. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  35004. return this._needProjectionMatrixCompute;
  35005. };
  35006. /**
  35007. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  35008. */
  35009. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  35010. this._needProjectionMatrixCompute = true;
  35011. };
  35012. /**
  35013. * Get the world matrix of the sahdow lights.
  35014. */
  35015. ShadowLight.prototype._getWorldMatrix = function () {
  35016. if (!this._worldMatrix) {
  35017. this._worldMatrix = BABYLON.Matrix.Identity();
  35018. }
  35019. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  35020. return this._worldMatrix;
  35021. };
  35022. /**
  35023. * Gets the minZ used for shadow according to both the scene and the light.
  35024. * @param activeCamera
  35025. */
  35026. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  35027. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  35028. };
  35029. /**
  35030. * Gets the maxZ used for shadow according to both the scene and the light.
  35031. * @param activeCamera
  35032. */
  35033. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  35034. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  35035. };
  35036. /**
  35037. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  35038. * Returns the light.
  35039. */
  35040. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35041. if (this.customProjectionMatrixBuilder) {
  35042. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  35043. }
  35044. else {
  35045. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35046. }
  35047. return this;
  35048. };
  35049. return ShadowLight;
  35050. }(BABYLON.Light));
  35051. __decorate([
  35052. BABYLON.serializeAsVector3()
  35053. ], ShadowLight.prototype, "position", void 0);
  35054. __decorate([
  35055. BABYLON.serializeAsVector3()
  35056. ], ShadowLight.prototype, "direction", null);
  35057. __decorate([
  35058. BABYLON.serialize()
  35059. ], ShadowLight.prototype, "shadowMinZ", null);
  35060. __decorate([
  35061. BABYLON.serialize()
  35062. ], ShadowLight.prototype, "shadowMaxZ", null);
  35063. BABYLON.ShadowLight = ShadowLight;
  35064. })(BABYLON || (BABYLON = {}));
  35065. //# sourceMappingURL=babylon.shadowLight.js.map
  35066. var BABYLON;
  35067. (function (BABYLON) {
  35068. var PointLight = (function (_super) {
  35069. __extends(PointLight, _super);
  35070. /**
  35071. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  35072. * A PointLight emits the light in every direction.
  35073. * It can cast shadows.
  35074. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  35075. * ```javascript
  35076. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  35077. * ```
  35078. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35079. */
  35080. function PointLight(name, position, scene) {
  35081. var _this = _super.call(this, name, scene) || this;
  35082. _this._shadowAngle = Math.PI / 2;
  35083. _this.position = position;
  35084. return _this;
  35085. }
  35086. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  35087. /**
  35088. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35089. * This specifies what angle the shadow will use to be created.
  35090. *
  35091. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35092. */
  35093. get: function () {
  35094. return this._shadowAngle;
  35095. },
  35096. /**
  35097. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35098. * This specifies what angle the shadow will use to be created.
  35099. *
  35100. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35101. */
  35102. set: function (value) {
  35103. this._shadowAngle = value;
  35104. this.forceProjectionMatrixCompute();
  35105. },
  35106. enumerable: true,
  35107. configurable: true
  35108. });
  35109. Object.defineProperty(PointLight.prototype, "direction", {
  35110. get: function () {
  35111. return this._direction;
  35112. },
  35113. /**
  35114. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35115. */
  35116. set: function (value) {
  35117. var previousNeedCube = this.needCube();
  35118. this._direction = value;
  35119. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  35120. this._shadowGenerator.recreateShadowMap();
  35121. }
  35122. },
  35123. enumerable: true,
  35124. configurable: true
  35125. });
  35126. /**
  35127. * Returns the string "PointLight"
  35128. */
  35129. PointLight.prototype.getClassName = function () {
  35130. return "PointLight";
  35131. };
  35132. /**
  35133. * Returns the integer 0.
  35134. */
  35135. PointLight.prototype.getTypeID = function () {
  35136. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  35137. };
  35138. /**
  35139. * Specifies wether or not the shadowmap should be a cube texture.
  35140. */
  35141. PointLight.prototype.needCube = function () {
  35142. return !this.direction;
  35143. };
  35144. /**
  35145. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  35146. */
  35147. PointLight.prototype.getShadowDirection = function (faceIndex) {
  35148. if (this.direction) {
  35149. return _super.prototype.getShadowDirection.call(this, faceIndex);
  35150. }
  35151. else {
  35152. switch (faceIndex) {
  35153. case 0:
  35154. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  35155. case 1:
  35156. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  35157. case 2:
  35158. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  35159. case 3:
  35160. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  35161. case 4:
  35162. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  35163. case 5:
  35164. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  35165. }
  35166. }
  35167. return BABYLON.Vector3.Zero();
  35168. };
  35169. /**
  35170. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  35171. * - fov = PI / 2
  35172. * - aspect ratio : 1.0
  35173. * - z-near and far equal to the active camera minZ and maxZ.
  35174. * Returns the PointLight.
  35175. */
  35176. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35177. var activeCamera = this.getScene().activeCamera;
  35178. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35179. };
  35180. PointLight.prototype._buildUniformLayout = function () {
  35181. this._uniformBuffer.addUniform("vLightData", 4);
  35182. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35183. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35184. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35185. this._uniformBuffer.addUniform("depthValues", 2);
  35186. this._uniformBuffer.create();
  35187. };
  35188. /**
  35189. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  35190. * Returns the PointLight.
  35191. */
  35192. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  35193. if (this.computeTransformedInformation()) {
  35194. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  35195. return this;
  35196. }
  35197. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  35198. return this;
  35199. };
  35200. return PointLight;
  35201. }(BABYLON.ShadowLight));
  35202. __decorate([
  35203. BABYLON.serialize()
  35204. ], PointLight.prototype, "shadowAngle", null);
  35205. BABYLON.PointLight = PointLight;
  35206. })(BABYLON || (BABYLON = {}));
  35207. //# sourceMappingURL=babylon.pointLight.js.map
  35208. /// <reference path="babylon.light.ts" />
  35209. var BABYLON;
  35210. (function (BABYLON) {
  35211. var DirectionalLight = (function (_super) {
  35212. __extends(DirectionalLight, _super);
  35213. /**
  35214. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  35215. * The directional light is emitted from everywhere in the given direction.
  35216. * It can cast shawdows.
  35217. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35218. */
  35219. function DirectionalLight(name, direction, scene) {
  35220. var _this = _super.call(this, name, scene) || this;
  35221. _this._shadowFrustumSize = 0;
  35222. _this._shadowOrthoScale = 0.5;
  35223. _this.autoUpdateExtends = true;
  35224. // Cache
  35225. _this._orthoLeft = Number.MAX_VALUE;
  35226. _this._orthoRight = Number.MIN_VALUE;
  35227. _this._orthoTop = Number.MIN_VALUE;
  35228. _this._orthoBottom = Number.MAX_VALUE;
  35229. _this.position = direction.scale(-1.0);
  35230. _this.direction = direction;
  35231. return _this;
  35232. }
  35233. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  35234. /**
  35235. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  35236. */
  35237. get: function () {
  35238. return this._shadowFrustumSize;
  35239. },
  35240. /**
  35241. * Specifies a fix frustum size for the shadow generation.
  35242. */
  35243. set: function (value) {
  35244. this._shadowFrustumSize = value;
  35245. this.forceProjectionMatrixCompute();
  35246. },
  35247. enumerable: true,
  35248. configurable: true
  35249. });
  35250. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  35251. get: function () {
  35252. return this._shadowOrthoScale;
  35253. },
  35254. set: function (value) {
  35255. this._shadowOrthoScale = value;
  35256. this.forceProjectionMatrixCompute();
  35257. },
  35258. enumerable: true,
  35259. configurable: true
  35260. });
  35261. /**
  35262. * Returns the string "DirectionalLight".
  35263. */
  35264. DirectionalLight.prototype.getClassName = function () {
  35265. return "DirectionalLight";
  35266. };
  35267. /**
  35268. * Returns the integer 1.
  35269. */
  35270. DirectionalLight.prototype.getTypeID = function () {
  35271. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  35272. };
  35273. /**
  35274. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  35275. * Returns the DirectionalLight Shadow projection matrix.
  35276. */
  35277. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35278. if (this.shadowFrustumSize > 0) {
  35279. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  35280. }
  35281. else {
  35282. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35283. }
  35284. };
  35285. /**
  35286. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  35287. * Returns the DirectionalLight Shadow projection matrix.
  35288. */
  35289. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  35290. var activeCamera = this.getScene().activeCamera;
  35291. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  35292. };
  35293. /**
  35294. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  35295. * Returns the DirectionalLight Shadow projection matrix.
  35296. */
  35297. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35298. var activeCamera = this.getScene().activeCamera;
  35299. // Check extends
  35300. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  35301. var tempVector3 = BABYLON.Vector3.Zero();
  35302. this._orthoLeft = Number.MAX_VALUE;
  35303. this._orthoRight = Number.MIN_VALUE;
  35304. this._orthoTop = Number.MIN_VALUE;
  35305. this._orthoBottom = Number.MAX_VALUE;
  35306. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  35307. var mesh = renderList[meshIndex];
  35308. if (!mesh) {
  35309. continue;
  35310. }
  35311. var boundingInfo = mesh.getBoundingInfo();
  35312. if (!boundingInfo) {
  35313. continue;
  35314. }
  35315. var boundingBox = boundingInfo.boundingBox;
  35316. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  35317. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  35318. if (tempVector3.x < this._orthoLeft)
  35319. this._orthoLeft = tempVector3.x;
  35320. if (tempVector3.y < this._orthoBottom)
  35321. this._orthoBottom = tempVector3.y;
  35322. if (tempVector3.x > this._orthoRight)
  35323. this._orthoRight = tempVector3.x;
  35324. if (tempVector3.y > this._orthoTop)
  35325. this._orthoTop = tempVector3.y;
  35326. }
  35327. }
  35328. }
  35329. var xOffset = this._orthoRight - this._orthoLeft;
  35330. var yOffset = this._orthoTop - this._orthoBottom;
  35331. 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);
  35332. };
  35333. DirectionalLight.prototype._buildUniformLayout = function () {
  35334. this._uniformBuffer.addUniform("vLightData", 4);
  35335. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35336. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35337. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35338. this._uniformBuffer.addUniform("depthValues", 2);
  35339. this._uniformBuffer.create();
  35340. };
  35341. /**
  35342. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  35343. * Returns the DirectionalLight.
  35344. */
  35345. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  35346. if (this.computeTransformedInformation()) {
  35347. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  35348. return this;
  35349. }
  35350. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  35351. return this;
  35352. };
  35353. /**
  35354. * Gets the minZ used for shadow according to both the scene and the light.
  35355. *
  35356. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35357. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35358. * @param activeCamera
  35359. */
  35360. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  35361. return 1;
  35362. };
  35363. /**
  35364. * Gets the maxZ used for shadow according to both the scene and the light.
  35365. *
  35366. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35367. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35368. * @param activeCamera
  35369. */
  35370. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  35371. return 1;
  35372. };
  35373. return DirectionalLight;
  35374. }(BABYLON.ShadowLight));
  35375. __decorate([
  35376. BABYLON.serialize()
  35377. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  35378. __decorate([
  35379. BABYLON.serialize()
  35380. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  35381. __decorate([
  35382. BABYLON.serialize()
  35383. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  35384. BABYLON.DirectionalLight = DirectionalLight;
  35385. })(BABYLON || (BABYLON = {}));
  35386. //# sourceMappingURL=babylon.directionalLight.js.map
  35387. var BABYLON;
  35388. (function (BABYLON) {
  35389. var SpotLight = (function (_super) {
  35390. __extends(SpotLight, _super);
  35391. /**
  35392. * Creates a SpotLight object in the scene with the passed parameters :
  35393. * - `position` (Vector3) is the initial SpotLight position,
  35394. * - `direction` (Vector3) is the initial SpotLight direction,
  35395. * - `angle` (float, in radians) is the spot light cone angle,
  35396. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  35397. * A spot light is a simply light oriented cone.
  35398. * It can cast shadows.
  35399. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35400. */
  35401. function SpotLight(name, position, direction, angle, exponent, scene) {
  35402. var _this = _super.call(this, name, scene) || this;
  35403. _this.position = position;
  35404. _this.direction = direction;
  35405. _this.angle = angle;
  35406. _this.exponent = exponent;
  35407. return _this;
  35408. }
  35409. Object.defineProperty(SpotLight.prototype, "angle", {
  35410. get: function () {
  35411. return this._angle;
  35412. },
  35413. set: function (value) {
  35414. this._angle = value;
  35415. this.forceProjectionMatrixCompute();
  35416. },
  35417. enumerable: true,
  35418. configurable: true
  35419. });
  35420. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  35421. get: function () {
  35422. return this._shadowAngleScale;
  35423. },
  35424. /**
  35425. * Allows scaling the angle of the light for shadow generation only.
  35426. */
  35427. set: function (value) {
  35428. this._shadowAngleScale = value;
  35429. this.forceProjectionMatrixCompute();
  35430. },
  35431. enumerable: true,
  35432. configurable: true
  35433. });
  35434. /**
  35435. * Returns the string "SpotLight".
  35436. */
  35437. SpotLight.prototype.getClassName = function () {
  35438. return "SpotLight";
  35439. };
  35440. /**
  35441. * Returns the integer 2.
  35442. */
  35443. SpotLight.prototype.getTypeID = function () {
  35444. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  35445. };
  35446. /**
  35447. * 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.
  35448. * Returns the SpotLight.
  35449. */
  35450. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35451. var activeCamera = this.getScene().activeCamera;
  35452. this._shadowAngleScale = this._shadowAngleScale || 1;
  35453. var angle = this._shadowAngleScale * this._angle;
  35454. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35455. };
  35456. SpotLight.prototype._buildUniformLayout = function () {
  35457. this._uniformBuffer.addUniform("vLightData", 4);
  35458. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35459. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35460. this._uniformBuffer.addUniform("vLightDirection", 3);
  35461. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35462. this._uniformBuffer.addUniform("depthValues", 2);
  35463. this._uniformBuffer.create();
  35464. };
  35465. /**
  35466. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  35467. * Return the SpotLight.
  35468. */
  35469. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  35470. var normalizeDirection;
  35471. if (this.computeTransformedInformation()) {
  35472. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  35473. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  35474. }
  35475. else {
  35476. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  35477. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35478. }
  35479. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  35480. return this;
  35481. };
  35482. return SpotLight;
  35483. }(BABYLON.ShadowLight));
  35484. __decorate([
  35485. BABYLON.serialize()
  35486. ], SpotLight.prototype, "angle", null);
  35487. __decorate([
  35488. BABYLON.serialize()
  35489. /**
  35490. * Allows scaling the angle of the light for shadow generation only.
  35491. */
  35492. ], SpotLight.prototype, "shadowAngleScale", null);
  35493. __decorate([
  35494. BABYLON.serialize()
  35495. ], SpotLight.prototype, "exponent", void 0);
  35496. BABYLON.SpotLight = SpotLight;
  35497. })(BABYLON || (BABYLON = {}));
  35498. //# sourceMappingURL=babylon.spotLight.js.map
  35499. var BABYLON;
  35500. (function (BABYLON) {
  35501. var AnimationRange = (function () {
  35502. function AnimationRange(name, from, to) {
  35503. this.name = name;
  35504. this.from = from;
  35505. this.to = to;
  35506. }
  35507. AnimationRange.prototype.clone = function () {
  35508. return new AnimationRange(this.name, this.from, this.to);
  35509. };
  35510. return AnimationRange;
  35511. }());
  35512. BABYLON.AnimationRange = AnimationRange;
  35513. /**
  35514. * Composed of a frame, and an action function
  35515. */
  35516. var AnimationEvent = (function () {
  35517. function AnimationEvent(frame, action, onlyOnce) {
  35518. this.frame = frame;
  35519. this.action = action;
  35520. this.onlyOnce = onlyOnce;
  35521. this.isDone = false;
  35522. }
  35523. return AnimationEvent;
  35524. }());
  35525. BABYLON.AnimationEvent = AnimationEvent;
  35526. var PathCursor = (function () {
  35527. function PathCursor(path) {
  35528. this.path = path;
  35529. this._onchange = new Array();
  35530. this.value = 0;
  35531. this.animations = new Array();
  35532. }
  35533. PathCursor.prototype.getPoint = function () {
  35534. var point = this.path.getPointAtLengthPosition(this.value);
  35535. return new BABYLON.Vector3(point.x, 0, point.y);
  35536. };
  35537. PathCursor.prototype.moveAhead = function (step) {
  35538. if (step === void 0) { step = 0.002; }
  35539. this.move(step);
  35540. return this;
  35541. };
  35542. PathCursor.prototype.moveBack = function (step) {
  35543. if (step === void 0) { step = 0.002; }
  35544. this.move(-step);
  35545. return this;
  35546. };
  35547. PathCursor.prototype.move = function (step) {
  35548. if (Math.abs(step) > 1) {
  35549. throw "step size should be less than 1.";
  35550. }
  35551. this.value += step;
  35552. this.ensureLimits();
  35553. this.raiseOnChange();
  35554. return this;
  35555. };
  35556. PathCursor.prototype.ensureLimits = function () {
  35557. while (this.value > 1) {
  35558. this.value -= 1;
  35559. }
  35560. while (this.value < 0) {
  35561. this.value += 1;
  35562. }
  35563. return this;
  35564. };
  35565. // used by animation engine
  35566. PathCursor.prototype.markAsDirty = function (propertyName) {
  35567. this.ensureLimits();
  35568. this.raiseOnChange();
  35569. return this;
  35570. };
  35571. PathCursor.prototype.raiseOnChange = function () {
  35572. var _this = this;
  35573. this._onchange.forEach(function (f) { return f(_this); });
  35574. return this;
  35575. };
  35576. PathCursor.prototype.onchange = function (f) {
  35577. this._onchange.push(f);
  35578. return this;
  35579. };
  35580. return PathCursor;
  35581. }());
  35582. BABYLON.PathCursor = PathCursor;
  35583. var Animation = (function () {
  35584. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  35585. this.name = name;
  35586. this.targetProperty = targetProperty;
  35587. this.framePerSecond = framePerSecond;
  35588. this.dataType = dataType;
  35589. this.loopMode = loopMode;
  35590. this.enableBlending = enableBlending;
  35591. this._offsetsCache = {};
  35592. this._highLimitsCache = {};
  35593. this._stopped = false;
  35594. this._blendingFactor = 0;
  35595. // The set of event that will be linked to this animation
  35596. this._events = new Array();
  35597. this.allowMatricesInterpolation = false;
  35598. this.blendingSpeed = 0.01;
  35599. this._ranges = {};
  35600. this.targetPropertyPath = targetProperty.split(".");
  35601. this.dataType = dataType;
  35602. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  35603. }
  35604. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  35605. var dataType = undefined;
  35606. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  35607. dataType = Animation.ANIMATIONTYPE_FLOAT;
  35608. }
  35609. else if (from instanceof BABYLON.Quaternion) {
  35610. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  35611. }
  35612. else if (from instanceof BABYLON.Vector3) {
  35613. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  35614. }
  35615. else if (from instanceof BABYLON.Vector2) {
  35616. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  35617. }
  35618. else if (from instanceof BABYLON.Color3) {
  35619. dataType = Animation.ANIMATIONTYPE_COLOR3;
  35620. }
  35621. else if (from instanceof BABYLON.Size) {
  35622. dataType = Animation.ANIMATIONTYPE_SIZE;
  35623. }
  35624. if (dataType == undefined) {
  35625. return null;
  35626. }
  35627. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  35628. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  35629. animation.setKeys(keys);
  35630. if (easingFunction !== undefined) {
  35631. animation.setEasingFunction(easingFunction);
  35632. }
  35633. return animation;
  35634. };
  35635. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  35636. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  35637. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  35638. };
  35639. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  35640. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  35641. node.animations.push(animation);
  35642. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  35643. };
  35644. // Methods
  35645. /**
  35646. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  35647. */
  35648. Animation.prototype.toString = function (fullDetails) {
  35649. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  35650. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  35651. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  35652. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  35653. if (fullDetails) {
  35654. ret += ", Ranges: {";
  35655. var first = true;
  35656. for (var name in this._ranges) {
  35657. if (first) {
  35658. ret += ", ";
  35659. first = false;
  35660. }
  35661. ret += name;
  35662. }
  35663. ret += "}";
  35664. }
  35665. return ret;
  35666. };
  35667. /**
  35668. * Add an event to this animation.
  35669. */
  35670. Animation.prototype.addEvent = function (event) {
  35671. this._events.push(event);
  35672. };
  35673. /**
  35674. * Remove all events found at the given frame
  35675. * @param frame
  35676. */
  35677. Animation.prototype.removeEvents = function (frame) {
  35678. for (var index = 0; index < this._events.length; index++) {
  35679. if (this._events[index].frame === frame) {
  35680. this._events.splice(index, 1);
  35681. index--;
  35682. }
  35683. }
  35684. };
  35685. Animation.prototype.createRange = function (name, from, to) {
  35686. // check name not already in use; could happen for bones after serialized
  35687. if (!this._ranges[name]) {
  35688. this._ranges[name] = new AnimationRange(name, from, to);
  35689. }
  35690. };
  35691. Animation.prototype.deleteRange = function (name, deleteFrames) {
  35692. if (deleteFrames === void 0) { deleteFrames = true; }
  35693. if (this._ranges[name]) {
  35694. if (deleteFrames) {
  35695. var from = this._ranges[name].from;
  35696. var to = this._ranges[name].to;
  35697. // this loop MUST go high to low for multiple splices to work
  35698. for (var key = this._keys.length - 1; key >= 0; key--) {
  35699. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  35700. this._keys.splice(key, 1);
  35701. }
  35702. }
  35703. }
  35704. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  35705. }
  35706. };
  35707. Animation.prototype.getRange = function (name) {
  35708. return this._ranges[name];
  35709. };
  35710. Animation.prototype.reset = function () {
  35711. this._offsetsCache = {};
  35712. this._highLimitsCache = {};
  35713. this.currentFrame = 0;
  35714. this._blendingFactor = 0;
  35715. this._originalBlendValue = null;
  35716. };
  35717. Animation.prototype.isStopped = function () {
  35718. return this._stopped;
  35719. };
  35720. Animation.prototype.getKeys = function () {
  35721. return this._keys;
  35722. };
  35723. Animation.prototype.getHighestFrame = function () {
  35724. var ret = 0;
  35725. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  35726. if (ret < this._keys[key].frame) {
  35727. ret = this._keys[key].frame;
  35728. }
  35729. }
  35730. return ret;
  35731. };
  35732. Animation.prototype.getEasingFunction = function () {
  35733. return this._easingFunction;
  35734. };
  35735. Animation.prototype.setEasingFunction = function (easingFunction) {
  35736. this._easingFunction = easingFunction;
  35737. };
  35738. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  35739. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  35740. };
  35741. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35742. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35743. };
  35744. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  35745. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  35746. };
  35747. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35748. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  35749. };
  35750. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  35751. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  35752. };
  35753. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35754. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35755. };
  35756. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  35757. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  35758. };
  35759. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  35760. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  35761. };
  35762. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  35763. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  35764. };
  35765. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  35766. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  35767. };
  35768. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  35769. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  35770. };
  35771. Animation.prototype.clone = function () {
  35772. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  35773. clone.enableBlending = this.enableBlending;
  35774. clone.blendingSpeed = this.blendingSpeed;
  35775. if (this._keys) {
  35776. clone.setKeys(this._keys);
  35777. }
  35778. if (this._ranges) {
  35779. clone._ranges = {};
  35780. for (var name in this._ranges) {
  35781. clone._ranges[name] = this._ranges[name].clone();
  35782. }
  35783. }
  35784. return clone;
  35785. };
  35786. Animation.prototype.setKeys = function (values) {
  35787. this._keys = values.slice(0);
  35788. this._offsetsCache = {};
  35789. this._highLimitsCache = {};
  35790. };
  35791. Animation.prototype._getKeyValue = function (value) {
  35792. if (typeof value === "function") {
  35793. return value();
  35794. }
  35795. return value;
  35796. };
  35797. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  35798. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  35799. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  35800. }
  35801. this.currentFrame = currentFrame;
  35802. // Try to get a hash to find the right key
  35803. 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));
  35804. if (this._keys[startKeyIndex].frame >= currentFrame) {
  35805. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  35806. startKeyIndex--;
  35807. }
  35808. }
  35809. for (var key = startKeyIndex; key < this._keys.length; key++) {
  35810. var endKey = this._keys[key + 1];
  35811. if (endKey.frame >= currentFrame) {
  35812. var startKey = this._keys[key];
  35813. var startValue = this._getKeyValue(startKey.value);
  35814. var endValue = this._getKeyValue(endKey.value);
  35815. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  35816. var frameDelta = endKey.frame - startKey.frame;
  35817. // gradient : percent of currentFrame between the frame inf and the frame sup
  35818. var gradient = (currentFrame - startKey.frame) / frameDelta;
  35819. // check for easingFunction and correction of gradient
  35820. if (this._easingFunction != null) {
  35821. gradient = this._easingFunction.ease(gradient);
  35822. }
  35823. switch (this.dataType) {
  35824. // Float
  35825. case Animation.ANIMATIONTYPE_FLOAT:
  35826. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  35827. switch (loopMode) {
  35828. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35829. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35830. return floatValue;
  35831. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35832. return offsetValue * repeatCount + floatValue;
  35833. }
  35834. break;
  35835. // Quaternion
  35836. case Animation.ANIMATIONTYPE_QUATERNION:
  35837. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  35838. switch (loopMode) {
  35839. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35840. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35841. return quatValue;
  35842. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35843. return quatValue.add(offsetValue.scale(repeatCount));
  35844. }
  35845. return quatValue;
  35846. // Vector3
  35847. case Animation.ANIMATIONTYPE_VECTOR3:
  35848. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  35849. switch (loopMode) {
  35850. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35851. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35852. return vec3Value;
  35853. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35854. return vec3Value.add(offsetValue.scale(repeatCount));
  35855. }
  35856. // Vector2
  35857. case Animation.ANIMATIONTYPE_VECTOR2:
  35858. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  35859. switch (loopMode) {
  35860. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35861. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35862. return vec2Value;
  35863. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35864. return vec2Value.add(offsetValue.scale(repeatCount));
  35865. }
  35866. // Size
  35867. case Animation.ANIMATIONTYPE_SIZE:
  35868. switch (loopMode) {
  35869. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35870. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35871. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  35872. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35873. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  35874. }
  35875. // Color3
  35876. case Animation.ANIMATIONTYPE_COLOR3:
  35877. switch (loopMode) {
  35878. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35879. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35880. return this.color3InterpolateFunction(startValue, endValue, gradient);
  35881. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35882. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  35883. }
  35884. // Matrix
  35885. case Animation.ANIMATIONTYPE_MATRIX:
  35886. switch (loopMode) {
  35887. case Animation.ANIMATIONLOOPMODE_CYCLE:
  35888. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  35889. if (this.allowMatricesInterpolation) {
  35890. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  35891. }
  35892. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  35893. return startValue;
  35894. }
  35895. default:
  35896. break;
  35897. }
  35898. break;
  35899. }
  35900. }
  35901. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  35902. };
  35903. Animation.prototype.setValue = function (currentValue, blend) {
  35904. if (blend === void 0) { blend = false; }
  35905. // Set value
  35906. var path;
  35907. var destination;
  35908. if (this.targetPropertyPath.length > 1) {
  35909. var property = this._target[this.targetPropertyPath[0]];
  35910. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  35911. property = property[this.targetPropertyPath[index]];
  35912. }
  35913. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  35914. destination = property;
  35915. }
  35916. else {
  35917. path = this.targetPropertyPath[0];
  35918. destination = this._target;
  35919. }
  35920. // Blending
  35921. if (this.enableBlending && this._blendingFactor <= 1.0) {
  35922. if (!this._originalBlendValue) {
  35923. if (destination[path].clone) {
  35924. this._originalBlendValue = destination[path].clone();
  35925. }
  35926. else {
  35927. this._originalBlendValue = destination[path];
  35928. }
  35929. }
  35930. if (this._originalBlendValue.prototype) {
  35931. if (this._originalBlendValue.prototype.Lerp) {
  35932. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  35933. }
  35934. else {
  35935. destination[path] = currentValue;
  35936. }
  35937. }
  35938. else if (this._originalBlendValue.m) {
  35939. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  35940. }
  35941. else {
  35942. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  35943. }
  35944. this._blendingFactor += this.blendingSpeed;
  35945. }
  35946. else {
  35947. destination[path] = currentValue;
  35948. }
  35949. if (this._target.markAsDirty) {
  35950. this._target.markAsDirty(this.targetProperty);
  35951. }
  35952. };
  35953. Animation.prototype.goToFrame = function (frame) {
  35954. if (frame < this._keys[0].frame) {
  35955. frame = this._keys[0].frame;
  35956. }
  35957. else if (frame > this._keys[this._keys.length - 1].frame) {
  35958. frame = this._keys[this._keys.length - 1].frame;
  35959. }
  35960. var currentValue = this._interpolate(frame, 0, this.loopMode);
  35961. this.setValue(currentValue);
  35962. };
  35963. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  35964. if (blend === void 0) { blend = false; }
  35965. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  35966. this._stopped = true;
  35967. return false;
  35968. }
  35969. var returnValue = true;
  35970. // Adding a start key at frame 0 if missing
  35971. if (this._keys[0].frame !== 0) {
  35972. var newKey = { frame: 0, value: this._keys[0].value };
  35973. this._keys.splice(0, 0, newKey);
  35974. }
  35975. // Check limits
  35976. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  35977. from = this._keys[0].frame;
  35978. }
  35979. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  35980. to = this._keys[this._keys.length - 1].frame;
  35981. }
  35982. //to and from cannot be the same key
  35983. if (from === to) {
  35984. from++;
  35985. }
  35986. // Compute ratio
  35987. var range = to - from;
  35988. var offsetValue;
  35989. // ratio represents the frame delta between from and to
  35990. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  35991. var highLimitValue = 0;
  35992. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  35993. returnValue = false;
  35994. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  35995. }
  35996. else {
  35997. // Get max value if required
  35998. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  35999. var keyOffset = to.toString() + from.toString();
  36000. if (!this._offsetsCache[keyOffset]) {
  36001. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36002. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36003. switch (this.dataType) {
  36004. // Float
  36005. case Animation.ANIMATIONTYPE_FLOAT:
  36006. this._offsetsCache[keyOffset] = toValue - fromValue;
  36007. break;
  36008. // Quaternion
  36009. case Animation.ANIMATIONTYPE_QUATERNION:
  36010. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36011. break;
  36012. // Vector3
  36013. case Animation.ANIMATIONTYPE_VECTOR3:
  36014. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36015. // Vector2
  36016. case Animation.ANIMATIONTYPE_VECTOR2:
  36017. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36018. // Size
  36019. case Animation.ANIMATIONTYPE_SIZE:
  36020. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36021. // Color3
  36022. case Animation.ANIMATIONTYPE_COLOR3:
  36023. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36024. default:
  36025. break;
  36026. }
  36027. this._highLimitsCache[keyOffset] = toValue;
  36028. }
  36029. highLimitValue = this._highLimitsCache[keyOffset];
  36030. offsetValue = this._offsetsCache[keyOffset];
  36031. }
  36032. }
  36033. if (offsetValue === undefined) {
  36034. switch (this.dataType) {
  36035. // Float
  36036. case Animation.ANIMATIONTYPE_FLOAT:
  36037. offsetValue = 0;
  36038. break;
  36039. // Quaternion
  36040. case Animation.ANIMATIONTYPE_QUATERNION:
  36041. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  36042. break;
  36043. // Vector3
  36044. case Animation.ANIMATIONTYPE_VECTOR3:
  36045. offsetValue = BABYLON.Vector3.Zero();
  36046. break;
  36047. // Vector2
  36048. case Animation.ANIMATIONTYPE_VECTOR2:
  36049. offsetValue = BABYLON.Vector2.Zero();
  36050. break;
  36051. // Size
  36052. case Animation.ANIMATIONTYPE_SIZE:
  36053. offsetValue = BABYLON.Size.Zero();
  36054. break;
  36055. // Color3
  36056. case Animation.ANIMATIONTYPE_COLOR3:
  36057. offsetValue = BABYLON.Color3.Black();
  36058. }
  36059. }
  36060. // Compute value
  36061. var repeatCount = (ratio / range) >> 0;
  36062. var currentFrame = returnValue ? from + ratio % range : to;
  36063. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  36064. // Set value
  36065. this.setValue(currentValue);
  36066. // Check events
  36067. for (var index = 0; index < this._events.length; index++) {
  36068. // Make sure current frame has passed event frame and that event frame is within the current range
  36069. // Also, handle both forward and reverse animations
  36070. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  36071. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  36072. var event = this._events[index];
  36073. if (!event.isDone) {
  36074. // If event should be done only once, remove it.
  36075. if (event.onlyOnce) {
  36076. this._events.splice(index, 1);
  36077. index--;
  36078. }
  36079. event.isDone = true;
  36080. event.action();
  36081. } // Don't do anything if the event has already be done.
  36082. }
  36083. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  36084. // reset event, the animation is looping
  36085. this._events[index].isDone = false;
  36086. }
  36087. }
  36088. if (!returnValue) {
  36089. this._stopped = true;
  36090. }
  36091. return returnValue;
  36092. };
  36093. Animation.prototype.serialize = function () {
  36094. var serializationObject = {};
  36095. serializationObject.name = this.name;
  36096. serializationObject.property = this.targetProperty;
  36097. serializationObject.framePerSecond = this.framePerSecond;
  36098. serializationObject.dataType = this.dataType;
  36099. serializationObject.loopBehavior = this.loopMode;
  36100. serializationObject.enableBlending = this.enableBlending;
  36101. serializationObject.blendingSpeed = this.blendingSpeed;
  36102. var dataType = this.dataType;
  36103. serializationObject.keys = [];
  36104. var keys = this.getKeys();
  36105. for (var index = 0; index < keys.length; index++) {
  36106. var animationKey = keys[index];
  36107. var key = {};
  36108. key.frame = animationKey.frame;
  36109. switch (dataType) {
  36110. case Animation.ANIMATIONTYPE_FLOAT:
  36111. key.values = [animationKey.value];
  36112. break;
  36113. case Animation.ANIMATIONTYPE_QUATERNION:
  36114. case Animation.ANIMATIONTYPE_MATRIX:
  36115. case Animation.ANIMATIONTYPE_VECTOR3:
  36116. case Animation.ANIMATIONTYPE_COLOR3:
  36117. key.values = animationKey.value.asArray();
  36118. break;
  36119. }
  36120. serializationObject.keys.push(key);
  36121. }
  36122. serializationObject.ranges = [];
  36123. for (var name in this._ranges) {
  36124. var range = {};
  36125. range.name = name;
  36126. range.from = this._ranges[name].from;
  36127. range.to = this._ranges[name].to;
  36128. serializationObject.ranges.push(range);
  36129. }
  36130. return serializationObject;
  36131. };
  36132. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  36133. get: function () {
  36134. return Animation._ANIMATIONTYPE_FLOAT;
  36135. },
  36136. enumerable: true,
  36137. configurable: true
  36138. });
  36139. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  36140. get: function () {
  36141. return Animation._ANIMATIONTYPE_VECTOR3;
  36142. },
  36143. enumerable: true,
  36144. configurable: true
  36145. });
  36146. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  36147. get: function () {
  36148. return Animation._ANIMATIONTYPE_VECTOR2;
  36149. },
  36150. enumerable: true,
  36151. configurable: true
  36152. });
  36153. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  36154. get: function () {
  36155. return Animation._ANIMATIONTYPE_SIZE;
  36156. },
  36157. enumerable: true,
  36158. configurable: true
  36159. });
  36160. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  36161. get: function () {
  36162. return Animation._ANIMATIONTYPE_QUATERNION;
  36163. },
  36164. enumerable: true,
  36165. configurable: true
  36166. });
  36167. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  36168. get: function () {
  36169. return Animation._ANIMATIONTYPE_MATRIX;
  36170. },
  36171. enumerable: true,
  36172. configurable: true
  36173. });
  36174. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  36175. get: function () {
  36176. return Animation._ANIMATIONTYPE_COLOR3;
  36177. },
  36178. enumerable: true,
  36179. configurable: true
  36180. });
  36181. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  36182. get: function () {
  36183. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  36184. },
  36185. enumerable: true,
  36186. configurable: true
  36187. });
  36188. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  36189. get: function () {
  36190. return Animation._ANIMATIONLOOPMODE_CYCLE;
  36191. },
  36192. enumerable: true,
  36193. configurable: true
  36194. });
  36195. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  36196. get: function () {
  36197. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. Animation.Parse = function (parsedAnimation) {
  36203. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  36204. var dataType = parsedAnimation.dataType;
  36205. var keys = [];
  36206. var data;
  36207. var index;
  36208. if (parsedAnimation.enableBlending) {
  36209. animation.enableBlending = parsedAnimation.enableBlending;
  36210. }
  36211. if (parsedAnimation.blendingSpeed) {
  36212. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  36213. }
  36214. for (index = 0; index < parsedAnimation.keys.length; index++) {
  36215. var key = parsedAnimation.keys[index];
  36216. switch (dataType) {
  36217. case Animation.ANIMATIONTYPE_FLOAT:
  36218. data = key.values[0];
  36219. break;
  36220. case Animation.ANIMATIONTYPE_QUATERNION:
  36221. data = BABYLON.Quaternion.FromArray(key.values);
  36222. break;
  36223. case Animation.ANIMATIONTYPE_MATRIX:
  36224. data = BABYLON.Matrix.FromArray(key.values);
  36225. break;
  36226. case Animation.ANIMATIONTYPE_COLOR3:
  36227. data = BABYLON.Color3.FromArray(key.values);
  36228. break;
  36229. case Animation.ANIMATIONTYPE_VECTOR3:
  36230. default:
  36231. data = BABYLON.Vector3.FromArray(key.values);
  36232. break;
  36233. }
  36234. keys.push({
  36235. frame: key.frame,
  36236. value: data
  36237. });
  36238. }
  36239. animation.setKeys(keys);
  36240. if (parsedAnimation.ranges) {
  36241. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  36242. data = parsedAnimation.ranges[index];
  36243. animation.createRange(data.name, data.from, data.to);
  36244. }
  36245. }
  36246. return animation;
  36247. };
  36248. Animation.AppendSerializedAnimations = function (source, destination) {
  36249. if (source.animations) {
  36250. destination.animations = [];
  36251. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  36252. var animation = source.animations[animationIndex];
  36253. destination.animations.push(animation.serialize());
  36254. }
  36255. }
  36256. };
  36257. return Animation;
  36258. }());
  36259. // Statics
  36260. Animation._ANIMATIONTYPE_FLOAT = 0;
  36261. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  36262. Animation._ANIMATIONTYPE_QUATERNION = 2;
  36263. Animation._ANIMATIONTYPE_MATRIX = 3;
  36264. Animation._ANIMATIONTYPE_COLOR3 = 4;
  36265. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  36266. Animation._ANIMATIONTYPE_SIZE = 6;
  36267. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  36268. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  36269. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  36270. BABYLON.Animation = Animation;
  36271. })(BABYLON || (BABYLON = {}));
  36272. //# sourceMappingURL=babylon.animation.js.map
  36273. var BABYLON;
  36274. (function (BABYLON) {
  36275. var Animatable = (function () {
  36276. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  36277. if (fromFrame === void 0) { fromFrame = 0; }
  36278. if (toFrame === void 0) { toFrame = 100; }
  36279. if (loopAnimation === void 0) { loopAnimation = false; }
  36280. if (speedRatio === void 0) { speedRatio = 1.0; }
  36281. this.target = target;
  36282. this.fromFrame = fromFrame;
  36283. this.toFrame = toFrame;
  36284. this.loopAnimation = loopAnimation;
  36285. this.speedRatio = speedRatio;
  36286. this.onAnimationEnd = onAnimationEnd;
  36287. this._localDelayOffset = null;
  36288. this._pausedDelay = null;
  36289. this._animations = new Array();
  36290. this._paused = false;
  36291. this.animationStarted = false;
  36292. if (animations) {
  36293. this.appendAnimations(target, animations);
  36294. }
  36295. this._scene = scene;
  36296. scene._activeAnimatables.push(this);
  36297. }
  36298. // Methods
  36299. Animatable.prototype.getAnimations = function () {
  36300. return this._animations;
  36301. };
  36302. Animatable.prototype.appendAnimations = function (target, animations) {
  36303. for (var index = 0; index < animations.length; index++) {
  36304. var animation = animations[index];
  36305. animation._target = target;
  36306. this._animations.push(animation);
  36307. }
  36308. };
  36309. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  36310. var animations = this._animations;
  36311. for (var index = 0; index < animations.length; index++) {
  36312. if (animations[index].targetProperty === property) {
  36313. return animations[index];
  36314. }
  36315. }
  36316. return null;
  36317. };
  36318. Animatable.prototype.reset = function () {
  36319. var animations = this._animations;
  36320. for (var index = 0; index < animations.length; index++) {
  36321. animations[index].reset();
  36322. }
  36323. this._localDelayOffset = null;
  36324. this._pausedDelay = null;
  36325. };
  36326. Animatable.prototype.enableBlending = function (blendingSpeed) {
  36327. var animations = this._animations;
  36328. for (var index = 0; index < animations.length; index++) {
  36329. animations[index].enableBlending = true;
  36330. animations[index].blendingSpeed = blendingSpeed;
  36331. }
  36332. };
  36333. Animatable.prototype.disableBlending = function () {
  36334. var animations = this._animations;
  36335. for (var index = 0; index < animations.length; index++) {
  36336. animations[index].enableBlending = false;
  36337. }
  36338. };
  36339. Animatable.prototype.goToFrame = function (frame) {
  36340. var animations = this._animations;
  36341. if (animations[0]) {
  36342. var fps = animations[0].framePerSecond;
  36343. var currentFrame = animations[0].currentFrame;
  36344. var adjustTime = frame - currentFrame;
  36345. var delay = adjustTime * 1000 / fps;
  36346. this._localDelayOffset -= delay;
  36347. }
  36348. for (var index = 0; index < animations.length; index++) {
  36349. animations[index].goToFrame(frame);
  36350. }
  36351. };
  36352. Animatable.prototype.pause = function () {
  36353. if (this._paused) {
  36354. return;
  36355. }
  36356. this._paused = true;
  36357. };
  36358. Animatable.prototype.restart = function () {
  36359. this._paused = false;
  36360. };
  36361. Animatable.prototype.stop = function (animationName) {
  36362. if (animationName) {
  36363. var idx = this._scene._activeAnimatables.indexOf(this);
  36364. if (idx > -1) {
  36365. var animations = this._animations;
  36366. for (var index = animations.length - 1; index >= 0; index--) {
  36367. if (typeof animationName === "string" && animations[index].name != animationName) {
  36368. continue;
  36369. }
  36370. animations[index].reset();
  36371. animations.splice(index, 1);
  36372. }
  36373. if (animations.length == 0) {
  36374. this._scene._activeAnimatables.splice(idx, 1);
  36375. if (this.onAnimationEnd) {
  36376. this.onAnimationEnd();
  36377. }
  36378. }
  36379. }
  36380. }
  36381. else {
  36382. var index = this._scene._activeAnimatables.indexOf(this);
  36383. if (index > -1) {
  36384. this._scene._activeAnimatables.splice(index, 1);
  36385. var animations = this._animations;
  36386. for (var index = 0; index < animations.length; index++) {
  36387. animations[index].reset();
  36388. }
  36389. if (this.onAnimationEnd) {
  36390. this.onAnimationEnd();
  36391. }
  36392. }
  36393. }
  36394. };
  36395. Animatable.prototype._animate = function (delay) {
  36396. if (this._paused) {
  36397. this.animationStarted = false;
  36398. if (this._pausedDelay === null) {
  36399. this._pausedDelay = delay;
  36400. }
  36401. return true;
  36402. }
  36403. if (this._localDelayOffset === null) {
  36404. this._localDelayOffset = delay;
  36405. }
  36406. else if (this._pausedDelay !== null) {
  36407. this._localDelayOffset += delay - this._pausedDelay;
  36408. this._pausedDelay = null;
  36409. }
  36410. // Animating
  36411. var running = false;
  36412. var animations = this._animations;
  36413. var index;
  36414. for (index = 0; index < animations.length; index++) {
  36415. var animation = animations[index];
  36416. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  36417. running = running || isRunning;
  36418. }
  36419. this.animationStarted = running;
  36420. if (!running) {
  36421. // Remove from active animatables
  36422. index = this._scene._activeAnimatables.indexOf(this);
  36423. this._scene._activeAnimatables.splice(index, 1);
  36424. }
  36425. if (!running && this.onAnimationEnd) {
  36426. this.onAnimationEnd();
  36427. this.onAnimationEnd = null;
  36428. }
  36429. return running;
  36430. };
  36431. return Animatable;
  36432. }());
  36433. BABYLON.Animatable = Animatable;
  36434. })(BABYLON || (BABYLON = {}));
  36435. //# sourceMappingURL=babylon.animatable.js.map
  36436. var BABYLON;
  36437. (function (BABYLON) {
  36438. var EasingFunction = (function () {
  36439. function EasingFunction() {
  36440. // Properties
  36441. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  36442. }
  36443. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  36444. get: function () {
  36445. return EasingFunction._EASINGMODE_EASEIN;
  36446. },
  36447. enumerable: true,
  36448. configurable: true
  36449. });
  36450. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  36451. get: function () {
  36452. return EasingFunction._EASINGMODE_EASEOUT;
  36453. },
  36454. enumerable: true,
  36455. configurable: true
  36456. });
  36457. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  36458. get: function () {
  36459. return EasingFunction._EASINGMODE_EASEINOUT;
  36460. },
  36461. enumerable: true,
  36462. configurable: true
  36463. });
  36464. EasingFunction.prototype.setEasingMode = function (easingMode) {
  36465. var n = Math.min(Math.max(easingMode, 0), 2);
  36466. this._easingMode = n;
  36467. };
  36468. EasingFunction.prototype.getEasingMode = function () {
  36469. return this._easingMode;
  36470. };
  36471. EasingFunction.prototype.easeInCore = function (gradient) {
  36472. throw new Error('You must implement this method');
  36473. };
  36474. EasingFunction.prototype.ease = function (gradient) {
  36475. switch (this._easingMode) {
  36476. case EasingFunction.EASINGMODE_EASEIN:
  36477. return this.easeInCore(gradient);
  36478. case EasingFunction.EASINGMODE_EASEOUT:
  36479. return (1 - this.easeInCore(1 - gradient));
  36480. }
  36481. if (gradient >= 0.5) {
  36482. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  36483. }
  36484. return (this.easeInCore(gradient * 2) * 0.5);
  36485. };
  36486. return EasingFunction;
  36487. }());
  36488. //Statics
  36489. EasingFunction._EASINGMODE_EASEIN = 0;
  36490. EasingFunction._EASINGMODE_EASEOUT = 1;
  36491. EasingFunction._EASINGMODE_EASEINOUT = 2;
  36492. BABYLON.EasingFunction = EasingFunction;
  36493. var CircleEase = (function (_super) {
  36494. __extends(CircleEase, _super);
  36495. function CircleEase() {
  36496. return _super !== null && _super.apply(this, arguments) || this;
  36497. }
  36498. CircleEase.prototype.easeInCore = function (gradient) {
  36499. gradient = Math.max(0, Math.min(1, gradient));
  36500. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  36501. };
  36502. return CircleEase;
  36503. }(EasingFunction));
  36504. BABYLON.CircleEase = CircleEase;
  36505. var BackEase = (function (_super) {
  36506. __extends(BackEase, _super);
  36507. function BackEase(amplitude) {
  36508. if (amplitude === void 0) { amplitude = 1; }
  36509. var _this = _super.call(this) || this;
  36510. _this.amplitude = amplitude;
  36511. return _this;
  36512. }
  36513. BackEase.prototype.easeInCore = function (gradient) {
  36514. var num = Math.max(0, this.amplitude);
  36515. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  36516. };
  36517. return BackEase;
  36518. }(EasingFunction));
  36519. BABYLON.BackEase = BackEase;
  36520. var BounceEase = (function (_super) {
  36521. __extends(BounceEase, _super);
  36522. function BounceEase(bounces, bounciness) {
  36523. if (bounces === void 0) { bounces = 3; }
  36524. if (bounciness === void 0) { bounciness = 2; }
  36525. var _this = _super.call(this) || this;
  36526. _this.bounces = bounces;
  36527. _this.bounciness = bounciness;
  36528. return _this;
  36529. }
  36530. BounceEase.prototype.easeInCore = function (gradient) {
  36531. var y = Math.max(0.0, this.bounces);
  36532. var bounciness = this.bounciness;
  36533. if (bounciness <= 1.0) {
  36534. bounciness = 1.001;
  36535. }
  36536. var num9 = Math.pow(bounciness, y);
  36537. var num5 = 1.0 - bounciness;
  36538. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  36539. var num15 = gradient * num4;
  36540. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  36541. var num3 = Math.floor(num65);
  36542. var num13 = num3 + 1.0;
  36543. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  36544. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  36545. var num7 = (num8 + num12) * 0.5;
  36546. var num6 = gradient - num7;
  36547. var num2 = num7 - num8;
  36548. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  36549. };
  36550. return BounceEase;
  36551. }(EasingFunction));
  36552. BABYLON.BounceEase = BounceEase;
  36553. var CubicEase = (function (_super) {
  36554. __extends(CubicEase, _super);
  36555. function CubicEase() {
  36556. return _super !== null && _super.apply(this, arguments) || this;
  36557. }
  36558. CubicEase.prototype.easeInCore = function (gradient) {
  36559. return (gradient * gradient * gradient);
  36560. };
  36561. return CubicEase;
  36562. }(EasingFunction));
  36563. BABYLON.CubicEase = CubicEase;
  36564. var ElasticEase = (function (_super) {
  36565. __extends(ElasticEase, _super);
  36566. function ElasticEase(oscillations, springiness) {
  36567. if (oscillations === void 0) { oscillations = 3; }
  36568. if (springiness === void 0) { springiness = 3; }
  36569. var _this = _super.call(this) || this;
  36570. _this.oscillations = oscillations;
  36571. _this.springiness = springiness;
  36572. return _this;
  36573. }
  36574. ElasticEase.prototype.easeInCore = function (gradient) {
  36575. var num2;
  36576. var num3 = Math.max(0.0, this.oscillations);
  36577. var num = Math.max(0.0, this.springiness);
  36578. if (num == 0) {
  36579. num2 = gradient;
  36580. }
  36581. else {
  36582. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  36583. }
  36584. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  36585. };
  36586. return ElasticEase;
  36587. }(EasingFunction));
  36588. BABYLON.ElasticEase = ElasticEase;
  36589. var ExponentialEase = (function (_super) {
  36590. __extends(ExponentialEase, _super);
  36591. function ExponentialEase(exponent) {
  36592. if (exponent === void 0) { exponent = 2; }
  36593. var _this = _super.call(this) || this;
  36594. _this.exponent = exponent;
  36595. return _this;
  36596. }
  36597. ExponentialEase.prototype.easeInCore = function (gradient) {
  36598. if (this.exponent <= 0) {
  36599. return gradient;
  36600. }
  36601. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  36602. };
  36603. return ExponentialEase;
  36604. }(EasingFunction));
  36605. BABYLON.ExponentialEase = ExponentialEase;
  36606. var PowerEase = (function (_super) {
  36607. __extends(PowerEase, _super);
  36608. function PowerEase(power) {
  36609. if (power === void 0) { power = 2; }
  36610. var _this = _super.call(this) || this;
  36611. _this.power = power;
  36612. return _this;
  36613. }
  36614. PowerEase.prototype.easeInCore = function (gradient) {
  36615. var y = Math.max(0.0, this.power);
  36616. return Math.pow(gradient, y);
  36617. };
  36618. return PowerEase;
  36619. }(EasingFunction));
  36620. BABYLON.PowerEase = PowerEase;
  36621. var QuadraticEase = (function (_super) {
  36622. __extends(QuadraticEase, _super);
  36623. function QuadraticEase() {
  36624. return _super !== null && _super.apply(this, arguments) || this;
  36625. }
  36626. QuadraticEase.prototype.easeInCore = function (gradient) {
  36627. return (gradient * gradient);
  36628. };
  36629. return QuadraticEase;
  36630. }(EasingFunction));
  36631. BABYLON.QuadraticEase = QuadraticEase;
  36632. var QuarticEase = (function (_super) {
  36633. __extends(QuarticEase, _super);
  36634. function QuarticEase() {
  36635. return _super !== null && _super.apply(this, arguments) || this;
  36636. }
  36637. QuarticEase.prototype.easeInCore = function (gradient) {
  36638. return (gradient * gradient * gradient * gradient);
  36639. };
  36640. return QuarticEase;
  36641. }(EasingFunction));
  36642. BABYLON.QuarticEase = QuarticEase;
  36643. var QuinticEase = (function (_super) {
  36644. __extends(QuinticEase, _super);
  36645. function QuinticEase() {
  36646. return _super !== null && _super.apply(this, arguments) || this;
  36647. }
  36648. QuinticEase.prototype.easeInCore = function (gradient) {
  36649. return (gradient * gradient * gradient * gradient * gradient);
  36650. };
  36651. return QuinticEase;
  36652. }(EasingFunction));
  36653. BABYLON.QuinticEase = QuinticEase;
  36654. var SineEase = (function (_super) {
  36655. __extends(SineEase, _super);
  36656. function SineEase() {
  36657. return _super !== null && _super.apply(this, arguments) || this;
  36658. }
  36659. SineEase.prototype.easeInCore = function (gradient) {
  36660. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  36661. };
  36662. return SineEase;
  36663. }(EasingFunction));
  36664. BABYLON.SineEase = SineEase;
  36665. var BezierCurveEase = (function (_super) {
  36666. __extends(BezierCurveEase, _super);
  36667. function BezierCurveEase(x1, y1, x2, y2) {
  36668. if (x1 === void 0) { x1 = 0; }
  36669. if (y1 === void 0) { y1 = 0; }
  36670. if (x2 === void 0) { x2 = 1; }
  36671. if (y2 === void 0) { y2 = 1; }
  36672. var _this = _super.call(this) || this;
  36673. _this.x1 = x1;
  36674. _this.y1 = y1;
  36675. _this.x2 = x2;
  36676. _this.y2 = y2;
  36677. return _this;
  36678. }
  36679. BezierCurveEase.prototype.easeInCore = function (gradient) {
  36680. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  36681. };
  36682. return BezierCurveEase;
  36683. }(EasingFunction));
  36684. BABYLON.BezierCurveEase = BezierCurveEase;
  36685. })(BABYLON || (BABYLON = {}));
  36686. //# sourceMappingURL=babylon.easing.js.map
  36687. var BABYLON;
  36688. (function (BABYLON) {
  36689. var Condition = (function () {
  36690. function Condition(actionManager) {
  36691. this._actionManager = actionManager;
  36692. }
  36693. Condition.prototype.isValid = function () {
  36694. return true;
  36695. };
  36696. Condition.prototype._getProperty = function (propertyPath) {
  36697. return this._actionManager._getProperty(propertyPath);
  36698. };
  36699. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  36700. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36701. };
  36702. Condition.prototype.serialize = function () {
  36703. };
  36704. Condition.prototype._serialize = function (serializedCondition) {
  36705. return {
  36706. type: 2,
  36707. children: [],
  36708. name: serializedCondition.name,
  36709. properties: serializedCondition.properties
  36710. };
  36711. };
  36712. return Condition;
  36713. }());
  36714. BABYLON.Condition = Condition;
  36715. var ValueCondition = (function (_super) {
  36716. __extends(ValueCondition, _super);
  36717. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  36718. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  36719. var _this = _super.call(this, actionManager) || this;
  36720. _this.propertyPath = propertyPath;
  36721. _this.value = value;
  36722. _this.operator = operator;
  36723. _this._target = target;
  36724. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  36725. _this._property = _this._getProperty(_this.propertyPath);
  36726. return _this;
  36727. }
  36728. Object.defineProperty(ValueCondition, "IsEqual", {
  36729. get: function () {
  36730. return ValueCondition._IsEqual;
  36731. },
  36732. enumerable: true,
  36733. configurable: true
  36734. });
  36735. Object.defineProperty(ValueCondition, "IsDifferent", {
  36736. get: function () {
  36737. return ValueCondition._IsDifferent;
  36738. },
  36739. enumerable: true,
  36740. configurable: true
  36741. });
  36742. Object.defineProperty(ValueCondition, "IsGreater", {
  36743. get: function () {
  36744. return ValueCondition._IsGreater;
  36745. },
  36746. enumerable: true,
  36747. configurable: true
  36748. });
  36749. Object.defineProperty(ValueCondition, "IsLesser", {
  36750. get: function () {
  36751. return ValueCondition._IsLesser;
  36752. },
  36753. enumerable: true,
  36754. configurable: true
  36755. });
  36756. // Methods
  36757. ValueCondition.prototype.isValid = function () {
  36758. switch (this.operator) {
  36759. case ValueCondition.IsGreater:
  36760. return this._effectiveTarget[this._property] > this.value;
  36761. case ValueCondition.IsLesser:
  36762. return this._effectiveTarget[this._property] < this.value;
  36763. case ValueCondition.IsEqual:
  36764. case ValueCondition.IsDifferent:
  36765. var check;
  36766. if (this.value.equals) {
  36767. check = this.value.equals(this._effectiveTarget[this._property]);
  36768. }
  36769. else {
  36770. check = this.value === this._effectiveTarget[this._property];
  36771. }
  36772. return this.operator === ValueCondition.IsEqual ? check : !check;
  36773. }
  36774. return false;
  36775. };
  36776. ValueCondition.prototype.serialize = function () {
  36777. return this._serialize({
  36778. name: "ValueCondition",
  36779. properties: [
  36780. BABYLON.Action._GetTargetProperty(this._target),
  36781. { name: "propertyPath", value: this.propertyPath },
  36782. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36783. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36784. ]
  36785. });
  36786. };
  36787. ValueCondition.GetOperatorName = function (operator) {
  36788. switch (operator) {
  36789. case ValueCondition._IsEqual: return "IsEqual";
  36790. case ValueCondition._IsDifferent: return "IsDifferent";
  36791. case ValueCondition._IsGreater: return "IsGreater";
  36792. case ValueCondition._IsLesser: return "IsLesser";
  36793. default: return "";
  36794. }
  36795. };
  36796. return ValueCondition;
  36797. }(Condition));
  36798. // Statics
  36799. ValueCondition._IsEqual = 0;
  36800. ValueCondition._IsDifferent = 1;
  36801. ValueCondition._IsGreater = 2;
  36802. ValueCondition._IsLesser = 3;
  36803. BABYLON.ValueCondition = ValueCondition;
  36804. var PredicateCondition = (function (_super) {
  36805. __extends(PredicateCondition, _super);
  36806. function PredicateCondition(actionManager, predicate) {
  36807. var _this = _super.call(this, actionManager) || this;
  36808. _this.predicate = predicate;
  36809. return _this;
  36810. }
  36811. PredicateCondition.prototype.isValid = function () {
  36812. return this.predicate();
  36813. };
  36814. return PredicateCondition;
  36815. }(Condition));
  36816. BABYLON.PredicateCondition = PredicateCondition;
  36817. var StateCondition = (function (_super) {
  36818. __extends(StateCondition, _super);
  36819. function StateCondition(actionManager, target, value) {
  36820. var _this = _super.call(this, actionManager) || this;
  36821. _this.value = value;
  36822. _this._target = target;
  36823. return _this;
  36824. }
  36825. // Methods
  36826. StateCondition.prototype.isValid = function () {
  36827. return this._target.state === this.value;
  36828. };
  36829. StateCondition.prototype.serialize = function () {
  36830. return this._serialize({
  36831. name: "StateCondition",
  36832. properties: [
  36833. BABYLON.Action._GetTargetProperty(this._target),
  36834. { name: "value", value: this.value }
  36835. ]
  36836. });
  36837. };
  36838. return StateCondition;
  36839. }(Condition));
  36840. BABYLON.StateCondition = StateCondition;
  36841. })(BABYLON || (BABYLON = {}));
  36842. //# sourceMappingURL=babylon.condition.js.map
  36843. var BABYLON;
  36844. (function (BABYLON) {
  36845. var Action = (function () {
  36846. function Action(triggerOptions, condition) {
  36847. this.triggerOptions = triggerOptions;
  36848. if (triggerOptions.parameter) {
  36849. this.trigger = triggerOptions.trigger;
  36850. this._triggerParameter = triggerOptions.parameter;
  36851. }
  36852. else {
  36853. this.trigger = triggerOptions;
  36854. }
  36855. this._nextActiveAction = this;
  36856. this._condition = condition;
  36857. }
  36858. // Methods
  36859. Action.prototype._prepare = function () {
  36860. };
  36861. Action.prototype.getTriggerParameter = function () {
  36862. return this._triggerParameter;
  36863. };
  36864. Action.prototype._executeCurrent = function (evt) {
  36865. if (this._nextActiveAction._condition) {
  36866. var condition = this._nextActiveAction._condition;
  36867. var currentRenderId = this._actionManager.getScene().getRenderId();
  36868. // We cache the current evaluation for the current frame
  36869. if (condition._evaluationId === currentRenderId) {
  36870. if (!condition._currentResult) {
  36871. return;
  36872. }
  36873. }
  36874. else {
  36875. condition._evaluationId = currentRenderId;
  36876. if (!condition.isValid()) {
  36877. condition._currentResult = false;
  36878. return;
  36879. }
  36880. condition._currentResult = true;
  36881. }
  36882. }
  36883. this._nextActiveAction.execute(evt);
  36884. this.skipToNextActiveAction();
  36885. };
  36886. Action.prototype.execute = function (evt) {
  36887. };
  36888. Action.prototype.skipToNextActiveAction = function () {
  36889. if (this._nextActiveAction._child) {
  36890. if (!this._nextActiveAction._child._actionManager) {
  36891. this._nextActiveAction._child._actionManager = this._actionManager;
  36892. }
  36893. this._nextActiveAction = this._nextActiveAction._child;
  36894. }
  36895. else {
  36896. this._nextActiveAction = this;
  36897. }
  36898. };
  36899. Action.prototype.then = function (action) {
  36900. this._child = action;
  36901. action._actionManager = this._actionManager;
  36902. action._prepare();
  36903. return action;
  36904. };
  36905. Action.prototype._getProperty = function (propertyPath) {
  36906. return this._actionManager._getProperty(propertyPath);
  36907. };
  36908. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36909. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36910. };
  36911. Action.prototype.serialize = function (parent) {
  36912. };
  36913. // Called by BABYLON.Action objects in serialize(...). Internal use
  36914. Action.prototype._serialize = function (serializedAction, parent) {
  36915. var serializationObject = {
  36916. type: 1,
  36917. children: [],
  36918. name: serializedAction.name,
  36919. properties: serializedAction.properties || []
  36920. };
  36921. // Serialize child
  36922. if (this._child) {
  36923. this._child.serialize(serializationObject);
  36924. }
  36925. // Check if "this" has a condition
  36926. if (this._condition) {
  36927. var serializedCondition = this._condition.serialize();
  36928. serializedCondition.children.push(serializationObject);
  36929. if (parent) {
  36930. parent.children.push(serializedCondition);
  36931. }
  36932. return serializedCondition;
  36933. }
  36934. if (parent) {
  36935. parent.children.push(serializationObject);
  36936. }
  36937. return serializationObject;
  36938. };
  36939. return Action;
  36940. }());
  36941. Action._SerializeValueAsString = function (value) {
  36942. if (typeof value === "number") {
  36943. return value.toString();
  36944. }
  36945. if (typeof value === "boolean") {
  36946. return value ? "true" : "false";
  36947. }
  36948. if (value instanceof BABYLON.Vector2) {
  36949. return value.x + ", " + value.y;
  36950. }
  36951. if (value instanceof BABYLON.Vector3) {
  36952. return value.x + ", " + value.y + ", " + value.z;
  36953. }
  36954. if (value instanceof BABYLON.Color3) {
  36955. return value.r + ", " + value.g + ", " + value.b;
  36956. }
  36957. if (value instanceof BABYLON.Color4) {
  36958. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36959. }
  36960. return value; // string
  36961. };
  36962. Action._GetTargetProperty = function (target) {
  36963. return {
  36964. name: "target",
  36965. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36966. : target instanceof BABYLON.Light ? "LightProperties"
  36967. : target instanceof BABYLON.Camera ? "CameraProperties"
  36968. : "SceneProperties",
  36969. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36970. };
  36971. };
  36972. BABYLON.Action = Action;
  36973. })(BABYLON || (BABYLON = {}));
  36974. //# sourceMappingURL=babylon.action.js.map
  36975. var BABYLON;
  36976. (function (BABYLON) {
  36977. /**
  36978. * ActionEvent is the event beint sent when an action is triggered.
  36979. */
  36980. var ActionEvent = (function () {
  36981. /**
  36982. * @param source The mesh or sprite that triggered the action.
  36983. * @param pointerX The X mouse cursor position at the time of the event
  36984. * @param pointerY The Y mouse cursor position at the time of the event
  36985. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36986. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36987. */
  36988. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36989. this.source = source;
  36990. this.pointerX = pointerX;
  36991. this.pointerY = pointerY;
  36992. this.meshUnderPointer = meshUnderPointer;
  36993. this.sourceEvent = sourceEvent;
  36994. this.additionalData = additionalData;
  36995. }
  36996. /**
  36997. * Helper function to auto-create an ActionEvent from a source mesh.
  36998. * @param source The source mesh that triggered the event
  36999. * @param evt {Event} The original (browser) event
  37000. */
  37001. ActionEvent.CreateNew = function (source, evt, additionalData) {
  37002. var scene = source.getScene();
  37003. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37004. };
  37005. /**
  37006. * Helper function to auto-create an ActionEvent from a source mesh.
  37007. * @param source The source sprite that triggered the event
  37008. * @param scene Scene associated with the sprite
  37009. * @param evt {Event} The original (browser) event
  37010. */
  37011. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  37012. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37013. };
  37014. /**
  37015. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  37016. * @param scene the scene where the event occurred
  37017. * @param evt {Event} The original (browser) event
  37018. */
  37019. ActionEvent.CreateNewFromScene = function (scene, evt) {
  37020. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  37021. };
  37022. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  37023. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  37024. };
  37025. return ActionEvent;
  37026. }());
  37027. BABYLON.ActionEvent = ActionEvent;
  37028. /**
  37029. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  37030. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  37031. */
  37032. var ActionManager = (function () {
  37033. function ActionManager(scene) {
  37034. // Members
  37035. this.actions = new Array();
  37036. this.hoverCursor = '';
  37037. this._scene = scene;
  37038. scene._actionManagers.push(this);
  37039. }
  37040. Object.defineProperty(ActionManager, "NothingTrigger", {
  37041. get: function () {
  37042. return ActionManager._NothingTrigger;
  37043. },
  37044. enumerable: true,
  37045. configurable: true
  37046. });
  37047. Object.defineProperty(ActionManager, "OnPickTrigger", {
  37048. get: function () {
  37049. return ActionManager._OnPickTrigger;
  37050. },
  37051. enumerable: true,
  37052. configurable: true
  37053. });
  37054. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  37055. get: function () {
  37056. return ActionManager._OnLeftPickTrigger;
  37057. },
  37058. enumerable: true,
  37059. configurable: true
  37060. });
  37061. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  37062. get: function () {
  37063. return ActionManager._OnRightPickTrigger;
  37064. },
  37065. enumerable: true,
  37066. configurable: true
  37067. });
  37068. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  37069. get: function () {
  37070. return ActionManager._OnCenterPickTrigger;
  37071. },
  37072. enumerable: true,
  37073. configurable: true
  37074. });
  37075. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  37076. get: function () {
  37077. return ActionManager._OnPickDownTrigger;
  37078. },
  37079. enumerable: true,
  37080. configurable: true
  37081. });
  37082. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  37083. get: function () {
  37084. return ActionManager._OnDoublePickTrigger;
  37085. },
  37086. enumerable: true,
  37087. configurable: true
  37088. });
  37089. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  37090. get: function () {
  37091. return ActionManager._OnPickUpTrigger;
  37092. },
  37093. enumerable: true,
  37094. configurable: true
  37095. });
  37096. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  37097. /// This trigger will only be raised if you also declared a OnPickDown
  37098. get: function () {
  37099. return ActionManager._OnPickOutTrigger;
  37100. },
  37101. enumerable: true,
  37102. configurable: true
  37103. });
  37104. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  37105. get: function () {
  37106. return ActionManager._OnLongPressTrigger;
  37107. },
  37108. enumerable: true,
  37109. configurable: true
  37110. });
  37111. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  37112. get: function () {
  37113. return ActionManager._OnPointerOverTrigger;
  37114. },
  37115. enumerable: true,
  37116. configurable: true
  37117. });
  37118. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  37119. get: function () {
  37120. return ActionManager._OnPointerOutTrigger;
  37121. },
  37122. enumerable: true,
  37123. configurable: true
  37124. });
  37125. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  37126. get: function () {
  37127. return ActionManager._OnEveryFrameTrigger;
  37128. },
  37129. enumerable: true,
  37130. configurable: true
  37131. });
  37132. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  37133. get: function () {
  37134. return ActionManager._OnIntersectionEnterTrigger;
  37135. },
  37136. enumerable: true,
  37137. configurable: true
  37138. });
  37139. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  37140. get: function () {
  37141. return ActionManager._OnIntersectionExitTrigger;
  37142. },
  37143. enumerable: true,
  37144. configurable: true
  37145. });
  37146. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  37147. get: function () {
  37148. return ActionManager._OnKeyDownTrigger;
  37149. },
  37150. enumerable: true,
  37151. configurable: true
  37152. });
  37153. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  37154. get: function () {
  37155. return ActionManager._OnKeyUpTrigger;
  37156. },
  37157. enumerable: true,
  37158. configurable: true
  37159. });
  37160. // Methods
  37161. ActionManager.prototype.dispose = function () {
  37162. var index = this._scene._actionManagers.indexOf(this);
  37163. for (var i = 0; i < this.actions.length; i++) {
  37164. var action = this.actions[i];
  37165. ActionManager.Triggers[action.trigger]--;
  37166. if (ActionManager.Triggers[action.trigger] === 0) {
  37167. delete ActionManager.Triggers[action.trigger];
  37168. }
  37169. }
  37170. if (index > -1) {
  37171. this._scene._actionManagers.splice(index, 1);
  37172. }
  37173. };
  37174. ActionManager.prototype.getScene = function () {
  37175. return this._scene;
  37176. };
  37177. /**
  37178. * Does this action manager handles actions of any of the given triggers
  37179. * @param {number[]} triggers - the triggers to be tested
  37180. * @return {boolean} whether one (or more) of the triggers is handeled
  37181. */
  37182. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  37183. for (var index = 0; index < this.actions.length; index++) {
  37184. var action = this.actions[index];
  37185. if (triggers.indexOf(action.trigger) > -1) {
  37186. return true;
  37187. }
  37188. }
  37189. return false;
  37190. };
  37191. /**
  37192. * Does this action manager handles actions of a given trigger
  37193. * @param {number} trigger - the trigger to be tested
  37194. * @return {boolean} whether the trigger is handeled
  37195. */
  37196. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  37197. for (var index = 0; index < this.actions.length; index++) {
  37198. var action = this.actions[index];
  37199. if (action.trigger === trigger) {
  37200. return true;
  37201. }
  37202. }
  37203. return false;
  37204. };
  37205. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  37206. /**
  37207. * Does this action manager has pointer triggers
  37208. * @return {boolean} whether or not it has pointer triggers
  37209. */
  37210. get: function () {
  37211. for (var index = 0; index < this.actions.length; index++) {
  37212. var action = this.actions[index];
  37213. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  37214. return true;
  37215. }
  37216. }
  37217. return false;
  37218. },
  37219. enumerable: true,
  37220. configurable: true
  37221. });
  37222. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  37223. /**
  37224. * Does this action manager has pick triggers
  37225. * @return {boolean} whether or not it has pick triggers
  37226. */
  37227. get: function () {
  37228. for (var index = 0; index < this.actions.length; index++) {
  37229. var action = this.actions[index];
  37230. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  37231. return true;
  37232. }
  37233. }
  37234. return false;
  37235. },
  37236. enumerable: true,
  37237. configurable: true
  37238. });
  37239. Object.defineProperty(ActionManager, "HasTriggers", {
  37240. /**
  37241. * Does exist one action manager with at least one trigger
  37242. * @return {boolean} whether or not it exists one action manager with one trigger
  37243. **/
  37244. get: function () {
  37245. for (var t in ActionManager.Triggers) {
  37246. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37247. return true;
  37248. }
  37249. }
  37250. return false;
  37251. },
  37252. enumerable: true,
  37253. configurable: true
  37254. });
  37255. Object.defineProperty(ActionManager, "HasPickTriggers", {
  37256. /**
  37257. * Does exist one action manager with at least one pick trigger
  37258. * @return {boolean} whether or not it exists one action manager with one pick trigger
  37259. **/
  37260. get: function () {
  37261. for (var t in ActionManager.Triggers) {
  37262. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37263. var t_int = parseInt(t);
  37264. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  37265. return true;
  37266. }
  37267. }
  37268. }
  37269. return false;
  37270. },
  37271. enumerable: true,
  37272. configurable: true
  37273. });
  37274. /**
  37275. * Does exist one action manager that handles actions of a given trigger
  37276. * @param {number} trigger - the trigger to be tested
  37277. * @return {boolean} whether the trigger is handeled by at least one action manager
  37278. **/
  37279. ActionManager.HasSpecificTrigger = function (trigger) {
  37280. for (var t in ActionManager.Triggers) {
  37281. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37282. var t_int = parseInt(t);
  37283. if (t_int === trigger) {
  37284. return true;
  37285. }
  37286. }
  37287. }
  37288. return false;
  37289. };
  37290. /**
  37291. * Registers an action to this action manager
  37292. * @param {BABYLON.Action} action - the action to be registered
  37293. * @return {BABYLON.Action} the action amended (prepared) after registration
  37294. */
  37295. ActionManager.prototype.registerAction = function (action) {
  37296. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  37297. if (this.getScene().actionManager !== this) {
  37298. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  37299. return null;
  37300. }
  37301. }
  37302. this.actions.push(action);
  37303. if (ActionManager.Triggers[action.trigger]) {
  37304. ActionManager.Triggers[action.trigger]++;
  37305. }
  37306. else {
  37307. ActionManager.Triggers[action.trigger] = 1;
  37308. }
  37309. action._actionManager = this;
  37310. action._prepare();
  37311. return action;
  37312. };
  37313. /**
  37314. * Process a specific trigger
  37315. * @param {number} trigger - the trigger to process
  37316. * @param evt {BABYLON.ActionEvent} the event details to be processed
  37317. */
  37318. ActionManager.prototype.processTrigger = function (trigger, evt) {
  37319. for (var index = 0; index < this.actions.length; index++) {
  37320. var action = this.actions[index];
  37321. if (action.trigger === trigger) {
  37322. if (trigger === ActionManager.OnKeyUpTrigger
  37323. || trigger === ActionManager.OnKeyDownTrigger) {
  37324. var parameter = action.getTriggerParameter();
  37325. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  37326. if (!parameter.toLowerCase) {
  37327. continue;
  37328. }
  37329. var lowerCase = parameter.toLowerCase();
  37330. if (lowerCase !== evt.sourceEvent.key) {
  37331. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  37332. var actualkey = String.fromCharCode(unicode).toLowerCase();
  37333. if (actualkey !== lowerCase) {
  37334. continue;
  37335. }
  37336. }
  37337. }
  37338. }
  37339. action._executeCurrent(evt);
  37340. }
  37341. }
  37342. };
  37343. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  37344. var properties = propertyPath.split(".");
  37345. for (var index = 0; index < properties.length - 1; index++) {
  37346. target = target[properties[index]];
  37347. }
  37348. return target;
  37349. };
  37350. ActionManager.prototype._getProperty = function (propertyPath) {
  37351. var properties = propertyPath.split(".");
  37352. return properties[properties.length - 1];
  37353. };
  37354. ActionManager.prototype.serialize = function (name) {
  37355. var root = {
  37356. children: [],
  37357. name: name,
  37358. type: 3,
  37359. properties: [] // Empty for root but required
  37360. };
  37361. for (var i = 0; i < this.actions.length; i++) {
  37362. var triggerObject = {
  37363. type: 0,
  37364. children: [],
  37365. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  37366. properties: []
  37367. };
  37368. var triggerOptions = this.actions[i].triggerOptions;
  37369. if (triggerOptions && typeof triggerOptions !== "number") {
  37370. if (triggerOptions.parameter instanceof BABYLON.Node) {
  37371. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  37372. }
  37373. else {
  37374. var parameter = {};
  37375. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  37376. if (triggerOptions.parameter.mesh) {
  37377. parameter._meshId = triggerOptions.parameter.mesh.id;
  37378. }
  37379. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  37380. }
  37381. }
  37382. // Serialize child action, recursively
  37383. this.actions[i].serialize(triggerObject);
  37384. // Add serialized trigger
  37385. root.children.push(triggerObject);
  37386. }
  37387. return root;
  37388. };
  37389. ActionManager.Parse = function (parsedActions, object, scene) {
  37390. var actionManager = new BABYLON.ActionManager(scene);
  37391. if (object === null)
  37392. scene.actionManager = actionManager;
  37393. else
  37394. object.actionManager = actionManager;
  37395. // instanciate a new object
  37396. var instanciate = function (name, params) {
  37397. var newInstance = Object.create(BABYLON[name].prototype);
  37398. newInstance.constructor.apply(newInstance, params);
  37399. return newInstance;
  37400. };
  37401. var parseParameter = function (name, value, target, propertyPath) {
  37402. if (propertyPath === null) {
  37403. // String, boolean or float
  37404. var floatValue = parseFloat(value);
  37405. if (value === "true" || value === "false")
  37406. return value === "true";
  37407. else
  37408. return isNaN(floatValue) ? value : floatValue;
  37409. }
  37410. var effectiveTarget = propertyPath.split(".");
  37411. var values = value.split(",");
  37412. // Get effective Target
  37413. for (var i = 0; i < effectiveTarget.length; i++) {
  37414. target = target[effectiveTarget[i]];
  37415. }
  37416. // Return appropriate value with its type
  37417. if (typeof (target) === "boolean")
  37418. return values[0] === "true";
  37419. if (typeof (target) === "string")
  37420. return values[0];
  37421. // Parameters with multiple values such as Vector3 etc.
  37422. var split = new Array();
  37423. for (var i = 0; i < values.length; i++)
  37424. split.push(parseFloat(values[i]));
  37425. if (target instanceof BABYLON.Vector3)
  37426. return BABYLON.Vector3.FromArray(split);
  37427. if (target instanceof BABYLON.Vector4)
  37428. return BABYLON.Vector4.FromArray(split);
  37429. if (target instanceof BABYLON.Color3)
  37430. return BABYLON.Color3.FromArray(split);
  37431. if (target instanceof BABYLON.Color4)
  37432. return BABYLON.Color4.FromArray(split);
  37433. return parseFloat(values[0]);
  37434. };
  37435. // traverse graph per trigger
  37436. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  37437. if (combineArray === void 0) { combineArray = null; }
  37438. if (parsedAction.detached)
  37439. return;
  37440. var parameters = new Array();
  37441. var target = null;
  37442. var propertyPath = null;
  37443. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  37444. // Parameters
  37445. if (parsedAction.type === 2)
  37446. parameters.push(actionManager);
  37447. else
  37448. parameters.push(trigger);
  37449. if (combine) {
  37450. var actions = new Array();
  37451. for (var j = 0; j < parsedAction.combine.length; j++) {
  37452. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  37453. }
  37454. parameters.push(actions);
  37455. }
  37456. else {
  37457. for (var i = 0; i < parsedAction.properties.length; i++) {
  37458. var value = parsedAction.properties[i].value;
  37459. var name = parsedAction.properties[i].name;
  37460. var targetType = parsedAction.properties[i].targetType;
  37461. if (name === "target")
  37462. if (targetType !== null && targetType === "SceneProperties")
  37463. value = target = scene;
  37464. else
  37465. value = target = scene.getNodeByName(value);
  37466. else if (name === "parent")
  37467. value = scene.getNodeByName(value);
  37468. else if (name === "sound")
  37469. value = scene.getSoundByName(value);
  37470. else if (name !== "propertyPath") {
  37471. if (parsedAction.type === 2 && name === "operator")
  37472. value = BABYLON.ValueCondition[value];
  37473. else
  37474. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  37475. }
  37476. else {
  37477. propertyPath = value;
  37478. }
  37479. parameters.push(value);
  37480. }
  37481. }
  37482. if (combineArray === null) {
  37483. parameters.push(condition);
  37484. }
  37485. else {
  37486. parameters.push(null);
  37487. }
  37488. // If interpolate value action
  37489. if (parsedAction.name === "InterpolateValueAction") {
  37490. var param = parameters[parameters.length - 2];
  37491. parameters[parameters.length - 1] = param;
  37492. parameters[parameters.length - 2] = condition;
  37493. }
  37494. // Action or condition(s) and not CombineAction
  37495. var newAction = instanciate(parsedAction.name, parameters);
  37496. if (newAction instanceof BABYLON.Condition && condition !== null) {
  37497. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  37498. if (action)
  37499. action.then(nothing);
  37500. else
  37501. actionManager.registerAction(nothing);
  37502. action = nothing;
  37503. }
  37504. if (combineArray === null) {
  37505. if (newAction instanceof BABYLON.Condition) {
  37506. condition = newAction;
  37507. newAction = action;
  37508. }
  37509. else {
  37510. condition = null;
  37511. if (action)
  37512. action.then(newAction);
  37513. else
  37514. actionManager.registerAction(newAction);
  37515. }
  37516. }
  37517. else {
  37518. combineArray.push(newAction);
  37519. }
  37520. for (var i = 0; i < parsedAction.children.length; i++)
  37521. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  37522. };
  37523. // triggers
  37524. for (var i = 0; i < parsedActions.children.length; i++) {
  37525. var triggerParams;
  37526. var trigger = parsedActions.children[i];
  37527. if (trigger.properties.length > 0) {
  37528. var param = trigger.properties[0].value;
  37529. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  37530. if (value._meshId) {
  37531. value.mesh = scene.getMeshByID(value._meshId);
  37532. }
  37533. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  37534. }
  37535. else
  37536. triggerParams = BABYLON.ActionManager[trigger.name];
  37537. for (var j = 0; j < trigger.children.length; j++) {
  37538. if (!trigger.detached)
  37539. traverse(trigger.children[j], triggerParams, null, null);
  37540. }
  37541. }
  37542. };
  37543. ActionManager.GetTriggerName = function (trigger) {
  37544. switch (trigger) {
  37545. case 0: return "NothingTrigger";
  37546. case 1: return "OnPickTrigger";
  37547. case 2: return "OnLeftPickTrigger";
  37548. case 3: return "OnRightPickTrigger";
  37549. case 4: return "OnCenterPickTrigger";
  37550. case 5: return "OnPickDownTrigger";
  37551. case 6: return "OnPickUpTrigger";
  37552. case 7: return "OnLongPressTrigger";
  37553. case 8: return "OnPointerOverTrigger";
  37554. case 9: return "OnPointerOutTrigger";
  37555. case 10: return "OnEveryFrameTrigger";
  37556. case 11: return "OnIntersectionEnterTrigger";
  37557. case 12: return "OnIntersectionExitTrigger";
  37558. case 13: return "OnKeyDownTrigger";
  37559. case 14: return "OnKeyUpTrigger";
  37560. case 15: return "OnPickOutTrigger";
  37561. default: return "";
  37562. }
  37563. };
  37564. return ActionManager;
  37565. }());
  37566. // Statics
  37567. ActionManager._NothingTrigger = 0;
  37568. ActionManager._OnPickTrigger = 1;
  37569. ActionManager._OnLeftPickTrigger = 2;
  37570. ActionManager._OnRightPickTrigger = 3;
  37571. ActionManager._OnCenterPickTrigger = 4;
  37572. ActionManager._OnPickDownTrigger = 5;
  37573. ActionManager._OnDoublePickTrigger = 6;
  37574. ActionManager._OnPickUpTrigger = 7;
  37575. ActionManager._OnLongPressTrigger = 8;
  37576. ActionManager._OnPointerOverTrigger = 9;
  37577. ActionManager._OnPointerOutTrigger = 10;
  37578. ActionManager._OnEveryFrameTrigger = 11;
  37579. ActionManager._OnIntersectionEnterTrigger = 12;
  37580. ActionManager._OnIntersectionExitTrigger = 13;
  37581. ActionManager._OnKeyDownTrigger = 14;
  37582. ActionManager._OnKeyUpTrigger = 15;
  37583. ActionManager._OnPickOutTrigger = 16;
  37584. ActionManager.Triggers = {};
  37585. BABYLON.ActionManager = ActionManager;
  37586. })(BABYLON || (BABYLON = {}));
  37587. //# sourceMappingURL=babylon.actionManager.js.map
  37588. var BABYLON;
  37589. (function (BABYLON) {
  37590. var InterpolateValueAction = (function (_super) {
  37591. __extends(InterpolateValueAction, _super);
  37592. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  37593. if (duration === void 0) { duration = 1000; }
  37594. var _this = _super.call(this, triggerOptions, condition) || this;
  37595. _this.propertyPath = propertyPath;
  37596. _this.value = value;
  37597. _this.duration = duration;
  37598. _this.stopOtherAnimations = stopOtherAnimations;
  37599. _this.onInterpolationDone = onInterpolationDone;
  37600. _this._target = _this._effectiveTarget = target;
  37601. return _this;
  37602. }
  37603. InterpolateValueAction.prototype._prepare = function () {
  37604. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37605. this._property = this._getProperty(this.propertyPath);
  37606. };
  37607. InterpolateValueAction.prototype.execute = function () {
  37608. var scene = this._actionManager.getScene();
  37609. var keys = [
  37610. {
  37611. frame: 0,
  37612. value: this._effectiveTarget[this._property]
  37613. }, {
  37614. frame: 100,
  37615. value: this.value
  37616. }
  37617. ];
  37618. var dataType;
  37619. if (typeof this.value === "number") {
  37620. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  37621. }
  37622. else if (this.value instanceof BABYLON.Color3) {
  37623. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  37624. }
  37625. else if (this.value instanceof BABYLON.Vector3) {
  37626. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  37627. }
  37628. else if (this.value instanceof BABYLON.Matrix) {
  37629. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  37630. }
  37631. else if (this.value instanceof BABYLON.Quaternion) {
  37632. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  37633. }
  37634. else {
  37635. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  37636. return;
  37637. }
  37638. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37639. animation.setKeys(keys);
  37640. if (this.stopOtherAnimations) {
  37641. scene.stopAnimation(this._effectiveTarget);
  37642. }
  37643. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  37644. };
  37645. InterpolateValueAction.prototype.serialize = function (parent) {
  37646. return _super.prototype._serialize.call(this, {
  37647. name: "InterpolateValueAction",
  37648. properties: [
  37649. BABYLON.Action._GetTargetProperty(this._target),
  37650. { name: "propertyPath", value: this.propertyPath },
  37651. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37652. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  37653. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  37654. ]
  37655. }, parent);
  37656. };
  37657. return InterpolateValueAction;
  37658. }(BABYLON.Action));
  37659. BABYLON.InterpolateValueAction = InterpolateValueAction;
  37660. })(BABYLON || (BABYLON = {}));
  37661. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  37662. var BABYLON;
  37663. (function (BABYLON) {
  37664. var SwitchBooleanAction = (function (_super) {
  37665. __extends(SwitchBooleanAction, _super);
  37666. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  37667. var _this = _super.call(this, triggerOptions, condition) || this;
  37668. _this.propertyPath = propertyPath;
  37669. _this._target = _this._effectiveTarget = target;
  37670. return _this;
  37671. }
  37672. SwitchBooleanAction.prototype._prepare = function () {
  37673. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37674. this._property = this._getProperty(this.propertyPath);
  37675. };
  37676. SwitchBooleanAction.prototype.execute = function () {
  37677. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  37678. };
  37679. SwitchBooleanAction.prototype.serialize = function (parent) {
  37680. return _super.prototype._serialize.call(this, {
  37681. name: "SwitchBooleanAction",
  37682. properties: [
  37683. BABYLON.Action._GetTargetProperty(this._target),
  37684. { name: "propertyPath", value: this.propertyPath }
  37685. ]
  37686. }, parent);
  37687. };
  37688. return SwitchBooleanAction;
  37689. }(BABYLON.Action));
  37690. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  37691. var SetStateAction = (function (_super) {
  37692. __extends(SetStateAction, _super);
  37693. function SetStateAction(triggerOptions, target, value, condition) {
  37694. var _this = _super.call(this, triggerOptions, condition) || this;
  37695. _this.value = value;
  37696. _this._target = target;
  37697. return _this;
  37698. }
  37699. SetStateAction.prototype.execute = function () {
  37700. this._target.state = this.value;
  37701. };
  37702. SetStateAction.prototype.serialize = function (parent) {
  37703. return _super.prototype._serialize.call(this, {
  37704. name: "SetStateAction",
  37705. properties: [
  37706. BABYLON.Action._GetTargetProperty(this._target),
  37707. { name: "value", value: this.value }
  37708. ]
  37709. }, parent);
  37710. };
  37711. return SetStateAction;
  37712. }(BABYLON.Action));
  37713. BABYLON.SetStateAction = SetStateAction;
  37714. var SetValueAction = (function (_super) {
  37715. __extends(SetValueAction, _super);
  37716. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  37717. var _this = _super.call(this, triggerOptions, condition) || this;
  37718. _this.propertyPath = propertyPath;
  37719. _this.value = value;
  37720. _this._target = _this._effectiveTarget = target;
  37721. return _this;
  37722. }
  37723. SetValueAction.prototype._prepare = function () {
  37724. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37725. this._property = this._getProperty(this.propertyPath);
  37726. };
  37727. SetValueAction.prototype.execute = function () {
  37728. this._effectiveTarget[this._property] = this.value;
  37729. if (this._target.markAsDirty) {
  37730. this._target.markAsDirty(this._property);
  37731. }
  37732. };
  37733. SetValueAction.prototype.serialize = function (parent) {
  37734. return _super.prototype._serialize.call(this, {
  37735. name: "SetValueAction",
  37736. properties: [
  37737. BABYLON.Action._GetTargetProperty(this._target),
  37738. { name: "propertyPath", value: this.propertyPath },
  37739. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37740. ]
  37741. }, parent);
  37742. };
  37743. return SetValueAction;
  37744. }(BABYLON.Action));
  37745. BABYLON.SetValueAction = SetValueAction;
  37746. var IncrementValueAction = (function (_super) {
  37747. __extends(IncrementValueAction, _super);
  37748. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  37749. var _this = _super.call(this, triggerOptions, condition) || this;
  37750. _this.propertyPath = propertyPath;
  37751. _this.value = value;
  37752. _this._target = _this._effectiveTarget = target;
  37753. return _this;
  37754. }
  37755. IncrementValueAction.prototype._prepare = function () {
  37756. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37757. this._property = this._getProperty(this.propertyPath);
  37758. if (typeof this._effectiveTarget[this._property] !== "number") {
  37759. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  37760. }
  37761. };
  37762. IncrementValueAction.prototype.execute = function () {
  37763. this._effectiveTarget[this._property] += this.value;
  37764. if (this._target.markAsDirty) {
  37765. this._target.markAsDirty(this._property);
  37766. }
  37767. };
  37768. IncrementValueAction.prototype.serialize = function (parent) {
  37769. return _super.prototype._serialize.call(this, {
  37770. name: "IncrementValueAction",
  37771. properties: [
  37772. BABYLON.Action._GetTargetProperty(this._target),
  37773. { name: "propertyPath", value: this.propertyPath },
  37774. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37775. ]
  37776. }, parent);
  37777. };
  37778. return IncrementValueAction;
  37779. }(BABYLON.Action));
  37780. BABYLON.IncrementValueAction = IncrementValueAction;
  37781. var PlayAnimationAction = (function (_super) {
  37782. __extends(PlayAnimationAction, _super);
  37783. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  37784. var _this = _super.call(this, triggerOptions, condition) || this;
  37785. _this.from = from;
  37786. _this.to = to;
  37787. _this.loop = loop;
  37788. _this._target = target;
  37789. return _this;
  37790. }
  37791. PlayAnimationAction.prototype._prepare = function () {
  37792. };
  37793. PlayAnimationAction.prototype.execute = function () {
  37794. var scene = this._actionManager.getScene();
  37795. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  37796. };
  37797. PlayAnimationAction.prototype.serialize = function (parent) {
  37798. return _super.prototype._serialize.call(this, {
  37799. name: "PlayAnimationAction",
  37800. properties: [
  37801. BABYLON.Action._GetTargetProperty(this._target),
  37802. { name: "from", value: String(this.from) },
  37803. { name: "to", value: String(this.to) },
  37804. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  37805. ]
  37806. }, parent);
  37807. };
  37808. return PlayAnimationAction;
  37809. }(BABYLON.Action));
  37810. BABYLON.PlayAnimationAction = PlayAnimationAction;
  37811. var StopAnimationAction = (function (_super) {
  37812. __extends(StopAnimationAction, _super);
  37813. function StopAnimationAction(triggerOptions, target, condition) {
  37814. var _this = _super.call(this, triggerOptions, condition) || this;
  37815. _this._target = target;
  37816. return _this;
  37817. }
  37818. StopAnimationAction.prototype._prepare = function () {
  37819. };
  37820. StopAnimationAction.prototype.execute = function () {
  37821. var scene = this._actionManager.getScene();
  37822. scene.stopAnimation(this._target);
  37823. };
  37824. StopAnimationAction.prototype.serialize = function (parent) {
  37825. return _super.prototype._serialize.call(this, {
  37826. name: "StopAnimationAction",
  37827. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  37828. }, parent);
  37829. };
  37830. return StopAnimationAction;
  37831. }(BABYLON.Action));
  37832. BABYLON.StopAnimationAction = StopAnimationAction;
  37833. var DoNothingAction = (function (_super) {
  37834. __extends(DoNothingAction, _super);
  37835. function DoNothingAction(triggerOptions, condition) {
  37836. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  37837. return _super.call(this, triggerOptions, condition) || this;
  37838. }
  37839. DoNothingAction.prototype.execute = function () {
  37840. };
  37841. DoNothingAction.prototype.serialize = function (parent) {
  37842. return _super.prototype._serialize.call(this, {
  37843. name: "DoNothingAction",
  37844. properties: []
  37845. }, parent);
  37846. };
  37847. return DoNothingAction;
  37848. }(BABYLON.Action));
  37849. BABYLON.DoNothingAction = DoNothingAction;
  37850. var CombineAction = (function (_super) {
  37851. __extends(CombineAction, _super);
  37852. function CombineAction(triggerOptions, children, condition) {
  37853. var _this = _super.call(this, triggerOptions, condition) || this;
  37854. _this.children = children;
  37855. return _this;
  37856. }
  37857. CombineAction.prototype._prepare = function () {
  37858. for (var index = 0; index < this.children.length; index++) {
  37859. this.children[index]._actionManager = this._actionManager;
  37860. this.children[index]._prepare();
  37861. }
  37862. };
  37863. CombineAction.prototype.execute = function (evt) {
  37864. for (var index = 0; index < this.children.length; index++) {
  37865. this.children[index].execute(evt);
  37866. }
  37867. };
  37868. CombineAction.prototype.serialize = function (parent) {
  37869. var serializationObject = _super.prototype._serialize.call(this, {
  37870. name: "CombineAction",
  37871. properties: [],
  37872. combine: []
  37873. }, parent);
  37874. for (var i = 0; i < this.children.length; i++) {
  37875. serializationObject.combine.push(this.children[i].serialize(null));
  37876. }
  37877. return serializationObject;
  37878. };
  37879. return CombineAction;
  37880. }(BABYLON.Action));
  37881. BABYLON.CombineAction = CombineAction;
  37882. var ExecuteCodeAction = (function (_super) {
  37883. __extends(ExecuteCodeAction, _super);
  37884. function ExecuteCodeAction(triggerOptions, func, condition) {
  37885. var _this = _super.call(this, triggerOptions, condition) || this;
  37886. _this.func = func;
  37887. return _this;
  37888. }
  37889. ExecuteCodeAction.prototype.execute = function (evt) {
  37890. this.func(evt);
  37891. };
  37892. return ExecuteCodeAction;
  37893. }(BABYLON.Action));
  37894. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  37895. var SetParentAction = (function (_super) {
  37896. __extends(SetParentAction, _super);
  37897. function SetParentAction(triggerOptions, target, parent, condition) {
  37898. var _this = _super.call(this, triggerOptions, condition) || this;
  37899. _this._target = target;
  37900. _this._parent = parent;
  37901. return _this;
  37902. }
  37903. SetParentAction.prototype._prepare = function () {
  37904. };
  37905. SetParentAction.prototype.execute = function () {
  37906. if (this._target.parent === this._parent) {
  37907. return;
  37908. }
  37909. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  37910. invertParentWorldMatrix.invert();
  37911. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  37912. this._target.parent = this._parent;
  37913. };
  37914. SetParentAction.prototype.serialize = function (parent) {
  37915. return _super.prototype._serialize.call(this, {
  37916. name: "SetParentAction",
  37917. properties: [
  37918. BABYLON.Action._GetTargetProperty(this._target),
  37919. BABYLON.Action._GetTargetProperty(this._parent),
  37920. ]
  37921. }, parent);
  37922. };
  37923. return SetParentAction;
  37924. }(BABYLON.Action));
  37925. BABYLON.SetParentAction = SetParentAction;
  37926. var PlaySoundAction = (function (_super) {
  37927. __extends(PlaySoundAction, _super);
  37928. function PlaySoundAction(triggerOptions, sound, condition) {
  37929. var _this = _super.call(this, triggerOptions, condition) || this;
  37930. _this._sound = sound;
  37931. return _this;
  37932. }
  37933. PlaySoundAction.prototype._prepare = function () {
  37934. };
  37935. PlaySoundAction.prototype.execute = function () {
  37936. if (this._sound !== undefined)
  37937. this._sound.play();
  37938. };
  37939. PlaySoundAction.prototype.serialize = function (parent) {
  37940. return _super.prototype._serialize.call(this, {
  37941. name: "PlaySoundAction",
  37942. properties: [{ name: "sound", value: this._sound.name }]
  37943. }, parent);
  37944. };
  37945. return PlaySoundAction;
  37946. }(BABYLON.Action));
  37947. BABYLON.PlaySoundAction = PlaySoundAction;
  37948. var StopSoundAction = (function (_super) {
  37949. __extends(StopSoundAction, _super);
  37950. function StopSoundAction(triggerOptions, sound, condition) {
  37951. var _this = _super.call(this, triggerOptions, condition) || this;
  37952. _this._sound = sound;
  37953. return _this;
  37954. }
  37955. StopSoundAction.prototype._prepare = function () {
  37956. };
  37957. StopSoundAction.prototype.execute = function () {
  37958. if (this._sound !== undefined)
  37959. this._sound.stop();
  37960. };
  37961. StopSoundAction.prototype.serialize = function (parent) {
  37962. return _super.prototype._serialize.call(this, {
  37963. name: "StopSoundAction",
  37964. properties: [{ name: "sound", value: this._sound.name }]
  37965. }, parent);
  37966. };
  37967. return StopSoundAction;
  37968. }(BABYLON.Action));
  37969. BABYLON.StopSoundAction = StopSoundAction;
  37970. })(BABYLON || (BABYLON = {}));
  37971. //# sourceMappingURL=babylon.directActions.js.map
  37972. var BABYLON;
  37973. (function (BABYLON) {
  37974. var SpriteManager = (function () {
  37975. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  37976. if (epsilon === void 0) { epsilon = 0.01; }
  37977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37978. this.name = name;
  37979. this.sprites = new Array();
  37980. this.renderingGroupId = 0;
  37981. this.layerMask = 0x0FFFFFFF;
  37982. this.fogEnabled = true;
  37983. this.isPickable = false;
  37984. /**
  37985. * An event triggered when the manager is disposed.
  37986. * @type {BABYLON.Observable}
  37987. */
  37988. this.onDisposeObservable = new BABYLON.Observable();
  37989. this._vertexBuffers = {};
  37990. this._capacity = capacity;
  37991. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  37992. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37993. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37994. if (cellSize.width && cellSize.height) {
  37995. this.cellWidth = cellSize.width;
  37996. this.cellHeight = cellSize.height;
  37997. }
  37998. else if (cellSize !== undefined) {
  37999. this.cellWidth = cellSize;
  38000. this.cellHeight = cellSize;
  38001. }
  38002. else {
  38003. return;
  38004. }
  38005. this._epsilon = epsilon;
  38006. this._scene = scene;
  38007. this._scene.spriteManagers.push(this);
  38008. var indices = [];
  38009. var index = 0;
  38010. for (var count = 0; count < capacity; count++) {
  38011. indices.push(index);
  38012. indices.push(index + 1);
  38013. indices.push(index + 2);
  38014. indices.push(index);
  38015. indices.push(index + 2);
  38016. indices.push(index + 3);
  38017. index += 4;
  38018. }
  38019. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38020. // VBO
  38021. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  38022. this._vertexData = new Float32Array(capacity * 16 * 4);
  38023. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  38024. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  38025. var options = this._buffer.createVertexBuffer("options", 4, 4);
  38026. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  38027. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  38028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  38029. this._vertexBuffers["options"] = options;
  38030. this._vertexBuffers["cellInfo"] = cellInfo;
  38031. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  38032. // Effects
  38033. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  38034. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  38035. }
  38036. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  38037. set: function (callback) {
  38038. if (this._onDisposeObserver) {
  38039. this.onDisposeObservable.remove(this._onDisposeObserver);
  38040. }
  38041. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38042. },
  38043. enumerable: true,
  38044. configurable: true
  38045. });
  38046. Object.defineProperty(SpriteManager.prototype, "texture", {
  38047. get: function () {
  38048. return this._spriteTexture;
  38049. },
  38050. set: function (value) {
  38051. this._spriteTexture = value;
  38052. },
  38053. enumerable: true,
  38054. configurable: true
  38055. });
  38056. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  38057. var arrayOffset = index * 16;
  38058. if (offsetX === 0)
  38059. offsetX = this._epsilon;
  38060. else if (offsetX === 1)
  38061. offsetX = 1 - this._epsilon;
  38062. if (offsetY === 0)
  38063. offsetY = this._epsilon;
  38064. else if (offsetY === 1)
  38065. offsetY = 1 - this._epsilon;
  38066. this._vertexData[arrayOffset] = sprite.position.x;
  38067. this._vertexData[arrayOffset + 1] = sprite.position.y;
  38068. this._vertexData[arrayOffset + 2] = sprite.position.z;
  38069. this._vertexData[arrayOffset + 3] = sprite.angle;
  38070. this._vertexData[arrayOffset + 4] = sprite.width;
  38071. this._vertexData[arrayOffset + 5] = sprite.height;
  38072. this._vertexData[arrayOffset + 6] = offsetX;
  38073. this._vertexData[arrayOffset + 7] = offsetY;
  38074. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  38075. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  38076. var offset = (sprite.cellIndex / rowSize) >> 0;
  38077. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  38078. this._vertexData[arrayOffset + 11] = offset;
  38079. // Color
  38080. this._vertexData[arrayOffset + 12] = sprite.color.r;
  38081. this._vertexData[arrayOffset + 13] = sprite.color.g;
  38082. this._vertexData[arrayOffset + 14] = sprite.color.b;
  38083. this._vertexData[arrayOffset + 15] = sprite.color.a;
  38084. };
  38085. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  38086. var count = Math.min(this._capacity, this.sprites.length);
  38087. var min = BABYLON.Vector3.Zero();
  38088. var max = BABYLON.Vector3.Zero();
  38089. var distance = Number.MAX_VALUE;
  38090. var currentSprite;
  38091. var cameraSpacePosition = BABYLON.Vector3.Zero();
  38092. var cameraView = camera.getViewMatrix();
  38093. for (var index = 0; index < count; index++) {
  38094. var sprite = this.sprites[index];
  38095. if (!sprite) {
  38096. continue;
  38097. }
  38098. if (predicate) {
  38099. if (!predicate(sprite)) {
  38100. continue;
  38101. }
  38102. }
  38103. else if (!sprite.isPickable) {
  38104. continue;
  38105. }
  38106. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  38107. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  38108. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  38109. if (ray.intersectsBoxMinMax(min, max)) {
  38110. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  38111. if (distance > currentDistance) {
  38112. distance = currentDistance;
  38113. currentSprite = sprite;
  38114. if (fastCheck) {
  38115. break;
  38116. }
  38117. }
  38118. }
  38119. }
  38120. if (currentSprite) {
  38121. var result = new BABYLON.PickingInfo();
  38122. result.hit = true;
  38123. result.pickedSprite = currentSprite;
  38124. result.distance = distance;
  38125. return result;
  38126. }
  38127. return null;
  38128. };
  38129. SpriteManager.prototype.render = function () {
  38130. // Check
  38131. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  38132. return;
  38133. var engine = this._scene.getEngine();
  38134. var baseSize = this._spriteTexture.getBaseSize();
  38135. // Sprites
  38136. var deltaTime = engine.getDeltaTime();
  38137. var max = Math.min(this._capacity, this.sprites.length);
  38138. var rowSize = baseSize.width / this.cellWidth;
  38139. var offset = 0;
  38140. for (var index = 0; index < max; index++) {
  38141. var sprite = this.sprites[index];
  38142. if (!sprite) {
  38143. continue;
  38144. }
  38145. sprite._animate(deltaTime);
  38146. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  38147. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  38148. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  38149. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  38150. }
  38151. this._buffer.update(this._vertexData);
  38152. // Render
  38153. var effect = this._effectBase;
  38154. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38155. effect = this._effectFog;
  38156. }
  38157. engine.enableEffect(effect);
  38158. var viewMatrix = this._scene.getViewMatrix();
  38159. effect.setTexture("diffuseSampler", this._spriteTexture);
  38160. effect.setMatrix("view", viewMatrix);
  38161. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  38162. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  38163. // Fog
  38164. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38165. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  38166. effect.setColor3("vFogColor", this._scene.fogColor);
  38167. }
  38168. // VBOs
  38169. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38170. // Draw order
  38171. engine.setDepthFunctionToLessOrEqual();
  38172. effect.setBool("alphaTest", true);
  38173. engine.setColorWrite(false);
  38174. engine.draw(true, 0, max * 6);
  38175. engine.setColorWrite(true);
  38176. effect.setBool("alphaTest", false);
  38177. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38178. engine.draw(true, 0, max * 6);
  38179. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38180. };
  38181. SpriteManager.prototype.dispose = function () {
  38182. if (this._buffer) {
  38183. this._buffer.dispose();
  38184. this._buffer = null;
  38185. }
  38186. if (this._indexBuffer) {
  38187. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38188. this._indexBuffer = null;
  38189. }
  38190. if (this._spriteTexture) {
  38191. this._spriteTexture.dispose();
  38192. this._spriteTexture = null;
  38193. }
  38194. // Remove from scene
  38195. var index = this._scene.spriteManagers.indexOf(this);
  38196. this._scene.spriteManagers.splice(index, 1);
  38197. // Callback
  38198. this.onDisposeObservable.notifyObservers(this);
  38199. this.onDisposeObservable.clear();
  38200. };
  38201. return SpriteManager;
  38202. }());
  38203. BABYLON.SpriteManager = SpriteManager;
  38204. })(BABYLON || (BABYLON = {}));
  38205. //# sourceMappingURL=babylon.spriteManager.js.map
  38206. var BABYLON;
  38207. (function (BABYLON) {
  38208. var Sprite = (function () {
  38209. function Sprite(name, manager) {
  38210. this.name = name;
  38211. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38212. this.width = 1.0;
  38213. this.height = 1.0;
  38214. this.angle = 0;
  38215. this.cellIndex = 0;
  38216. this.invertU = 0;
  38217. this.invertV = 0;
  38218. this.animations = new Array();
  38219. this.isPickable = false;
  38220. this._animationStarted = false;
  38221. this._loopAnimation = false;
  38222. this._fromIndex = 0;
  38223. this._toIndex = 0;
  38224. this._delay = 0;
  38225. this._direction = 1;
  38226. this._frameCount = 0;
  38227. this._time = 0;
  38228. this._manager = manager;
  38229. this._manager.sprites.push(this);
  38230. this.position = BABYLON.Vector3.Zero();
  38231. }
  38232. Object.defineProperty(Sprite.prototype, "size", {
  38233. get: function () {
  38234. return this.width;
  38235. },
  38236. set: function (value) {
  38237. this.width = value;
  38238. this.height = value;
  38239. },
  38240. enumerable: true,
  38241. configurable: true
  38242. });
  38243. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  38244. this._fromIndex = from;
  38245. this._toIndex = to;
  38246. this._loopAnimation = loop;
  38247. this._delay = delay;
  38248. this._animationStarted = true;
  38249. this._direction = from < to ? 1 : -1;
  38250. this.cellIndex = from;
  38251. this._time = 0;
  38252. this._onAnimationEnd = onAnimationEnd;
  38253. };
  38254. Sprite.prototype.stopAnimation = function () {
  38255. this._animationStarted = false;
  38256. };
  38257. Sprite.prototype._animate = function (deltaTime) {
  38258. if (!this._animationStarted)
  38259. return;
  38260. this._time += deltaTime;
  38261. if (this._time > this._delay) {
  38262. this._time = this._time % this._delay;
  38263. this.cellIndex += this._direction;
  38264. if (this.cellIndex === this._toIndex) {
  38265. if (this._loopAnimation) {
  38266. this.cellIndex = this._fromIndex;
  38267. }
  38268. else {
  38269. this._animationStarted = false;
  38270. if (this._onAnimationEnd) {
  38271. this._onAnimationEnd();
  38272. }
  38273. if (this.disposeWhenFinishedAnimating) {
  38274. this.dispose();
  38275. }
  38276. }
  38277. }
  38278. }
  38279. };
  38280. Sprite.prototype.dispose = function () {
  38281. for (var i = 0; i < this._manager.sprites.length; i++) {
  38282. if (this._manager.sprites[i] == this) {
  38283. this._manager.sprites.splice(i, 1);
  38284. }
  38285. }
  38286. };
  38287. return Sprite;
  38288. }());
  38289. BABYLON.Sprite = Sprite;
  38290. })(BABYLON || (BABYLON = {}));
  38291. //# sourceMappingURL=babylon.sprite.js.map
  38292. var BABYLON;
  38293. (function (BABYLON) {
  38294. var IntersectionInfo = (function () {
  38295. function IntersectionInfo(bu, bv, distance) {
  38296. this.bu = bu;
  38297. this.bv = bv;
  38298. this.distance = distance;
  38299. this.faceId = 0;
  38300. this.subMeshId = 0;
  38301. }
  38302. return IntersectionInfo;
  38303. }());
  38304. BABYLON.IntersectionInfo = IntersectionInfo;
  38305. var PickingInfo = (function () {
  38306. function PickingInfo() {
  38307. this.hit = false;
  38308. this.distance = 0;
  38309. this.pickedPoint = null;
  38310. this.pickedMesh = null;
  38311. this.bu = 0;
  38312. this.bv = 0;
  38313. this.faceId = -1;
  38314. this.subMeshId = 0;
  38315. this.pickedSprite = null;
  38316. }
  38317. // Methods
  38318. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  38319. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  38320. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  38321. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38322. return null;
  38323. }
  38324. var indices = this.pickedMesh.getIndices();
  38325. var result;
  38326. if (useVerticesNormals) {
  38327. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38328. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  38329. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  38330. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  38331. normal0 = normal0.scale(this.bu);
  38332. normal1 = normal1.scale(this.bv);
  38333. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  38334. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  38335. }
  38336. else {
  38337. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38338. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  38339. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  38340. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  38341. var p1p2 = vertex1.subtract(vertex2);
  38342. var p3p2 = vertex3.subtract(vertex2);
  38343. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  38344. }
  38345. if (useWorldCoordinates) {
  38346. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  38347. }
  38348. return BABYLON.Vector3.Normalize(result);
  38349. };
  38350. PickingInfo.prototype.getTextureCoordinates = function () {
  38351. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38352. return null;
  38353. }
  38354. var indices = this.pickedMesh.getIndices();
  38355. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38356. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  38357. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  38358. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  38359. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  38360. uv1 = uv1.scale(this.bu);
  38361. uv2 = uv2.scale(this.bv);
  38362. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  38363. };
  38364. return PickingInfo;
  38365. }());
  38366. BABYLON.PickingInfo = PickingInfo;
  38367. })(BABYLON || (BABYLON = {}));
  38368. //# sourceMappingURL=babylon.pickingInfo.js.map
  38369. var BABYLON;
  38370. (function (BABYLON) {
  38371. var Ray = (function () {
  38372. function Ray(origin, direction, length) {
  38373. if (length === void 0) { length = Number.MAX_VALUE; }
  38374. this.origin = origin;
  38375. this.direction = direction;
  38376. this.length = length;
  38377. }
  38378. // Methods
  38379. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  38380. var d = 0.0;
  38381. var maxValue = Number.MAX_VALUE;
  38382. var inv;
  38383. var min;
  38384. var max;
  38385. var temp;
  38386. if (Math.abs(this.direction.x) < 0.0000001) {
  38387. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  38388. return false;
  38389. }
  38390. }
  38391. else {
  38392. inv = 1.0 / this.direction.x;
  38393. min = (minimum.x - this.origin.x) * inv;
  38394. max = (maximum.x - this.origin.x) * inv;
  38395. if (max === -Infinity) {
  38396. max = Infinity;
  38397. }
  38398. if (min > max) {
  38399. temp = min;
  38400. min = max;
  38401. max = temp;
  38402. }
  38403. d = Math.max(min, d);
  38404. maxValue = Math.min(max, maxValue);
  38405. if (d > maxValue) {
  38406. return false;
  38407. }
  38408. }
  38409. if (Math.abs(this.direction.y) < 0.0000001) {
  38410. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  38411. return false;
  38412. }
  38413. }
  38414. else {
  38415. inv = 1.0 / this.direction.y;
  38416. min = (minimum.y - this.origin.y) * inv;
  38417. max = (maximum.y - this.origin.y) * inv;
  38418. if (max === -Infinity) {
  38419. max = Infinity;
  38420. }
  38421. if (min > max) {
  38422. temp = min;
  38423. min = max;
  38424. max = temp;
  38425. }
  38426. d = Math.max(min, d);
  38427. maxValue = Math.min(max, maxValue);
  38428. if (d > maxValue) {
  38429. return false;
  38430. }
  38431. }
  38432. if (Math.abs(this.direction.z) < 0.0000001) {
  38433. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  38434. return false;
  38435. }
  38436. }
  38437. else {
  38438. inv = 1.0 / this.direction.z;
  38439. min = (minimum.z - this.origin.z) * inv;
  38440. max = (maximum.z - this.origin.z) * inv;
  38441. if (max === -Infinity) {
  38442. max = Infinity;
  38443. }
  38444. if (min > max) {
  38445. temp = min;
  38446. min = max;
  38447. max = temp;
  38448. }
  38449. d = Math.max(min, d);
  38450. maxValue = Math.min(max, maxValue);
  38451. if (d > maxValue) {
  38452. return false;
  38453. }
  38454. }
  38455. return true;
  38456. };
  38457. Ray.prototype.intersectsBox = function (box) {
  38458. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  38459. };
  38460. Ray.prototype.intersectsSphere = function (sphere) {
  38461. var x = sphere.center.x - this.origin.x;
  38462. var y = sphere.center.y - this.origin.y;
  38463. var z = sphere.center.z - this.origin.z;
  38464. var pyth = (x * x) + (y * y) + (z * z);
  38465. var rr = sphere.radius * sphere.radius;
  38466. if (pyth <= rr) {
  38467. return true;
  38468. }
  38469. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  38470. if (dot < 0.0) {
  38471. return false;
  38472. }
  38473. var temp = pyth - (dot * dot);
  38474. return temp <= rr;
  38475. };
  38476. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  38477. if (!this._edge1) {
  38478. this._edge1 = BABYLON.Vector3.Zero();
  38479. this._edge2 = BABYLON.Vector3.Zero();
  38480. this._pvec = BABYLON.Vector3.Zero();
  38481. this._tvec = BABYLON.Vector3.Zero();
  38482. this._qvec = BABYLON.Vector3.Zero();
  38483. }
  38484. vertex1.subtractToRef(vertex0, this._edge1);
  38485. vertex2.subtractToRef(vertex0, this._edge2);
  38486. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  38487. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  38488. if (det === 0) {
  38489. return null;
  38490. }
  38491. var invdet = 1 / det;
  38492. this.origin.subtractToRef(vertex0, this._tvec);
  38493. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  38494. if (bu < 0 || bu > 1.0) {
  38495. return null;
  38496. }
  38497. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  38498. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  38499. if (bv < 0 || bu + bv > 1.0) {
  38500. return null;
  38501. }
  38502. //check if the distance is longer than the predefined length.
  38503. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  38504. if (distance > this.length) {
  38505. return null;
  38506. }
  38507. return new BABYLON.IntersectionInfo(bu, bv, distance);
  38508. };
  38509. Ray.prototype.intersectsPlane = function (plane) {
  38510. var distance;
  38511. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  38512. if (Math.abs(result1) < 9.99999997475243E-07) {
  38513. return null;
  38514. }
  38515. else {
  38516. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  38517. distance = (-plane.d - result2) / result1;
  38518. if (distance < 0.0) {
  38519. if (distance < -9.99999997475243E-07) {
  38520. return null;
  38521. }
  38522. else {
  38523. return 0;
  38524. }
  38525. }
  38526. return distance;
  38527. }
  38528. };
  38529. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  38530. var tm = BABYLON.Tmp.Matrix[0];
  38531. mesh.getWorldMatrix().invertToRef(tm);
  38532. if (this._tmpRay) {
  38533. Ray.TransformToRef(this, tm, this._tmpRay);
  38534. }
  38535. else {
  38536. this._tmpRay = Ray.Transform(this, tm);
  38537. }
  38538. return mesh.intersects(this._tmpRay, fastCheck);
  38539. };
  38540. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  38541. if (results) {
  38542. results.length = 0;
  38543. }
  38544. else {
  38545. results = [];
  38546. }
  38547. for (var i = 0; i < meshes.length; i++) {
  38548. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  38549. if (pickInfo.hit) {
  38550. results.push(pickInfo);
  38551. }
  38552. }
  38553. results.sort(this._comparePickingInfo);
  38554. return results;
  38555. };
  38556. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  38557. if (pickingInfoA.distance < pickingInfoB.distance) {
  38558. return -1;
  38559. }
  38560. else if (pickingInfoA.distance > pickingInfoB.distance) {
  38561. return 1;
  38562. }
  38563. else {
  38564. return 0;
  38565. }
  38566. };
  38567. /**
  38568. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  38569. * @param sega the first point of the segment to test the intersection against
  38570. * @param segb the second point of the segment to test the intersection against
  38571. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  38572. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  38573. */
  38574. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  38575. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  38576. var u = segb.subtract(sega);
  38577. var v = rsegb.subtract(this.origin);
  38578. var w = sega.subtract(this.origin);
  38579. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  38580. var b = BABYLON.Vector3.Dot(u, v);
  38581. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  38582. var d = BABYLON.Vector3.Dot(u, w);
  38583. var e = BABYLON.Vector3.Dot(v, w);
  38584. var D = a * c - b * b; // always >= 0
  38585. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  38586. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  38587. // compute the line parameters of the two closest points
  38588. if (D < Ray.smallnum) {
  38589. sN = 0.0; // force using point P0 on segment S1
  38590. sD = 1.0; // to prevent possible division by 0.0 later
  38591. tN = e;
  38592. tD = c;
  38593. }
  38594. else {
  38595. sN = (b * e - c * d);
  38596. tN = (a * e - b * d);
  38597. if (sN < 0.0) {
  38598. sN = 0.0;
  38599. tN = e;
  38600. tD = c;
  38601. }
  38602. else if (sN > sD) {
  38603. sN = sD;
  38604. tN = e + b;
  38605. tD = c;
  38606. }
  38607. }
  38608. if (tN < 0.0) {
  38609. tN = 0.0;
  38610. // recompute sc for this edge
  38611. if (-d < 0.0) {
  38612. sN = 0.0;
  38613. }
  38614. else if (-d > a)
  38615. sN = sD;
  38616. else {
  38617. sN = -d;
  38618. sD = a;
  38619. }
  38620. }
  38621. else if (tN > tD) {
  38622. tN = tD;
  38623. // recompute sc for this edge
  38624. if ((-d + b) < 0.0) {
  38625. sN = 0;
  38626. }
  38627. else if ((-d + b) > a) {
  38628. sN = sD;
  38629. }
  38630. else {
  38631. sN = (-d + b);
  38632. sD = a;
  38633. }
  38634. }
  38635. // finally do the division to get sc and tc
  38636. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  38637. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  38638. // get the difference of the two closest points
  38639. var qtc = v.multiplyByFloats(tc, tc, tc);
  38640. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  38641. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  38642. if (isIntersected) {
  38643. return qtc.length();
  38644. }
  38645. return -1;
  38646. };
  38647. // Statics
  38648. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  38649. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  38650. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  38651. var direction = end.subtract(start);
  38652. direction.normalize();
  38653. return new Ray(start, direction);
  38654. };
  38655. /**
  38656. * 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
  38657. * transformed to the given world matrix.
  38658. * @param origin The origin point
  38659. * @param end The end point
  38660. * @param world a matrix to transform the ray to. Default is the identity matrix.
  38661. */
  38662. Ray.CreateNewFromTo = function (origin, end, world) {
  38663. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  38664. var direction = end.subtract(origin);
  38665. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  38666. direction.normalize();
  38667. return Ray.Transform(new Ray(origin, direction, length), world);
  38668. };
  38669. Ray.Transform = function (ray, matrix) {
  38670. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  38671. Ray.TransformToRef(ray, matrix, result);
  38672. return result;
  38673. };
  38674. Ray.TransformToRef = function (ray, matrix, result) {
  38675. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  38676. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  38677. result.length = ray.length;
  38678. var dir = result.direction;
  38679. var len = dir.length();
  38680. if (!(len === 0 || len === 1)) {
  38681. var num = 1.0 / len;
  38682. dir.x *= num;
  38683. dir.y *= num;
  38684. dir.z *= num;
  38685. result.length *= len;
  38686. }
  38687. };
  38688. return Ray;
  38689. }());
  38690. Ray.smallnum = 0.00000001;
  38691. Ray.rayl = 10e8;
  38692. BABYLON.Ray = Ray;
  38693. })(BABYLON || (BABYLON = {}));
  38694. //# sourceMappingURL=babylon.ray.js.map
  38695. var BABYLON;
  38696. (function (BABYLON) {
  38697. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  38698. if (boxMin.x > sphereCenter.x + sphereRadius)
  38699. return false;
  38700. if (sphereCenter.x - sphereRadius > boxMax.x)
  38701. return false;
  38702. if (boxMin.y > sphereCenter.y + sphereRadius)
  38703. return false;
  38704. if (sphereCenter.y - sphereRadius > boxMax.y)
  38705. return false;
  38706. if (boxMin.z > sphereCenter.z + sphereRadius)
  38707. return false;
  38708. if (sphereCenter.z - sphereRadius > boxMax.z)
  38709. return false;
  38710. return true;
  38711. };
  38712. var getLowestRoot = (function () {
  38713. var result = { root: 0, found: false };
  38714. return function (a, b, c, maxR) {
  38715. result.root = 0;
  38716. result.found = false;
  38717. var determinant = b * b - 4.0 * a * c;
  38718. if (determinant < 0)
  38719. return result;
  38720. var sqrtD = Math.sqrt(determinant);
  38721. var r1 = (-b - sqrtD) / (2.0 * a);
  38722. var r2 = (-b + sqrtD) / (2.0 * a);
  38723. if (r1 > r2) {
  38724. var temp = r2;
  38725. r2 = r1;
  38726. r1 = temp;
  38727. }
  38728. if (r1 > 0 && r1 < maxR) {
  38729. result.root = r1;
  38730. result.found = true;
  38731. return result;
  38732. }
  38733. if (r2 > 0 && r2 < maxR) {
  38734. result.root = r2;
  38735. result.found = true;
  38736. return result;
  38737. }
  38738. return result;
  38739. };
  38740. })();
  38741. var Collider = (function () {
  38742. function Collider() {
  38743. this.radius = BABYLON.Vector3.One();
  38744. this.retry = 0;
  38745. this.basePointWorld = BABYLON.Vector3.Zero();
  38746. this.velocityWorld = BABYLON.Vector3.Zero();
  38747. this.normalizedVelocity = BABYLON.Vector3.Zero();
  38748. this._collisionPoint = BABYLON.Vector3.Zero();
  38749. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  38750. this._tempVector = BABYLON.Vector3.Zero();
  38751. this._tempVector2 = BABYLON.Vector3.Zero();
  38752. this._tempVector3 = BABYLON.Vector3.Zero();
  38753. this._tempVector4 = BABYLON.Vector3.Zero();
  38754. this._edge = BABYLON.Vector3.Zero();
  38755. this._baseToVertex = BABYLON.Vector3.Zero();
  38756. this._destinationPoint = BABYLON.Vector3.Zero();
  38757. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  38758. this._displacementVector = BABYLON.Vector3.Zero();
  38759. this._collisionMask = -1;
  38760. }
  38761. Object.defineProperty(Collider.prototype, "collisionMask", {
  38762. get: function () {
  38763. return this._collisionMask;
  38764. },
  38765. set: function (mask) {
  38766. this._collisionMask = !isNaN(mask) ? mask : -1;
  38767. },
  38768. enumerable: true,
  38769. configurable: true
  38770. });
  38771. // Methods
  38772. Collider.prototype._initialize = function (source, dir, e) {
  38773. this.velocity = dir;
  38774. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  38775. this.basePoint = source;
  38776. source.multiplyToRef(this.radius, this.basePointWorld);
  38777. dir.multiplyToRef(this.radius, this.velocityWorld);
  38778. this.velocityWorldLength = this.velocityWorld.length();
  38779. this.epsilon = e;
  38780. this.collisionFound = false;
  38781. };
  38782. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  38783. pa.subtractToRef(point, this._tempVector);
  38784. pb.subtractToRef(point, this._tempVector2);
  38785. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  38786. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38787. if (d < 0)
  38788. return false;
  38789. pc.subtractToRef(point, this._tempVector3);
  38790. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  38791. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38792. if (d < 0)
  38793. return false;
  38794. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  38795. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  38796. return d >= 0;
  38797. };
  38798. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  38799. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  38800. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  38801. if (distance > this.velocityWorldLength + max + sphereRadius) {
  38802. return false;
  38803. }
  38804. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  38805. return false;
  38806. return true;
  38807. };
  38808. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  38809. var t0;
  38810. var embeddedInPlane = false;
  38811. //defensive programming, actually not needed.
  38812. if (!trianglePlaneArray) {
  38813. trianglePlaneArray = [];
  38814. }
  38815. if (!trianglePlaneArray[faceIndex]) {
  38816. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  38817. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  38818. }
  38819. var trianglePlane = trianglePlaneArray[faceIndex];
  38820. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  38821. return;
  38822. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  38823. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  38824. if (normalDotVelocity == 0) {
  38825. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  38826. return;
  38827. embeddedInPlane = true;
  38828. t0 = 0;
  38829. }
  38830. else {
  38831. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  38832. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  38833. if (t0 > t1) {
  38834. var temp = t1;
  38835. t1 = t0;
  38836. t0 = temp;
  38837. }
  38838. if (t0 > 1.0 || t1 < 0.0)
  38839. return;
  38840. if (t0 < 0)
  38841. t0 = 0;
  38842. if (t0 > 1.0)
  38843. t0 = 1.0;
  38844. }
  38845. this._collisionPoint.copyFromFloats(0, 0, 0);
  38846. var found = false;
  38847. var t = 1.0;
  38848. if (!embeddedInPlane) {
  38849. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  38850. this.velocity.scaleToRef(t0, this._tempVector);
  38851. this._planeIntersectionPoint.addInPlace(this._tempVector);
  38852. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  38853. found = true;
  38854. t = t0;
  38855. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  38856. }
  38857. }
  38858. if (!found) {
  38859. var velocitySquaredLength = this.velocity.lengthSquared();
  38860. var a = velocitySquaredLength;
  38861. this.basePoint.subtractToRef(p1, this._tempVector);
  38862. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  38863. var c = this._tempVector.lengthSquared() - 1.0;
  38864. var lowestRoot = getLowestRoot(a, b, c, t);
  38865. if (lowestRoot.found) {
  38866. t = lowestRoot.root;
  38867. found = true;
  38868. this._collisionPoint.copyFrom(p1);
  38869. }
  38870. this.basePoint.subtractToRef(p2, this._tempVector);
  38871. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  38872. c = this._tempVector.lengthSquared() - 1.0;
  38873. lowestRoot = getLowestRoot(a, b, c, t);
  38874. if (lowestRoot.found) {
  38875. t = lowestRoot.root;
  38876. found = true;
  38877. this._collisionPoint.copyFrom(p2);
  38878. }
  38879. this.basePoint.subtractToRef(p3, this._tempVector);
  38880. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  38881. c = this._tempVector.lengthSquared() - 1.0;
  38882. lowestRoot = getLowestRoot(a, b, c, t);
  38883. if (lowestRoot.found) {
  38884. t = lowestRoot.root;
  38885. found = true;
  38886. this._collisionPoint.copyFrom(p3);
  38887. }
  38888. p2.subtractToRef(p1, this._edge);
  38889. p1.subtractToRef(this.basePoint, this._baseToVertex);
  38890. var edgeSquaredLength = this._edge.lengthSquared();
  38891. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  38892. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  38893. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  38894. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  38895. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  38896. lowestRoot = getLowestRoot(a, b, c, t);
  38897. if (lowestRoot.found) {
  38898. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  38899. if (f >= 0.0 && f <= 1.0) {
  38900. t = lowestRoot.root;
  38901. found = true;
  38902. this._edge.scaleInPlace(f);
  38903. p1.addToRef(this._edge, this._collisionPoint);
  38904. }
  38905. }
  38906. p3.subtractToRef(p2, this._edge);
  38907. p2.subtractToRef(this.basePoint, this._baseToVertex);
  38908. edgeSquaredLength = this._edge.lengthSquared();
  38909. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  38910. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  38911. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  38912. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  38913. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  38914. lowestRoot = getLowestRoot(a, b, c, t);
  38915. if (lowestRoot.found) {
  38916. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  38917. if (f >= 0.0 && f <= 1.0) {
  38918. t = lowestRoot.root;
  38919. found = true;
  38920. this._edge.scaleInPlace(f);
  38921. p2.addToRef(this._edge, this._collisionPoint);
  38922. }
  38923. }
  38924. p1.subtractToRef(p3, this._edge);
  38925. p3.subtractToRef(this.basePoint, this._baseToVertex);
  38926. edgeSquaredLength = this._edge.lengthSquared();
  38927. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  38928. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  38929. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  38930. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  38931. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  38932. lowestRoot = getLowestRoot(a, b, c, t);
  38933. if (lowestRoot.found) {
  38934. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  38935. if (f >= 0.0 && f <= 1.0) {
  38936. t = lowestRoot.root;
  38937. found = true;
  38938. this._edge.scaleInPlace(f);
  38939. p3.addToRef(this._edge, this._collisionPoint);
  38940. }
  38941. }
  38942. }
  38943. if (found) {
  38944. var distToCollision = t * this.velocity.length();
  38945. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  38946. if (!this.intersectionPoint) {
  38947. this.intersectionPoint = this._collisionPoint.clone();
  38948. }
  38949. else {
  38950. this.intersectionPoint.copyFrom(this._collisionPoint);
  38951. }
  38952. this.nearestDistance = distToCollision;
  38953. this.collisionFound = true;
  38954. }
  38955. }
  38956. };
  38957. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  38958. for (var i = indexStart; i < indexEnd; i += 3) {
  38959. var p1 = pts[indices[i] - decal];
  38960. var p2 = pts[indices[i + 1] - decal];
  38961. var p3 = pts[indices[i + 2] - decal];
  38962. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  38963. }
  38964. };
  38965. Collider.prototype._getResponse = function (pos, vel) {
  38966. pos.addToRef(vel, this._destinationPoint);
  38967. vel.scaleInPlace((this.nearestDistance / vel.length()));
  38968. this.basePoint.addToRef(vel, pos);
  38969. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  38970. this._slidePlaneNormal.normalize();
  38971. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  38972. pos.addInPlace(this._displacementVector);
  38973. this.intersectionPoint.addInPlace(this._displacementVector);
  38974. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  38975. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  38976. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  38977. };
  38978. return Collider;
  38979. }());
  38980. BABYLON.Collider = Collider;
  38981. })(BABYLON || (BABYLON = {}));
  38982. //# sourceMappingURL=babylon.collider.js.map
  38983. var BABYLON;
  38984. (function (BABYLON) {
  38985. //WebWorker code will be inserted to this variable.
  38986. BABYLON.CollisionWorker = "";
  38987. var WorkerTaskType;
  38988. (function (WorkerTaskType) {
  38989. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  38990. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  38991. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  38992. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  38993. var WorkerReplyType;
  38994. (function (WorkerReplyType) {
  38995. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  38996. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  38997. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  38998. var CollisionCoordinatorWorker = (function () {
  38999. function CollisionCoordinatorWorker() {
  39000. var _this = this;
  39001. this._scaledPosition = BABYLON.Vector3.Zero();
  39002. this._scaledVelocity = BABYLON.Vector3.Zero();
  39003. this.onMeshUpdated = function (mesh) {
  39004. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  39005. };
  39006. this.onGeometryUpdated = function (geometry) {
  39007. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  39008. };
  39009. this._afterRender = function () {
  39010. if (!_this._init)
  39011. return;
  39012. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  39013. return;
  39014. }
  39015. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  39016. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  39017. if (_this._runningUpdated > 4) {
  39018. return;
  39019. }
  39020. ++_this._runningUpdated;
  39021. var payload = {
  39022. updatedMeshes: _this._addUpdateMeshesList,
  39023. updatedGeometries: _this._addUpdateGeometriesList,
  39024. removedGeometries: _this._toRemoveGeometryArray,
  39025. removedMeshes: _this._toRemoveMeshesArray
  39026. };
  39027. var message = {
  39028. payload: payload,
  39029. taskType: WorkerTaskType.UPDATE
  39030. };
  39031. var serializable = [];
  39032. for (var id in payload.updatedGeometries) {
  39033. if (payload.updatedGeometries.hasOwnProperty(id)) {
  39034. //prepare transferables
  39035. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  39036. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  39037. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  39038. }
  39039. }
  39040. _this._worker.postMessage(message, serializable);
  39041. _this._addUpdateMeshesList = {};
  39042. _this._addUpdateGeometriesList = {};
  39043. _this._toRemoveGeometryArray = [];
  39044. _this._toRemoveMeshesArray = [];
  39045. };
  39046. this._onMessageFromWorker = function (e) {
  39047. var returnData = e.data;
  39048. if (returnData.error != WorkerReplyType.SUCCESS) {
  39049. //TODO what errors can be returned from the worker?
  39050. BABYLON.Tools.Warn("error returned from worker!");
  39051. return;
  39052. }
  39053. switch (returnData.taskType) {
  39054. case WorkerTaskType.INIT:
  39055. _this._init = true;
  39056. //Update the worked with ALL of the scene's current state
  39057. _this._scene.meshes.forEach(function (mesh) {
  39058. _this.onMeshAdded(mesh);
  39059. });
  39060. _this._scene.getGeometries().forEach(function (geometry) {
  39061. _this.onGeometryAdded(geometry);
  39062. });
  39063. break;
  39064. case WorkerTaskType.UPDATE:
  39065. _this._runningUpdated--;
  39066. break;
  39067. case WorkerTaskType.COLLIDE:
  39068. _this._runningCollisionTask = false;
  39069. var returnPayload = returnData.payload;
  39070. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  39071. return;
  39072. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  39073. //cleanup
  39074. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  39075. break;
  39076. }
  39077. };
  39078. this._collisionsCallbackArray = [];
  39079. this._init = false;
  39080. this._runningUpdated = 0;
  39081. this._runningCollisionTask = false;
  39082. this._addUpdateMeshesList = {};
  39083. this._addUpdateGeometriesList = {};
  39084. this._toRemoveGeometryArray = [];
  39085. this._toRemoveMeshesArray = [];
  39086. }
  39087. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  39088. if (!this._init)
  39089. return;
  39090. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  39091. return;
  39092. position.divideToRef(collider.radius, this._scaledPosition);
  39093. velocity.divideToRef(collider.radius, this._scaledVelocity);
  39094. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  39095. var payload = {
  39096. collider: {
  39097. position: this._scaledPosition.asArray(),
  39098. velocity: this._scaledVelocity.asArray(),
  39099. radius: collider.radius.asArray()
  39100. },
  39101. collisionId: collisionIndex,
  39102. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  39103. maximumRetry: maximumRetry
  39104. };
  39105. var message = {
  39106. payload: payload,
  39107. taskType: WorkerTaskType.COLLIDE
  39108. };
  39109. this._worker.postMessage(message);
  39110. };
  39111. CollisionCoordinatorWorker.prototype.init = function (scene) {
  39112. this._scene = scene;
  39113. this._scene.registerAfterRender(this._afterRender);
  39114. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  39115. this._worker = new Worker(workerUrl);
  39116. this._worker.onmessage = this._onMessageFromWorker;
  39117. var message = {
  39118. payload: {},
  39119. taskType: WorkerTaskType.INIT
  39120. };
  39121. this._worker.postMessage(message);
  39122. };
  39123. CollisionCoordinatorWorker.prototype.destroy = function () {
  39124. this._scene.unregisterAfterRender(this._afterRender);
  39125. this._worker.terminate();
  39126. };
  39127. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  39128. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  39129. this.onMeshUpdated(mesh);
  39130. };
  39131. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  39132. this._toRemoveMeshesArray.push(mesh.uniqueId);
  39133. };
  39134. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  39135. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  39136. geometry.onGeometryUpdated = this.onGeometryUpdated;
  39137. this.onGeometryUpdated(geometry);
  39138. };
  39139. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  39140. this._toRemoveGeometryArray.push(geometry.id);
  39141. };
  39142. return CollisionCoordinatorWorker;
  39143. }());
  39144. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  39145. var submeshes = [];
  39146. if (mesh.subMeshes) {
  39147. submeshes = mesh.subMeshes.map(function (sm, idx) {
  39148. return {
  39149. position: idx,
  39150. verticesStart: sm.verticesStart,
  39151. verticesCount: sm.verticesCount,
  39152. indexStart: sm.indexStart,
  39153. indexCount: sm.indexCount,
  39154. hasMaterial: !!sm.getMaterial(),
  39155. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  39156. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  39157. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  39158. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  39159. };
  39160. });
  39161. }
  39162. var geometryId = null;
  39163. if (mesh instanceof BABYLON.Mesh) {
  39164. geometryId = mesh.geometry ? mesh.geometry.id : null;
  39165. }
  39166. else if (mesh instanceof BABYLON.InstancedMesh) {
  39167. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  39168. }
  39169. return {
  39170. uniqueId: mesh.uniqueId,
  39171. id: mesh.id,
  39172. name: mesh.name,
  39173. geometryId: geometryId,
  39174. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  39175. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  39176. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  39177. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  39178. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  39179. subMeshes: submeshes,
  39180. checkCollisions: mesh.checkCollisions
  39181. };
  39182. };
  39183. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  39184. return {
  39185. id: geometry.id,
  39186. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  39187. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  39188. indices: new Uint32Array(geometry.getIndices() || []),
  39189. };
  39190. };
  39191. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  39192. var CollisionCoordinatorLegacy = (function () {
  39193. function CollisionCoordinatorLegacy() {
  39194. this._scaledPosition = BABYLON.Vector3.Zero();
  39195. this._scaledVelocity = BABYLON.Vector3.Zero();
  39196. this._finalPosition = BABYLON.Vector3.Zero();
  39197. }
  39198. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  39199. position.divideToRef(collider.radius, this._scaledPosition);
  39200. velocity.divideToRef(collider.radius, this._scaledVelocity);
  39201. collider.collidedMesh = null;
  39202. collider.retry = 0;
  39203. collider.initialVelocity = this._scaledVelocity;
  39204. collider.initialPosition = this._scaledPosition;
  39205. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  39206. this._finalPosition.multiplyInPlace(collider.radius);
  39207. //run the callback
  39208. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  39209. };
  39210. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  39211. this._scene = scene;
  39212. };
  39213. CollisionCoordinatorLegacy.prototype.destroy = function () {
  39214. //Legacy need no destruction method.
  39215. };
  39216. //No update in legacy mode
  39217. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  39218. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  39219. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  39220. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  39221. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  39222. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  39223. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  39224. if (excludedMesh === void 0) { excludedMesh = null; }
  39225. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  39226. if (collider.retry >= maximumRetry) {
  39227. finalPosition.copyFrom(position);
  39228. return;
  39229. }
  39230. // Check if this is a mesh else camera or -1
  39231. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  39232. collider._initialize(position, velocity, closeDistance);
  39233. // Check all meshes
  39234. for (var index = 0; index < this._scene.meshes.length; index++) {
  39235. var mesh = this._scene.meshes[index];
  39236. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  39237. mesh._checkCollision(collider);
  39238. }
  39239. }
  39240. if (!collider.collisionFound) {
  39241. position.addToRef(velocity, finalPosition);
  39242. return;
  39243. }
  39244. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  39245. collider._getResponse(position, velocity);
  39246. }
  39247. if (velocity.length() <= closeDistance) {
  39248. finalPosition.copyFrom(position);
  39249. return;
  39250. }
  39251. collider.retry++;
  39252. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  39253. };
  39254. return CollisionCoordinatorLegacy;
  39255. }());
  39256. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  39257. })(BABYLON || (BABYLON = {}));
  39258. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  39259. var BABYLON;
  39260. (function (BABYLON) {
  39261. var Particle = (function () {
  39262. function Particle() {
  39263. this.position = BABYLON.Vector3.Zero();
  39264. this.direction = BABYLON.Vector3.Zero();
  39265. this.color = new BABYLON.Color4(0, 0, 0, 0);
  39266. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  39267. this.lifeTime = 1.0;
  39268. this.age = 0;
  39269. this.size = 0;
  39270. this.angle = 0;
  39271. this.angularSpeed = 0;
  39272. }
  39273. Particle.prototype.copyTo = function (other) {
  39274. other.position.copyFrom(this.position);
  39275. other.direction.copyFrom(this.direction);
  39276. other.color.copyFrom(this.color);
  39277. other.colorStep.copyFrom(this.colorStep);
  39278. other.lifeTime = this.lifeTime;
  39279. other.age = this.age;
  39280. other.size = this.size;
  39281. other.angle = this.angle;
  39282. other.angularSpeed = this.angularSpeed;
  39283. };
  39284. return Particle;
  39285. }());
  39286. BABYLON.Particle = Particle;
  39287. })(BABYLON || (BABYLON = {}));
  39288. //# sourceMappingURL=babylon.particle.js.map
  39289. var BABYLON;
  39290. (function (BABYLON) {
  39291. var randomNumber = function (min, max) {
  39292. if (min === max) {
  39293. return (min);
  39294. }
  39295. var random = Math.random();
  39296. return ((random * (max - min)) + min);
  39297. };
  39298. var ParticleSystem = (function () {
  39299. function ParticleSystem(name, capacity, scene, customEffect) {
  39300. var _this = this;
  39301. this.name = name;
  39302. // Members
  39303. this.animations = [];
  39304. this.renderingGroupId = 0;
  39305. this.emitter = null;
  39306. this.emitRate = 10;
  39307. this.manualEmitCount = -1;
  39308. this.updateSpeed = 0.01;
  39309. this.targetStopDuration = 0;
  39310. this.disposeOnStop = false;
  39311. this.minEmitPower = 1;
  39312. this.maxEmitPower = 1;
  39313. this.minLifeTime = 1;
  39314. this.maxLifeTime = 1;
  39315. this.minSize = 1;
  39316. this.maxSize = 1;
  39317. this.minAngularSpeed = 0;
  39318. this.maxAngularSpeed = 0;
  39319. this.layerMask = 0x0FFFFFFF;
  39320. this.customShader = null;
  39321. this.preventAutoStart = false;
  39322. /**
  39323. * An event triggered when the system is disposed.
  39324. * @type {BABYLON.Observable}
  39325. */
  39326. this.onDisposeObservable = new BABYLON.Observable();
  39327. this.onAnimationEnd = null;
  39328. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  39329. this.forceDepthWrite = false;
  39330. this.gravity = BABYLON.Vector3.Zero();
  39331. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  39332. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  39333. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  39334. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39335. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39336. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39337. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  39338. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39339. this.particles = new Array();
  39340. this._stockParticles = new Array();
  39341. this._newPartsExcess = 0;
  39342. this._vertexBuffers = {};
  39343. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  39344. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  39345. this._scaledDirection = BABYLON.Vector3.Zero();
  39346. this._scaledGravity = BABYLON.Vector3.Zero();
  39347. this._currentRenderId = -1;
  39348. this._started = false;
  39349. this._stopped = false;
  39350. this._actualFrame = 0;
  39351. this.id = name;
  39352. this._capacity = capacity;
  39353. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  39354. this._customEffect = customEffect;
  39355. scene.particleSystems.push(this);
  39356. var indices = [];
  39357. var index = 0;
  39358. for (var count = 0; count < capacity; count++) {
  39359. indices.push(index);
  39360. indices.push(index + 1);
  39361. indices.push(index + 2);
  39362. indices.push(index);
  39363. indices.push(index + 2);
  39364. indices.push(index + 3);
  39365. index += 4;
  39366. }
  39367. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39368. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  39369. this._vertexData = new Float32Array(capacity * 11 * 4);
  39370. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  39371. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  39372. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  39373. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  39374. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39375. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39376. this._vertexBuffers["options"] = options;
  39377. // Default behaviors
  39378. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  39379. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  39380. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  39381. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  39382. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  39383. };
  39384. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  39385. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  39386. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  39387. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  39388. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  39389. };
  39390. this.updateFunction = function (particles) {
  39391. for (var index = 0; index < particles.length; index++) {
  39392. var particle = particles[index];
  39393. particle.age += _this._scaledUpdateSpeed;
  39394. if (particle.age >= particle.lifeTime) {
  39395. _this.recycleParticle(particle);
  39396. index--;
  39397. continue;
  39398. }
  39399. else {
  39400. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  39401. particle.color.addInPlace(_this._scaledColorStep);
  39402. if (particle.color.a < 0)
  39403. particle.color.a = 0;
  39404. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  39405. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  39406. particle.position.addInPlace(_this._scaledDirection);
  39407. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  39408. particle.direction.addInPlace(_this._scaledGravity);
  39409. }
  39410. }
  39411. };
  39412. }
  39413. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  39414. set: function (callback) {
  39415. if (this._onDisposeObserver) {
  39416. this.onDisposeObservable.remove(this._onDisposeObserver);
  39417. }
  39418. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39419. },
  39420. enumerable: true,
  39421. configurable: true
  39422. });
  39423. ParticleSystem.prototype.recycleParticle = function (particle) {
  39424. var lastParticle = this.particles.pop();
  39425. if (lastParticle !== particle) {
  39426. lastParticle.copyTo(particle);
  39427. this._stockParticles.push(lastParticle);
  39428. }
  39429. };
  39430. ParticleSystem.prototype.getCapacity = function () {
  39431. return this._capacity;
  39432. };
  39433. ParticleSystem.prototype.isAlive = function () {
  39434. return this._alive;
  39435. };
  39436. ParticleSystem.prototype.isStarted = function () {
  39437. return this._started;
  39438. };
  39439. ParticleSystem.prototype.start = function () {
  39440. this._started = true;
  39441. this._stopped = false;
  39442. this._actualFrame = 0;
  39443. };
  39444. ParticleSystem.prototype.stop = function () {
  39445. this._stopped = true;
  39446. };
  39447. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  39448. var offset = index * 11;
  39449. this._vertexData[offset] = particle.position.x;
  39450. this._vertexData[offset + 1] = particle.position.y;
  39451. this._vertexData[offset + 2] = particle.position.z;
  39452. this._vertexData[offset + 3] = particle.color.r;
  39453. this._vertexData[offset + 4] = particle.color.g;
  39454. this._vertexData[offset + 5] = particle.color.b;
  39455. this._vertexData[offset + 6] = particle.color.a;
  39456. this._vertexData[offset + 7] = particle.angle;
  39457. this._vertexData[offset + 8] = particle.size;
  39458. this._vertexData[offset + 9] = offsetX;
  39459. this._vertexData[offset + 10] = offsetY;
  39460. };
  39461. ParticleSystem.prototype._update = function (newParticles) {
  39462. // Update current
  39463. this._alive = this.particles.length > 0;
  39464. this.updateFunction(this.particles);
  39465. // Add new ones
  39466. var worldMatrix;
  39467. if (this.emitter.position) {
  39468. var emitterMesh = this.emitter;
  39469. worldMatrix = emitterMesh.getWorldMatrix();
  39470. }
  39471. else {
  39472. var emitterPosition = this.emitter;
  39473. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  39474. }
  39475. var particle;
  39476. for (var index = 0; index < newParticles; index++) {
  39477. if (this.particles.length === this._capacity) {
  39478. break;
  39479. }
  39480. if (this._stockParticles.length !== 0) {
  39481. particle = this._stockParticles.pop();
  39482. particle.age = 0;
  39483. }
  39484. else {
  39485. particle = new BABYLON.Particle();
  39486. }
  39487. this.particles.push(particle);
  39488. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  39489. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  39490. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  39491. particle.size = randomNumber(this.minSize, this.maxSize);
  39492. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  39493. this.startPositionFunction(worldMatrix, particle.position, particle);
  39494. var step = randomNumber(0, 1.0);
  39495. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  39496. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  39497. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  39498. }
  39499. };
  39500. ParticleSystem.prototype._getEffect = function () {
  39501. if (this._customEffect) {
  39502. return this._customEffect;
  39503. }
  39504. ;
  39505. var defines = [];
  39506. if (this._scene.clipPlane) {
  39507. defines.push("#define CLIPPLANE");
  39508. }
  39509. // Effect
  39510. var join = defines.join("\n");
  39511. if (this._cachedDefines !== join) {
  39512. this._cachedDefines = join;
  39513. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  39514. }
  39515. return this._effect;
  39516. };
  39517. ParticleSystem.prototype.animate = function () {
  39518. if (!this._started)
  39519. return;
  39520. var effect = this._getEffect();
  39521. // Check
  39522. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  39523. return;
  39524. if (this._currentRenderId === this._scene.getRenderId()) {
  39525. return;
  39526. }
  39527. this._currentRenderId = this._scene.getRenderId();
  39528. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  39529. // determine the number of particles we need to create
  39530. var newParticles;
  39531. if (this.manualEmitCount > -1) {
  39532. newParticles = this.manualEmitCount;
  39533. this._newPartsExcess = 0;
  39534. this.manualEmitCount = 0;
  39535. }
  39536. else {
  39537. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  39538. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  39539. }
  39540. if (this._newPartsExcess > 1.0) {
  39541. newParticles += this._newPartsExcess >> 0;
  39542. this._newPartsExcess -= this._newPartsExcess >> 0;
  39543. }
  39544. this._alive = false;
  39545. if (!this._stopped) {
  39546. this._actualFrame += this._scaledUpdateSpeed;
  39547. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  39548. this.stop();
  39549. }
  39550. else {
  39551. newParticles = 0;
  39552. }
  39553. this._update(newParticles);
  39554. // Stopped?
  39555. if (this._stopped) {
  39556. if (!this._alive) {
  39557. this._started = false;
  39558. if (this.onAnimationEnd) {
  39559. this.onAnimationEnd();
  39560. }
  39561. if (this.disposeOnStop) {
  39562. this._scene._toBeDisposed.push(this);
  39563. }
  39564. }
  39565. }
  39566. // Update VBO
  39567. var offset = 0;
  39568. for (var index = 0; index < this.particles.length; index++) {
  39569. var particle = this.particles[index];
  39570. this._appendParticleVertex(offset++, particle, 0, 0);
  39571. this._appendParticleVertex(offset++, particle, 1, 0);
  39572. this._appendParticleVertex(offset++, particle, 1, 1);
  39573. this._appendParticleVertex(offset++, particle, 0, 1);
  39574. }
  39575. this._vertexBuffer.update(this._vertexData);
  39576. };
  39577. ParticleSystem.prototype.render = function () {
  39578. var effect = this._getEffect();
  39579. // Check
  39580. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  39581. return 0;
  39582. var engine = this._scene.getEngine();
  39583. // Render
  39584. engine.enableEffect(effect);
  39585. engine.setState(false);
  39586. var viewMatrix = this._scene.getViewMatrix();
  39587. effect.setTexture("diffuseSampler", this.particleTexture);
  39588. effect.setMatrix("view", viewMatrix);
  39589. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39590. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  39591. if (this._scene.clipPlane) {
  39592. var clipPlane = this._scene.clipPlane;
  39593. var invView = viewMatrix.clone();
  39594. invView.invert();
  39595. effect.setMatrix("invView", invView);
  39596. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39597. }
  39598. // VBOs
  39599. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39600. // Draw order
  39601. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  39602. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  39603. }
  39604. else {
  39605. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39606. }
  39607. if (this.forceDepthWrite) {
  39608. engine.setDepthWrite(true);
  39609. }
  39610. engine.draw(true, 0, this.particles.length * 6);
  39611. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39612. return this.particles.length;
  39613. };
  39614. ParticleSystem.prototype.dispose = function () {
  39615. if (this._vertexBuffer) {
  39616. this._vertexBuffer.dispose();
  39617. this._vertexBuffer = null;
  39618. }
  39619. if (this._indexBuffer) {
  39620. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39621. this._indexBuffer = null;
  39622. }
  39623. if (this.particleTexture) {
  39624. this.particleTexture.dispose();
  39625. this.particleTexture = null;
  39626. }
  39627. // Remove from scene
  39628. var index = this._scene.particleSystems.indexOf(this);
  39629. if (index > -1) {
  39630. this._scene.particleSystems.splice(index, 1);
  39631. }
  39632. // Callback
  39633. this.onDisposeObservable.notifyObservers(this);
  39634. this.onDisposeObservable.clear();
  39635. };
  39636. // Clone
  39637. ParticleSystem.prototype.clone = function (name, newEmitter) {
  39638. var custom = null;
  39639. var program = null;
  39640. if (this.customShader != null) {
  39641. program = this.customShader;
  39642. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  39643. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  39644. }
  39645. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  39646. result.customShader = program;
  39647. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  39648. if (newEmitter === undefined) {
  39649. newEmitter = this.emitter;
  39650. }
  39651. result.emitter = newEmitter;
  39652. if (this.particleTexture) {
  39653. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  39654. }
  39655. if (!this.preventAutoStart) {
  39656. result.start();
  39657. }
  39658. return result;
  39659. };
  39660. ParticleSystem.prototype.serialize = function () {
  39661. var serializationObject = {};
  39662. serializationObject.name = this.name;
  39663. serializationObject.id = this.id;
  39664. // Emitter
  39665. if (this.emitter.position) {
  39666. var emitterMesh = this.emitter;
  39667. serializationObject.emitterId = emitterMesh.id;
  39668. }
  39669. else {
  39670. var emitterPosition = this.emitter;
  39671. serializationObject.emitter = emitterPosition.asArray();
  39672. }
  39673. serializationObject.capacity = this.getCapacity();
  39674. if (this.particleTexture) {
  39675. serializationObject.textureName = this.particleTexture.name;
  39676. }
  39677. // Animations
  39678. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  39679. // Particle system
  39680. serializationObject.minAngularSpeed = this.minAngularSpeed;
  39681. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  39682. serializationObject.minSize = this.minSize;
  39683. serializationObject.maxSize = this.maxSize;
  39684. serializationObject.minEmitPower = this.minEmitPower;
  39685. serializationObject.maxEmitPower = this.maxEmitPower;
  39686. serializationObject.minLifeTime = this.minLifeTime;
  39687. serializationObject.maxLifeTime = this.maxLifeTime;
  39688. serializationObject.emitRate = this.emitRate;
  39689. serializationObject.minEmitBox = this.minEmitBox.asArray();
  39690. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  39691. serializationObject.gravity = this.gravity.asArray();
  39692. serializationObject.direction1 = this.direction1.asArray();
  39693. serializationObject.direction2 = this.direction2.asArray();
  39694. serializationObject.color1 = this.color1.asArray();
  39695. serializationObject.color2 = this.color2.asArray();
  39696. serializationObject.colorDead = this.colorDead.asArray();
  39697. serializationObject.updateSpeed = this.updateSpeed;
  39698. serializationObject.targetStopDuration = this.targetStopDuration;
  39699. serializationObject.textureMask = this.textureMask.asArray();
  39700. serializationObject.blendMode = this.blendMode;
  39701. serializationObject.customShader = this.customShader;
  39702. serializationObject.preventAutoStart = this.preventAutoStart;
  39703. return serializationObject;
  39704. };
  39705. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  39706. var name = parsedParticleSystem.name;
  39707. var custom = null;
  39708. var program = null;
  39709. if (parsedParticleSystem.customShader) {
  39710. program = parsedParticleSystem.customShader;
  39711. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  39712. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  39713. }
  39714. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  39715. particleSystem.customShader = program;
  39716. if (parsedParticleSystem.id) {
  39717. particleSystem.id = parsedParticleSystem.id;
  39718. }
  39719. // Auto start
  39720. if (parsedParticleSystem.preventAutoStart) {
  39721. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  39722. }
  39723. // Texture
  39724. if (parsedParticleSystem.textureName) {
  39725. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  39726. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  39727. }
  39728. // Emitter
  39729. if (parsedParticleSystem.emitterId) {
  39730. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  39731. }
  39732. else {
  39733. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  39734. }
  39735. // Animations
  39736. if (parsedParticleSystem.animations) {
  39737. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  39738. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  39739. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  39740. }
  39741. }
  39742. if (parsedParticleSystem.autoAnimate) {
  39743. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  39744. }
  39745. // Particle system
  39746. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  39747. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  39748. particleSystem.minSize = parsedParticleSystem.minSize;
  39749. particleSystem.maxSize = parsedParticleSystem.maxSize;
  39750. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  39751. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  39752. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  39753. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  39754. particleSystem.emitRate = parsedParticleSystem.emitRate;
  39755. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  39756. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  39757. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  39758. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  39759. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  39760. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  39761. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  39762. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  39763. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  39764. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  39765. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  39766. particleSystem.blendMode = parsedParticleSystem.blendMode;
  39767. if (!particleSystem.preventAutoStart) {
  39768. particleSystem.start();
  39769. }
  39770. return particleSystem;
  39771. };
  39772. return ParticleSystem;
  39773. }());
  39774. // Statics
  39775. ParticleSystem.BLENDMODE_ONEONE = 0;
  39776. ParticleSystem.BLENDMODE_STANDARD = 1;
  39777. BABYLON.ParticleSystem = ParticleSystem;
  39778. })(BABYLON || (BABYLON = {}));
  39779. //# sourceMappingURL=babylon.particleSystem.js.map
  39780. var BABYLON;
  39781. (function (BABYLON) {
  39782. var SolidParticle = (function () {
  39783. /**
  39784. * Creates a Solid Particle object.
  39785. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  39786. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  39787. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  39788. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  39789. * `shapeId` (integer) is the model shape identifier in the SPS.
  39790. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  39791. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  39792. */
  39793. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  39794. this.idx = 0; // particle global index
  39795. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  39796. this.position = BABYLON.Vector3.Zero(); // position
  39797. this.rotation = BABYLON.Vector3.Zero(); // rotation
  39798. this.scaling = BABYLON.Vector3.One(); // scaling
  39799. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  39800. this.velocity = BABYLON.Vector3.Zero(); // velocity
  39801. this.alive = true; // alive
  39802. this.isVisible = true; // visibility
  39803. this._pos = 0; // index of this particle in the global "positions" array
  39804. this.shapeId = 0; // model shape id
  39805. this.idxInShape = 0; // index of the particle in its shape id
  39806. this.idx = particleIndex;
  39807. this._pos = positionIndex;
  39808. this._model = model;
  39809. this.shapeId = shapeId;
  39810. this.idxInShape = idxInShape;
  39811. this._sps = sps;
  39812. if (modelBoundingInfo) {
  39813. this._modelBoundingInfo = modelBoundingInfo;
  39814. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  39815. }
  39816. }
  39817. Object.defineProperty(SolidParticle.prototype, "scale", {
  39818. /**
  39819. * legacy support, changed scale to scaling
  39820. */
  39821. get: function () {
  39822. return this.scaling;
  39823. },
  39824. set: function (scale) {
  39825. this.scaling = scale;
  39826. },
  39827. enumerable: true,
  39828. configurable: true
  39829. });
  39830. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  39831. /**
  39832. * legacy support, changed quaternion to rotationQuaternion
  39833. */
  39834. get: function () {
  39835. return this.rotationQuaternion;
  39836. },
  39837. set: function (q) {
  39838. this.rotationQuaternion = q;
  39839. },
  39840. enumerable: true,
  39841. configurable: true
  39842. });
  39843. /**
  39844. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  39845. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  39846. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  39847. */
  39848. SolidParticle.prototype.intersectsMesh = function (target) {
  39849. if (!this._boundingInfo || !target._boundingInfo) {
  39850. return false;
  39851. }
  39852. if (this._sps._bSphereOnly) {
  39853. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  39854. }
  39855. return this._boundingInfo.intersects(target._boundingInfo, false);
  39856. };
  39857. return SolidParticle;
  39858. }());
  39859. BABYLON.SolidParticle = SolidParticle;
  39860. var ModelShape = (function () {
  39861. /**
  39862. * 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.
  39863. * SPS internal tool, don't use it manually.
  39864. */
  39865. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  39866. this.shapeID = id;
  39867. this._shape = shape;
  39868. this._shapeUV = shapeUV;
  39869. this._positionFunction = posFunction;
  39870. this._vertexFunction = vtxFunction;
  39871. }
  39872. return ModelShape;
  39873. }());
  39874. BABYLON.ModelShape = ModelShape;
  39875. })(BABYLON || (BABYLON = {}));
  39876. //# sourceMappingURL=babylon.solidParticle.js.map
  39877. var BABYLON;
  39878. (function (BABYLON) {
  39879. /**
  39880. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  39881. */
  39882. var SolidParticleSystem = (function () {
  39883. /**
  39884. * Creates a SPS (Solid Particle System) object.
  39885. * `name` (String) is the SPS name, this will be the underlying mesh name.
  39886. * `scene` (Scene) is the scene in which the SPS is added.
  39887. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  39888. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  39889. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  39890. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  39891. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  39892. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  39893. */
  39894. function SolidParticleSystem(name, scene, options) {
  39895. // public members
  39896. /**
  39897. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  39898. * Example : var p = SPS.particles[i];
  39899. */
  39900. this.particles = new Array();
  39901. /**
  39902. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  39903. */
  39904. this.nbParticles = 0;
  39905. /**
  39906. * If the particles must ever face the camera (default false). Useful for planar particles.
  39907. */
  39908. this.billboard = false;
  39909. /**
  39910. * Recompute normals when adding a shape
  39911. */
  39912. this.recomputeNormals = true;
  39913. /**
  39914. * This a counter ofr your own usage. It's not set by any SPS functions.
  39915. */
  39916. this.counter = 0;
  39917. /**
  39918. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  39919. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  39920. */
  39921. this.vars = {};
  39922. this._positions = new Array();
  39923. this._indices = new Array();
  39924. this._normals = new Array();
  39925. this._colors = new Array();
  39926. this._uvs = new Array();
  39927. this._index = 0; // indices index
  39928. this._updatable = true;
  39929. this._pickable = false;
  39930. this._isVisibilityBoxLocked = false;
  39931. this._alwaysVisible = false;
  39932. this._shapeCounter = 0;
  39933. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  39934. this._color = new BABYLON.Color4(0, 0, 0, 0);
  39935. this._computeParticleColor = true;
  39936. this._computeParticleTexture = true;
  39937. this._computeParticleRotation = true;
  39938. this._computeParticleVertex = false;
  39939. this._computeBoundingBox = false;
  39940. this._cam_axisZ = BABYLON.Vector3.Zero();
  39941. this._cam_axisY = BABYLON.Vector3.Zero();
  39942. this._cam_axisX = BABYLON.Vector3.Zero();
  39943. this._axisX = BABYLON.Axis.X;
  39944. this._axisY = BABYLON.Axis.Y;
  39945. this._axisZ = BABYLON.Axis.Z;
  39946. this._camDir = BABYLON.Vector3.Zero();
  39947. this._rotMatrix = new BABYLON.Matrix();
  39948. this._invertMatrix = new BABYLON.Matrix();
  39949. this._rotated = BABYLON.Vector3.Zero();
  39950. this._quaternion = new BABYLON.Quaternion();
  39951. this._vertex = BABYLON.Vector3.Zero();
  39952. this._normal = BABYLON.Vector3.Zero();
  39953. this._yaw = 0.0;
  39954. this._pitch = 0.0;
  39955. this._roll = 0.0;
  39956. this._halfroll = 0.0;
  39957. this._halfpitch = 0.0;
  39958. this._halfyaw = 0.0;
  39959. this._sinRoll = 0.0;
  39960. this._cosRoll = 0.0;
  39961. this._sinPitch = 0.0;
  39962. this._cosPitch = 0.0;
  39963. this._sinYaw = 0.0;
  39964. this._cosYaw = 0.0;
  39965. this._w = 0.0;
  39966. this._mustUnrotateFixedNormals = false;
  39967. this._minimum = BABYLON.Tmp.Vector3[0];
  39968. this._maximum = BABYLON.Tmp.Vector3[1];
  39969. this._scale = BABYLON.Tmp.Vector3[2];
  39970. this._translation = BABYLON.Tmp.Vector3[3];
  39971. this._minBbox = BABYLON.Tmp.Vector3[4];
  39972. this._maxBbox = BABYLON.Tmp.Vector3[5];
  39973. this._particlesIntersect = false;
  39974. this._bSphereOnly = false;
  39975. this._bSphereRadiusFactor = 1.0;
  39976. this.name = name;
  39977. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  39978. this._camera = scene.activeCamera;
  39979. this._pickable = options ? options.isPickable : false;
  39980. this._particlesIntersect = options ? options.particleIntersection : false;
  39981. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  39982. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  39983. if (options && options.updatable) {
  39984. this._updatable = options.updatable;
  39985. }
  39986. else {
  39987. this._updatable = true;
  39988. }
  39989. if (this._pickable) {
  39990. this.pickedParticles = [];
  39991. }
  39992. }
  39993. /**
  39994. * Builds the SPS underlying mesh. Returns a standard Mesh.
  39995. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  39996. */
  39997. SolidParticleSystem.prototype.buildMesh = function () {
  39998. if (this.nbParticles === 0) {
  39999. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  40000. this.addShape(triangle, 1);
  40001. triangle.dispose();
  40002. }
  40003. this._positions32 = new Float32Array(this._positions);
  40004. this._uvs32 = new Float32Array(this._uvs);
  40005. this._colors32 = new Float32Array(this._colors);
  40006. if (this.recomputeNormals) {
  40007. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  40008. }
  40009. this._normals32 = new Float32Array(this._normals);
  40010. this._fixedNormal32 = new Float32Array(this._normals);
  40011. if (this._mustUnrotateFixedNormals) {
  40012. this._unrotateFixedNormals();
  40013. }
  40014. var vertexData = new BABYLON.VertexData();
  40015. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40016. vertexData.indices = this._indices;
  40017. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40018. if (this._uvs32) {
  40019. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  40020. ;
  40021. }
  40022. if (this._colors32) {
  40023. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  40024. }
  40025. var mesh = new BABYLON.Mesh(this.name, this._scene);
  40026. vertexData.applyToMesh(mesh, this._updatable);
  40027. this.mesh = mesh;
  40028. this.mesh.isPickable = this._pickable;
  40029. // free memory
  40030. this._positions = null;
  40031. this._normals = null;
  40032. this._uvs = null;
  40033. this._colors = null;
  40034. if (!this._updatable) {
  40035. this.particles.length = 0;
  40036. }
  40037. return mesh;
  40038. };
  40039. /**
  40040. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  40041. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  40042. * Thus the particles generated from `digest()` have their property `position` set yet.
  40043. * `mesh` ( Mesh ) is the mesh to be digested
  40044. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  40045. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  40046. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  40047. */
  40048. SolidParticleSystem.prototype.digest = function (mesh, options) {
  40049. var size = (options && options.facetNb) || 1;
  40050. var number = (options && options.number);
  40051. var delta = (options && options.delta) || 0;
  40052. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40053. var meshInd = mesh.getIndices();
  40054. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40055. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40056. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40057. var f = 0; // facet counter
  40058. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  40059. // compute size from number
  40060. if (number) {
  40061. number = (number > totalFacets) ? totalFacets : number;
  40062. size = Math.round(totalFacets / number);
  40063. delta = 0;
  40064. }
  40065. else {
  40066. size = (size > totalFacets) ? totalFacets : size;
  40067. }
  40068. var facetPos = []; // submesh positions
  40069. var facetInd = []; // submesh indices
  40070. var facetUV = []; // submesh UV
  40071. var facetCol = []; // submesh colors
  40072. var barycenter = BABYLON.Tmp.Vector3[0];
  40073. var rand;
  40074. var sizeO = size;
  40075. while (f < totalFacets) {
  40076. size = sizeO + Math.floor((1 + delta) * Math.random());
  40077. if (f > totalFacets - size) {
  40078. size = totalFacets - f;
  40079. }
  40080. // reset temp arrays
  40081. facetPos.length = 0;
  40082. facetInd.length = 0;
  40083. facetUV.length = 0;
  40084. facetCol.length = 0;
  40085. // iterate over "size" facets
  40086. var fi = 0;
  40087. for (var j = f * 3; j < (f + size) * 3; j++) {
  40088. facetInd.push(fi);
  40089. var i = meshInd[j];
  40090. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  40091. if (meshUV) {
  40092. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  40093. }
  40094. if (meshCol) {
  40095. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  40096. }
  40097. fi++;
  40098. }
  40099. // create a model shape for each single particle
  40100. var idx = this.nbParticles;
  40101. var shape = this._posToShape(facetPos);
  40102. var shapeUV = this._uvsToShapeUV(facetUV);
  40103. // compute the barycenter of the shape
  40104. var v;
  40105. for (v = 0; v < shape.length; v++) {
  40106. barycenter.addInPlace(shape[v]);
  40107. }
  40108. barycenter.scaleInPlace(1 / shape.length);
  40109. // shift the shape from its barycenter to the origin
  40110. for (v = 0; v < shape.length; v++) {
  40111. shape[v].subtractInPlace(barycenter);
  40112. }
  40113. var bInfo;
  40114. if (this._particlesIntersect) {
  40115. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  40116. }
  40117. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  40118. // add the particle in the SPS
  40119. var currentPos = this._positions.length;
  40120. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  40121. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  40122. // initialize the particle position
  40123. this.particles[this.nbParticles].position.addInPlace(barycenter);
  40124. this._index += shape.length;
  40125. idx++;
  40126. this.nbParticles++;
  40127. this._shapeCounter++;
  40128. f += size;
  40129. }
  40130. return this;
  40131. };
  40132. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  40133. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  40134. var index = 0;
  40135. var idx = 0;
  40136. for (var p = 0; p < this.particles.length; p++) {
  40137. this._particle = this.particles[p];
  40138. this._shape = this._particle._model._shape;
  40139. if (this._particle.rotationQuaternion) {
  40140. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40141. }
  40142. else {
  40143. this._yaw = this._particle.rotation.y;
  40144. this._pitch = this._particle.rotation.x;
  40145. this._roll = this._particle.rotation.z;
  40146. this._quaternionRotationYPR();
  40147. }
  40148. this._quaternionToRotationMatrix();
  40149. this._rotMatrix.invertToRef(this._invertMatrix);
  40150. for (var pt = 0; pt < this._shape.length; pt++) {
  40151. idx = index + pt * 3;
  40152. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  40153. this._fixedNormal32[idx] = this._normal.x;
  40154. this._fixedNormal32[idx + 1] = this._normal.y;
  40155. this._fixedNormal32[idx + 2] = this._normal.z;
  40156. }
  40157. index = idx + 3;
  40158. }
  40159. };
  40160. //reset copy
  40161. SolidParticleSystem.prototype._resetCopy = function () {
  40162. this._copy.position.x = 0;
  40163. this._copy.position.y = 0;
  40164. this._copy.position.z = 0;
  40165. this._copy.rotation.x = 0;
  40166. this._copy.rotation.y = 0;
  40167. this._copy.rotation.z = 0;
  40168. this._copy.rotationQuaternion = null;
  40169. this._copy.scaling.x = 1;
  40170. this._copy.scaling.y = 1;
  40171. this._copy.scaling.z = 1;
  40172. this._copy.uvs.x = 0;
  40173. this._copy.uvs.y = 0;
  40174. this._copy.uvs.z = 1;
  40175. this._copy.uvs.w = 1;
  40176. this._copy.color = null;
  40177. };
  40178. // _meshBuilder : inserts the shape model in the global SPS mesh
  40179. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  40180. var i;
  40181. var u = 0;
  40182. var c = 0;
  40183. var n = 0;
  40184. this._resetCopy();
  40185. if (options && options.positionFunction) {
  40186. options.positionFunction(this._copy, idx, idxInShape);
  40187. this._mustUnrotateFixedNormals = true;
  40188. }
  40189. if (this._copy.rotationQuaternion) {
  40190. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  40191. }
  40192. else {
  40193. this._yaw = this._copy.rotation.y;
  40194. this._pitch = this._copy.rotation.x;
  40195. this._roll = this._copy.rotation.z;
  40196. this._quaternionRotationYPR();
  40197. }
  40198. this._quaternionToRotationMatrix();
  40199. for (i = 0; i < shape.length; i++) {
  40200. this._vertex.x = shape[i].x;
  40201. this._vertex.y = shape[i].y;
  40202. this._vertex.z = shape[i].z;
  40203. if (options && options.vertexFunction) {
  40204. options.vertexFunction(this._copy, this._vertex, i);
  40205. }
  40206. this._vertex.x *= this._copy.scaling.x;
  40207. this._vertex.y *= this._copy.scaling.y;
  40208. this._vertex.z *= this._copy.scaling.z;
  40209. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40210. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  40211. if (meshUV) {
  40212. 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);
  40213. u += 2;
  40214. }
  40215. if (this._copy.color) {
  40216. this._color = this._copy.color;
  40217. }
  40218. else if (meshCol && meshCol[c] !== undefined) {
  40219. this._color.r = meshCol[c];
  40220. this._color.g = meshCol[c + 1];
  40221. this._color.b = meshCol[c + 2];
  40222. this._color.a = meshCol[c + 3];
  40223. }
  40224. else {
  40225. this._color.r = 1;
  40226. this._color.g = 1;
  40227. this._color.b = 1;
  40228. this._color.a = 1;
  40229. }
  40230. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  40231. c += 4;
  40232. if (!this.recomputeNormals && meshNor) {
  40233. this._normal.x = meshNor[n];
  40234. this._normal.y = meshNor[n + 1];
  40235. this._normal.z = meshNor[n + 2];
  40236. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  40237. normals.push(this._normal.x, this._normal.y, this._normal.z);
  40238. n += 3;
  40239. }
  40240. }
  40241. for (i = 0; i < meshInd.length; i++) {
  40242. indices.push(p + meshInd[i]);
  40243. }
  40244. if (this._pickable) {
  40245. var nbfaces = meshInd.length / 3;
  40246. for (i = 0; i < nbfaces; i++) {
  40247. this.pickedParticles.push({ idx: idx, faceId: i });
  40248. }
  40249. }
  40250. return this._copy;
  40251. };
  40252. // returns a shape array from positions array
  40253. SolidParticleSystem.prototype._posToShape = function (positions) {
  40254. var shape = [];
  40255. for (var i = 0; i < positions.length; i += 3) {
  40256. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  40257. }
  40258. return shape;
  40259. };
  40260. // returns a shapeUV array from a Vector4 uvs
  40261. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  40262. var shapeUV = [];
  40263. if (uvs) {
  40264. for (var i = 0; i < uvs.length; i++)
  40265. shapeUV.push(uvs[i]);
  40266. }
  40267. return shapeUV;
  40268. };
  40269. // adds a new particle object in the particles array
  40270. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  40271. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  40272. this.particles.push(sp);
  40273. return sp;
  40274. };
  40275. /**
  40276. * Adds some particles to the SPS from the model shape. Returns the shape id.
  40277. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  40278. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  40279. * `nb` (positive integer) the number of particles to be created from this model
  40280. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  40281. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  40282. */
  40283. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  40284. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40285. var meshInd = mesh.getIndices();
  40286. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40287. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40288. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40289. var bbInfo;
  40290. if (this._particlesIntersect) {
  40291. bbInfo = mesh.getBoundingInfo();
  40292. }
  40293. var shape = this._posToShape(meshPos);
  40294. var shapeUV = this._uvsToShapeUV(meshUV);
  40295. var posfunc = options ? options.positionFunction : null;
  40296. var vtxfunc = options ? options.vertexFunction : null;
  40297. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  40298. // particles
  40299. var sp;
  40300. var currentCopy;
  40301. var idx = this.nbParticles;
  40302. for (var i = 0; i < nb; i++) {
  40303. var currentPos = this._positions.length;
  40304. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  40305. if (this._updatable) {
  40306. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  40307. sp.position.copyFrom(currentCopy.position);
  40308. sp.rotation.copyFrom(currentCopy.rotation);
  40309. if (currentCopy.rotationQuaternion) {
  40310. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  40311. }
  40312. if (currentCopy.color) {
  40313. sp.color.copyFrom(currentCopy.color);
  40314. }
  40315. sp.scaling.copyFrom(currentCopy.scaling);
  40316. sp.uvs.copyFrom(currentCopy.uvs);
  40317. }
  40318. this._index += shape.length;
  40319. idx++;
  40320. }
  40321. this.nbParticles += nb;
  40322. this._shapeCounter++;
  40323. return this._shapeCounter - 1;
  40324. };
  40325. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  40326. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  40327. this._resetCopy();
  40328. if (particle._model._positionFunction) {
  40329. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  40330. }
  40331. if (this._copy.rotationQuaternion) {
  40332. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  40333. }
  40334. else {
  40335. this._yaw = this._copy.rotation.y;
  40336. this._pitch = this._copy.rotation.x;
  40337. this._roll = this._copy.rotation.z;
  40338. this._quaternionRotationYPR();
  40339. }
  40340. this._quaternionToRotationMatrix();
  40341. this._shape = particle._model._shape;
  40342. for (var pt = 0; pt < this._shape.length; pt++) {
  40343. this._vertex.x = this._shape[pt].x;
  40344. this._vertex.y = this._shape[pt].y;
  40345. this._vertex.z = this._shape[pt].z;
  40346. if (particle._model._vertexFunction) {
  40347. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  40348. }
  40349. this._vertex.x *= this._copy.scaling.x;
  40350. this._vertex.y *= this._copy.scaling.y;
  40351. this._vertex.z *= this._copy.scaling.z;
  40352. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40353. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  40354. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  40355. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  40356. }
  40357. particle.position.x = 0.0;
  40358. particle.position.y = 0.0;
  40359. particle.position.z = 0.0;
  40360. particle.rotation.x = 0.0;
  40361. particle.rotation.y = 0.0;
  40362. particle.rotation.z = 0.0;
  40363. particle.rotationQuaternion = null;
  40364. particle.scaling.x = 1.0;
  40365. particle.scaling.y = 1.0;
  40366. particle.scaling.z = 1.0;
  40367. };
  40368. /**
  40369. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  40370. * Returns the SPS.
  40371. */
  40372. SolidParticleSystem.prototype.rebuildMesh = function () {
  40373. for (var p = 0; p < this.particles.length; p++) {
  40374. this._rebuildParticle(this.particles[p]);
  40375. }
  40376. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40377. return this;
  40378. };
  40379. /**
  40380. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  40381. * This method calls `updateParticle()` for each particle of the SPS.
  40382. * For an animated SPS, it is usually called within the render loop.
  40383. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  40384. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  40385. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  40386. * Returns the SPS.
  40387. */
  40388. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  40389. if (start === void 0) { start = 0; }
  40390. if (end === void 0) { end = this.nbParticles - 1; }
  40391. if (update === void 0) { update = true; }
  40392. if (!this._updatable) {
  40393. return;
  40394. }
  40395. // custom beforeUpdate
  40396. this.beforeUpdateParticles(start, end, update);
  40397. this._cam_axisX.x = 1.0;
  40398. this._cam_axisX.y = 0.0;
  40399. this._cam_axisX.z = 0.0;
  40400. this._cam_axisY.x = 0.0;
  40401. this._cam_axisY.y = 1.0;
  40402. this._cam_axisY.z = 0.0;
  40403. this._cam_axisZ.x = 0.0;
  40404. this._cam_axisZ.y = 0.0;
  40405. this._cam_axisZ.z = 1.0;
  40406. // if the particles will always face the camera
  40407. if (this.billboard) {
  40408. this.mesh.computeWorldMatrix(true);
  40409. // compute the camera position and un-rotate it by the current mesh rotation
  40410. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  40411. this._quaternionToRotationMatrix();
  40412. this._rotMatrix.invertToRef(this._invertMatrix);
  40413. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  40414. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  40415. this._cam_axisZ.normalize();
  40416. // same for camera up vector extracted from the cam view matrix
  40417. var view = this._camera.getViewMatrix(true);
  40418. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  40419. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  40420. this._cam_axisY.normalize();
  40421. this._cam_axisX.normalize();
  40422. }
  40423. }
  40424. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  40425. var idx = 0; // current position index in the global array positions32
  40426. var index = 0; // position start index in the global array positions32 of the current particle
  40427. var colidx = 0; // current color index in the global array colors32
  40428. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  40429. var uvidx = 0; // current uv index in the global array uvs32
  40430. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  40431. var pt = 0; // current index in the particle model shape
  40432. if (this.mesh.isFacetDataEnabled) {
  40433. this._computeBoundingBox = true;
  40434. }
  40435. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  40436. if (this._computeBoundingBox) {
  40437. if (start == 0 && end == this.nbParticles - 1) {
  40438. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  40439. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  40440. }
  40441. else {
  40442. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  40443. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  40444. }
  40445. }
  40446. // particle loop
  40447. index = this.particles[start]._pos;
  40448. var vpos = (index / 3) | 0;
  40449. colorIndex = vpos * 4;
  40450. uvIndex = vpos * 2;
  40451. for (var p = start; p <= end; p++) {
  40452. this._particle = this.particles[p];
  40453. this._shape = this._particle._model._shape;
  40454. this._shapeUV = this._particle._model._shapeUV;
  40455. // call to custom user function to update the particle properties
  40456. this.updateParticle(this._particle);
  40457. if (this._particle.isVisible) {
  40458. // particle rotation matrix
  40459. if (this.billboard) {
  40460. this._particle.rotation.x = 0.0;
  40461. this._particle.rotation.y = 0.0;
  40462. }
  40463. if (this._computeParticleRotation || this.billboard) {
  40464. if (this._particle.rotationQuaternion) {
  40465. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40466. }
  40467. else {
  40468. this._yaw = this._particle.rotation.y;
  40469. this._pitch = this._particle.rotation.x;
  40470. this._roll = this._particle.rotation.z;
  40471. this._quaternionRotationYPR();
  40472. }
  40473. this._quaternionToRotationMatrix();
  40474. }
  40475. // particle vertex loop
  40476. for (pt = 0; pt < this._shape.length; pt++) {
  40477. idx = index + pt * 3;
  40478. colidx = colorIndex + pt * 4;
  40479. uvidx = uvIndex + pt * 2;
  40480. this._vertex.x = this._shape[pt].x;
  40481. this._vertex.y = this._shape[pt].y;
  40482. this._vertex.z = this._shape[pt].z;
  40483. if (this._computeParticleVertex) {
  40484. this.updateParticleVertex(this._particle, this._vertex, pt);
  40485. }
  40486. // positions
  40487. this._vertex.x *= this._particle.scaling.x;
  40488. this._vertex.y *= this._particle.scaling.y;
  40489. this._vertex.z *= this._particle.scaling.z;
  40490. 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];
  40491. 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;
  40492. 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;
  40493. 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;
  40494. 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;
  40495. 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;
  40496. 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;
  40497. if (this._computeBoundingBox) {
  40498. if (this._positions32[idx] < this._minimum.x) {
  40499. this._minimum.x = this._positions32[idx];
  40500. }
  40501. if (this._positions32[idx] > this._maximum.x) {
  40502. this._maximum.x = this._positions32[idx];
  40503. }
  40504. if (this._positions32[idx + 1] < this._minimum.y) {
  40505. this._minimum.y = this._positions32[idx + 1];
  40506. }
  40507. if (this._positions32[idx + 1] > this._maximum.y) {
  40508. this._maximum.y = this._positions32[idx + 1];
  40509. }
  40510. if (this._positions32[idx + 2] < this._minimum.z) {
  40511. this._minimum.z = this._positions32[idx + 2];
  40512. }
  40513. if (this._positions32[idx + 2] > this._maximum.z) {
  40514. this._maximum.z = this._positions32[idx + 2];
  40515. }
  40516. }
  40517. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  40518. if (!this._computeParticleVertex) {
  40519. this._normal.x = this._fixedNormal32[idx];
  40520. this._normal.y = this._fixedNormal32[idx + 1];
  40521. this._normal.z = this._fixedNormal32[idx + 2];
  40522. 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]);
  40523. 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]);
  40524. 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]);
  40525. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  40526. 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;
  40527. 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;
  40528. }
  40529. if (this._computeParticleColor) {
  40530. this._colors32[colidx] = this._particle.color.r;
  40531. this._colors32[colidx + 1] = this._particle.color.g;
  40532. this._colors32[colidx + 2] = this._particle.color.b;
  40533. this._colors32[colidx + 3] = this._particle.color.a;
  40534. }
  40535. if (this._computeParticleTexture) {
  40536. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40537. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40538. }
  40539. }
  40540. }
  40541. else {
  40542. for (pt = 0; pt < this._shape.length; pt++) {
  40543. idx = index + pt * 3;
  40544. colidx = colorIndex + pt * 4;
  40545. uvidx = uvIndex + pt * 2;
  40546. this._positions32[idx] = this._camera.globalPosition.x;
  40547. this._positions32[idx + 1] = this._camera.globalPosition.y;
  40548. this._positions32[idx + 2] = this._camera.globalPosition.z;
  40549. this._normals32[idx] = 0.0;
  40550. this._normals32[idx + 1] = 0.0;
  40551. this._normals32[idx + 2] = 0.0;
  40552. if (this._computeParticleColor) {
  40553. this._colors32[colidx] = this._particle.color.r;
  40554. this._colors32[colidx + 1] = this._particle.color.g;
  40555. this._colors32[colidx + 2] = this._particle.color.b;
  40556. this._colors32[colidx + 3] = this._particle.color.a;
  40557. }
  40558. if (this._computeParticleTexture) {
  40559. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40560. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40561. }
  40562. }
  40563. }
  40564. // if the particle intersections must be computed : update the bbInfo
  40565. if (this._particlesIntersect) {
  40566. var bInfo = this._particle._boundingInfo;
  40567. var bBox = bInfo.boundingBox;
  40568. var bSphere = bInfo.boundingSphere;
  40569. if (!this._bSphereOnly) {
  40570. // place, scale and rotate the particle bbox within the SPS local system, then update it
  40571. for (var b = 0; b < bBox.vectors.length; b++) {
  40572. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  40573. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  40574. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  40575. 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];
  40576. 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;
  40577. 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;
  40578. 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;
  40579. 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;
  40580. 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;
  40581. 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;
  40582. }
  40583. bBox._update(this.mesh._worldMatrix);
  40584. }
  40585. // place and scale the particle bouding sphere in the SPS local system, then update it
  40586. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  40587. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  40588. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  40589. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  40590. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  40591. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  40592. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  40593. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  40594. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  40595. 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));
  40596. bSphere._update(this.mesh._worldMatrix);
  40597. }
  40598. // increment indexes for the next particle
  40599. index = idx + 3;
  40600. colorIndex = colidx + 4;
  40601. uvIndex = uvidx + 2;
  40602. }
  40603. // if the VBO must be updated
  40604. if (update) {
  40605. if (this._computeParticleColor) {
  40606. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  40607. }
  40608. if (this._computeParticleTexture) {
  40609. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  40610. }
  40611. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40612. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  40613. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  40614. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  40615. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  40616. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  40617. for (var i = 0; i < this._normals32.length; i++) {
  40618. this._fixedNormal32[i] = this._normals32[i];
  40619. }
  40620. }
  40621. if (!this.mesh.areNormalsFrozen) {
  40622. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  40623. }
  40624. }
  40625. }
  40626. if (this._computeBoundingBox) {
  40627. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  40628. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  40629. }
  40630. this.afterUpdateParticles(start, end, update);
  40631. return this;
  40632. };
  40633. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  40634. this._halfroll = this._roll * 0.5;
  40635. this._halfpitch = this._pitch * 0.5;
  40636. this._halfyaw = this._yaw * 0.5;
  40637. this._sinRoll = Math.sin(this._halfroll);
  40638. this._cosRoll = Math.cos(this._halfroll);
  40639. this._sinPitch = Math.sin(this._halfpitch);
  40640. this._cosPitch = Math.cos(this._halfpitch);
  40641. this._sinYaw = Math.sin(this._halfyaw);
  40642. this._cosYaw = Math.cos(this._halfyaw);
  40643. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  40644. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  40645. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  40646. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  40647. };
  40648. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  40649. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  40650. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  40651. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  40652. this._rotMatrix.m[3] = 0;
  40653. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  40654. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  40655. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  40656. this._rotMatrix.m[7] = 0;
  40657. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  40658. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  40659. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  40660. this._rotMatrix.m[11] = 0;
  40661. this._rotMatrix.m[12] = 0;
  40662. this._rotMatrix.m[13] = 0;
  40663. this._rotMatrix.m[14] = 0;
  40664. this._rotMatrix.m[15] = 1.0;
  40665. };
  40666. /**
  40667. * Disposes the SPS.
  40668. * Returns nothing.
  40669. */
  40670. SolidParticleSystem.prototype.dispose = function () {
  40671. this.mesh.dispose();
  40672. this.vars = null;
  40673. // drop references to internal big arrays for the GC
  40674. this._positions = null;
  40675. this._indices = null;
  40676. this._normals = null;
  40677. this._uvs = null;
  40678. this._colors = null;
  40679. this._positions32 = null;
  40680. this._normals32 = null;
  40681. this._fixedNormal32 = null;
  40682. this._uvs32 = null;
  40683. this._colors32 = null;
  40684. this.pickedParticles = null;
  40685. };
  40686. /**
  40687. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  40688. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40689. * Returns the SPS.
  40690. */
  40691. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  40692. if (!this._isVisibilityBoxLocked) {
  40693. this.mesh.refreshBoundingInfo();
  40694. }
  40695. return this;
  40696. };
  40697. /**
  40698. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  40699. * @param size the size (float) of the visibility box
  40700. * note : this doesn't lock the SPS mesh bounding box.
  40701. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40702. */
  40703. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  40704. var vis = size / 2;
  40705. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  40706. };
  40707. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  40708. // getter and setter
  40709. get: function () {
  40710. return this._alwaysVisible;
  40711. },
  40712. /**
  40713. * Sets the SPS as always visible or not
  40714. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40715. */
  40716. set: function (val) {
  40717. this._alwaysVisible = val;
  40718. this.mesh.alwaysSelectAsActiveMesh = val;
  40719. },
  40720. enumerable: true,
  40721. configurable: true
  40722. });
  40723. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  40724. get: function () {
  40725. return this._isVisibilityBoxLocked;
  40726. },
  40727. /**
  40728. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  40729. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  40730. */
  40731. set: function (val) {
  40732. this._isVisibilityBoxLocked = val;
  40733. this.mesh.getBoundingInfo().isLocked = val;
  40734. },
  40735. enumerable: true,
  40736. configurable: true
  40737. });
  40738. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  40739. // getters
  40740. get: function () {
  40741. return this._computeParticleRotation;
  40742. },
  40743. // Optimizer setters
  40744. /**
  40745. * Tells to `setParticles()` to compute the particle rotations or not.
  40746. * Default value : true. The SPS is faster when it's set to false.
  40747. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  40748. */
  40749. set: function (val) {
  40750. this._computeParticleRotation = val;
  40751. },
  40752. enumerable: true,
  40753. configurable: true
  40754. });
  40755. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  40756. get: function () {
  40757. return this._computeParticleColor;
  40758. },
  40759. /**
  40760. * Tells to `setParticles()` to compute the particle colors or not.
  40761. * Default value : true. The SPS is faster when it's set to false.
  40762. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  40763. */
  40764. set: function (val) {
  40765. this._computeParticleColor = val;
  40766. },
  40767. enumerable: true,
  40768. configurable: true
  40769. });
  40770. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  40771. get: function () {
  40772. return this._computeParticleTexture;
  40773. },
  40774. /**
  40775. * Tells to `setParticles()` to compute the particle textures or not.
  40776. * Default value : true. The SPS is faster when it's set to false.
  40777. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  40778. */
  40779. set: function (val) {
  40780. this._computeParticleTexture = val;
  40781. },
  40782. enumerable: true,
  40783. configurable: true
  40784. });
  40785. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  40786. get: function () {
  40787. return this._computeParticleVertex;
  40788. },
  40789. /**
  40790. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  40791. * Default value : false. The SPS is faster when it's set to false.
  40792. * Note : the particle custom vertex positions aren't stored values.
  40793. */
  40794. set: function (val) {
  40795. this._computeParticleVertex = val;
  40796. },
  40797. enumerable: true,
  40798. configurable: true
  40799. });
  40800. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  40801. get: function () {
  40802. return this._computeBoundingBox;
  40803. },
  40804. /**
  40805. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  40806. */
  40807. set: function (val) {
  40808. this._computeBoundingBox = val;
  40809. },
  40810. enumerable: true,
  40811. configurable: true
  40812. });
  40813. // =======================================================================
  40814. // Particle behavior logic
  40815. // these following methods may be overwritten by the user to fit his needs
  40816. /**
  40817. * This function does nothing. It may be overwritten to set all the particle first values.
  40818. * The SPS doesn't call this function, you may have to call it by your own.
  40819. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  40820. */
  40821. SolidParticleSystem.prototype.initParticles = function () {
  40822. };
  40823. /**
  40824. * This function does nothing. It may be overwritten to recycle a particle.
  40825. * The SPS doesn't call this function, you may have to call it by your own.
  40826. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  40827. */
  40828. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  40829. return particle;
  40830. };
  40831. /**
  40832. * Updates a particle : this function should be overwritten by the user.
  40833. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  40834. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  40835. * ex : just set a particle position or velocity and recycle conditions
  40836. */
  40837. SolidParticleSystem.prototype.updateParticle = function (particle) {
  40838. return particle;
  40839. };
  40840. /**
  40841. * Updates a vertex of a particle : it can be overwritten by the user.
  40842. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  40843. * @param particle the current particle
  40844. * @param vertex the current index of the current particle
  40845. * @param pt the index of the current vertex in the particle shape
  40846. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  40847. * ex : just set a vertex particle position
  40848. */
  40849. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  40850. return vertex;
  40851. };
  40852. /**
  40853. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  40854. * This does nothing and may be overwritten by the user.
  40855. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40856. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40857. * @param update the boolean update value actually passed to setParticles()
  40858. */
  40859. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  40860. };
  40861. /**
  40862. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  40863. * This will be passed three parameters.
  40864. * This does nothing and may be overwritten by the user.
  40865. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40866. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  40867. * @param update the boolean update value actually passed to setParticles()
  40868. */
  40869. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  40870. };
  40871. return SolidParticleSystem;
  40872. }());
  40873. BABYLON.SolidParticleSystem = SolidParticleSystem;
  40874. })(BABYLON || (BABYLON = {}));
  40875. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  40876. /// <reference path="babylon.mesh.ts" />
  40877. var BABYLON;
  40878. (function (BABYLON) {
  40879. var GroundMesh = (function (_super) {
  40880. __extends(GroundMesh, _super);
  40881. function GroundMesh(name, scene) {
  40882. var _this = _super.call(this, name, scene) || this;
  40883. _this.generateOctree = false;
  40884. _this._worldInverse = new BABYLON.Matrix();
  40885. return _this;
  40886. }
  40887. GroundMesh.prototype.getClassName = function () {
  40888. return "GroundMesh";
  40889. };
  40890. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  40891. get: function () {
  40892. return Math.min(this._subdivisionsX, this._subdivisionsY);
  40893. },
  40894. enumerable: true,
  40895. configurable: true
  40896. });
  40897. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  40898. get: function () {
  40899. return this._subdivisionsX;
  40900. },
  40901. enumerable: true,
  40902. configurable: true
  40903. });
  40904. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  40905. get: function () {
  40906. return this._subdivisionsY;
  40907. },
  40908. enumerable: true,
  40909. configurable: true
  40910. });
  40911. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  40912. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  40913. this._subdivisionsX = chunksCount;
  40914. this._subdivisionsY = chunksCount;
  40915. this.subdivide(chunksCount);
  40916. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  40917. };
  40918. /**
  40919. * Returns a height (y) value in the Worl system :
  40920. * the ground altitude at the coordinates (x, z) expressed in the World system.
  40921. * Returns the ground y position if (x, z) are outside the ground surface.
  40922. */
  40923. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  40924. var world = this.getWorldMatrix();
  40925. var invMat = BABYLON.Tmp.Matrix[5];
  40926. world.invertToRef(invMat);
  40927. var tmpVect = BABYLON.Tmp.Vector3[8];
  40928. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  40929. x = tmpVect.x;
  40930. z = tmpVect.z;
  40931. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40932. return this.position.y;
  40933. }
  40934. if (!this._heightQuads || this._heightQuads.length == 0) {
  40935. this._initHeightQuads();
  40936. this._computeHeightQuads();
  40937. }
  40938. var facet = this._getFacetAt(x, z);
  40939. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  40940. // return y in the World system
  40941. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  40942. return tmpVect.y;
  40943. };
  40944. /**
  40945. * Returns a normalized vector (Vector3) orthogonal to the ground
  40946. * at the ground coordinates (x, z) expressed in the World system.
  40947. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  40948. */
  40949. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  40950. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  40951. this.getNormalAtCoordinatesToRef(x, z, normal);
  40952. return normal;
  40953. };
  40954. /**
  40955. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40956. * at the ground coordinates (x, z) expressed in the World system.
  40957. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40958. * Returns the GroundMesh.
  40959. */
  40960. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40961. var world = this.getWorldMatrix();
  40962. var tmpMat = BABYLON.Tmp.Matrix[5];
  40963. world.invertToRef(tmpMat);
  40964. var tmpVect = BABYLON.Tmp.Vector3[8];
  40965. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40966. x = tmpVect.x;
  40967. z = tmpVect.z;
  40968. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40969. return this;
  40970. }
  40971. if (!this._heightQuads || this._heightQuads.length == 0) {
  40972. this._initHeightQuads();
  40973. this._computeHeightQuads();
  40974. }
  40975. var facet = this._getFacetAt(x, z);
  40976. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40977. return this;
  40978. };
  40979. /**
  40980. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40981. * if the ground has been updated.
  40982. * This can be used in the render loop.
  40983. * Returns the GroundMesh.
  40984. */
  40985. GroundMesh.prototype.updateCoordinateHeights = function () {
  40986. if (!this._heightQuads || this._heightQuads.length == 0) {
  40987. this._initHeightQuads();
  40988. }
  40989. this._computeHeightQuads();
  40990. return this;
  40991. };
  40992. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40993. GroundMesh.prototype._getFacetAt = function (x, z) {
  40994. // retrieve col and row from x, z coordinates in the ground local system
  40995. var subdivisionsX = this._subdivisionsX;
  40996. var subdivisionsY = this._subdivisionsY;
  40997. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  40998. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  40999. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41000. var facet;
  41001. if (z < quad.slope.x * x + quad.slope.y) {
  41002. facet = quad.facet1;
  41003. }
  41004. else {
  41005. facet = quad.facet2;
  41006. }
  41007. return facet;
  41008. };
  41009. // Creates and populates the heightMap array with "facet" elements :
  41010. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  41011. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41012. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41013. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41014. // Returns the GroundMesh.
  41015. GroundMesh.prototype._initHeightQuads = function () {
  41016. var subdivisionsX = this._subdivisionsX;
  41017. var subdivisionsY = this._subdivisionsY;
  41018. this._heightQuads = new Array();
  41019. for (var row = 0; row < subdivisionsY; row++) {
  41020. for (var col = 0; col < subdivisionsX; col++) {
  41021. 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) };
  41022. this._heightQuads[row * subdivisionsX + col] = quad;
  41023. }
  41024. }
  41025. return this;
  41026. };
  41027. // Compute each quad element values and update the the heightMap array :
  41028. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41029. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41030. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41031. // Returns the GroundMesh.
  41032. GroundMesh.prototype._computeHeightQuads = function () {
  41033. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41034. var v1 = BABYLON.Tmp.Vector3[3];
  41035. var v2 = BABYLON.Tmp.Vector3[2];
  41036. var v3 = BABYLON.Tmp.Vector3[1];
  41037. var v4 = BABYLON.Tmp.Vector3[0];
  41038. var v1v2 = BABYLON.Tmp.Vector3[4];
  41039. var v1v3 = BABYLON.Tmp.Vector3[5];
  41040. var v1v4 = BABYLON.Tmp.Vector3[6];
  41041. var norm1 = BABYLON.Tmp.Vector3[7];
  41042. var norm2 = BABYLON.Tmp.Vector3[8];
  41043. var i = 0;
  41044. var j = 0;
  41045. var k = 0;
  41046. var cd = 0; // 2D slope coefficient : z = cd * x + h
  41047. var h = 0;
  41048. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  41049. var d2 = 0;
  41050. var subdivisionsX = this._subdivisionsX;
  41051. var subdivisionsY = this._subdivisionsY;
  41052. for (var row = 0; row < subdivisionsY; row++) {
  41053. for (var col = 0; col < subdivisionsX; col++) {
  41054. i = col * 3;
  41055. j = row * (subdivisionsX + 1) * 3;
  41056. k = (row + 1) * (subdivisionsX + 1) * 3;
  41057. v1.x = positions[j + i];
  41058. v1.y = positions[j + i + 1];
  41059. v1.z = positions[j + i + 2];
  41060. v2.x = positions[j + i + 3];
  41061. v2.y = positions[j + i + 4];
  41062. v2.z = positions[j + i + 5];
  41063. v3.x = positions[k + i];
  41064. v3.y = positions[k + i + 1];
  41065. v3.z = positions[k + i + 2];
  41066. v4.x = positions[k + i + 3];
  41067. v4.y = positions[k + i + 4];
  41068. v4.z = positions[k + i + 5];
  41069. // 2D slope V1V4
  41070. cd = (v4.z - v1.z) / (v4.x - v1.x);
  41071. h = v1.z - cd * v1.x; // v1 belongs to the slope
  41072. // facet equations :
  41073. // we compute each facet normal vector
  41074. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  41075. // we compute the value d by applying the equation to v1 which belongs to the plane
  41076. // then we store the facet equation in a Vector4
  41077. v2.subtractToRef(v1, v1v2);
  41078. v3.subtractToRef(v1, v1v3);
  41079. v4.subtractToRef(v1, v1v4);
  41080. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  41081. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  41082. norm1.normalize();
  41083. norm2.normalize();
  41084. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  41085. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  41086. var quad = this._heightQuads[row * subdivisionsX + col];
  41087. quad.slope.copyFromFloats(cd, h);
  41088. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41089. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41090. }
  41091. }
  41092. return this;
  41093. };
  41094. GroundMesh.prototype.serialize = function (serializationObject) {
  41095. _super.prototype.serialize.call(this, serializationObject);
  41096. serializationObject.subdivisionsX = this._subdivisionsX;
  41097. serializationObject.subdivisionsY = this._subdivisionsY;
  41098. serializationObject.minX = this._minX;
  41099. serializationObject.maxX = this._maxX;
  41100. serializationObject.minZ = this._minZ;
  41101. serializationObject.maxZ = this._maxZ;
  41102. serializationObject.width = this._width;
  41103. serializationObject.height = this._height;
  41104. };
  41105. GroundMesh.Parse = function (parsedMesh, scene) {
  41106. var result = new GroundMesh(parsedMesh.name, scene);
  41107. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41108. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41109. result._minX = parsedMesh.minX;
  41110. result._maxX = parsedMesh.maxX;
  41111. result._minZ = parsedMesh.minZ;
  41112. result._maxZ = parsedMesh.maxZ;
  41113. result._width = parsedMesh.width;
  41114. result._height = parsedMesh.height;
  41115. return result;
  41116. };
  41117. return GroundMesh;
  41118. }(BABYLON.Mesh));
  41119. BABYLON.GroundMesh = GroundMesh;
  41120. })(BABYLON || (BABYLON = {}));
  41121. //# sourceMappingURL=babylon.groundMesh.js.map
  41122. var BABYLON;
  41123. (function (BABYLON) {
  41124. /**
  41125. * Creates an instance based on a source mesh.
  41126. */
  41127. var InstancedMesh = (function (_super) {
  41128. __extends(InstancedMesh, _super);
  41129. function InstancedMesh(name, source) {
  41130. var _this = _super.call(this, name, source.getScene()) || this;
  41131. source.instances.push(_this);
  41132. _this._sourceMesh = source;
  41133. _this.position.copyFrom(source.position);
  41134. _this.rotation.copyFrom(source.rotation);
  41135. _this.scaling.copyFrom(source.scaling);
  41136. if (source.rotationQuaternion) {
  41137. _this.rotationQuaternion = source.rotationQuaternion.clone();
  41138. }
  41139. _this.infiniteDistance = source.infiniteDistance;
  41140. _this.setPivotMatrix(source.getPivotMatrix());
  41141. _this.refreshBoundingInfo();
  41142. _this._syncSubMeshes();
  41143. return _this;
  41144. }
  41145. /**
  41146. * Returns the string "InstancedMesh".
  41147. */
  41148. InstancedMesh.prototype.getClassName = function () {
  41149. return "InstancedMesh";
  41150. };
  41151. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  41152. // Methods
  41153. get: function () {
  41154. return this._sourceMesh.receiveShadows;
  41155. },
  41156. enumerable: true,
  41157. configurable: true
  41158. });
  41159. Object.defineProperty(InstancedMesh.prototype, "material", {
  41160. get: function () {
  41161. return this._sourceMesh.material;
  41162. },
  41163. enumerable: true,
  41164. configurable: true
  41165. });
  41166. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  41167. get: function () {
  41168. return this._sourceMesh.visibility;
  41169. },
  41170. enumerable: true,
  41171. configurable: true
  41172. });
  41173. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  41174. get: function () {
  41175. return this._sourceMesh.skeleton;
  41176. },
  41177. enumerable: true,
  41178. configurable: true
  41179. });
  41180. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  41181. get: function () {
  41182. return this._sourceMesh.renderingGroupId;
  41183. },
  41184. enumerable: true,
  41185. configurable: true
  41186. });
  41187. /**
  41188. * Returns the total number of vertices (integer).
  41189. */
  41190. InstancedMesh.prototype.getTotalVertices = function () {
  41191. return this._sourceMesh.getTotalVertices();
  41192. };
  41193. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  41194. get: function () {
  41195. return this._sourceMesh;
  41196. },
  41197. enumerable: true,
  41198. configurable: true
  41199. });
  41200. /**
  41201. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  41202. */
  41203. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  41204. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  41205. };
  41206. /**
  41207. * Sets the vertex data of the mesh geometry for the requested `kind`.
  41208. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  41209. * The `data` are either a numeric array either a Float32Array.
  41210. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  41211. * 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).
  41212. * Note that a new underlying VertexBuffer object is created each call.
  41213. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  41214. *
  41215. * Possible `kind` values :
  41216. * - BABYLON.VertexBuffer.PositionKind
  41217. * - BABYLON.VertexBuffer.UVKind
  41218. * - BABYLON.VertexBuffer.UV2Kind
  41219. * - BABYLON.VertexBuffer.UV3Kind
  41220. * - BABYLON.VertexBuffer.UV4Kind
  41221. * - BABYLON.VertexBuffer.UV5Kind
  41222. * - BABYLON.VertexBuffer.UV6Kind
  41223. * - BABYLON.VertexBuffer.ColorKind
  41224. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41225. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41226. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41227. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41228. *
  41229. * Returns the Mesh.
  41230. */
  41231. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41232. if (this.sourceMesh) {
  41233. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  41234. }
  41235. return this.sourceMesh;
  41236. };
  41237. /**
  41238. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  41239. * If the mesh has no geometry, it is simply returned as it is.
  41240. * The `data` are either a numeric array either a Float32Array.
  41241. * No new underlying VertexBuffer object is created.
  41242. * 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.
  41243. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  41244. *
  41245. * Possible `kind` values :
  41246. * - BABYLON.VertexBuffer.PositionKind
  41247. * - BABYLON.VertexBuffer.UVKind
  41248. * - BABYLON.VertexBuffer.UV2Kind
  41249. * - BABYLON.VertexBuffer.UV3Kind
  41250. * - BABYLON.VertexBuffer.UV4Kind
  41251. * - BABYLON.VertexBuffer.UV5Kind
  41252. * - BABYLON.VertexBuffer.UV6Kind
  41253. * - BABYLON.VertexBuffer.ColorKind
  41254. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41255. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41256. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41257. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41258. *
  41259. * Returns the Mesh.
  41260. */
  41261. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  41262. if (this.sourceMesh) {
  41263. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  41264. }
  41265. return this.sourceMesh;
  41266. };
  41267. /**
  41268. * Sets the mesh indices.
  41269. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  41270. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  41271. * This method creates a new index buffer each call.
  41272. * Returns the Mesh.
  41273. */
  41274. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  41275. if (this.sourceMesh) {
  41276. this.sourceMesh.setIndices(indices, totalVertices);
  41277. }
  41278. return this.sourceMesh;
  41279. };
  41280. /**
  41281. * Boolean : True if the mesh owns the requested kind of data.
  41282. */
  41283. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  41284. return this._sourceMesh.isVerticesDataPresent(kind);
  41285. };
  41286. /**
  41287. * Returns an array of indices (IndicesArray).
  41288. */
  41289. InstancedMesh.prototype.getIndices = function () {
  41290. return this._sourceMesh.getIndices();
  41291. };
  41292. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  41293. get: function () {
  41294. return this._sourceMesh._positions;
  41295. },
  41296. enumerable: true,
  41297. configurable: true
  41298. });
  41299. /**
  41300. * Sets a new updated BoundingInfo to the mesh.
  41301. * Returns the mesh.
  41302. */
  41303. InstancedMesh.prototype.refreshBoundingInfo = function () {
  41304. var meshBB = this._sourceMesh.getBoundingInfo();
  41305. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  41306. this._updateBoundingInfo();
  41307. return this;
  41308. };
  41309. InstancedMesh.prototype._preActivate = function () {
  41310. if (this._currentLOD) {
  41311. this._currentLOD._preActivate();
  41312. }
  41313. return this;
  41314. };
  41315. InstancedMesh.prototype._activate = function (renderId) {
  41316. if (this._currentLOD) {
  41317. this._currentLOD._registerInstanceForRenderId(this, renderId);
  41318. }
  41319. return this;
  41320. };
  41321. /**
  41322. * Returns the current associated LOD AbstractMesh.
  41323. */
  41324. InstancedMesh.prototype.getLOD = function (camera) {
  41325. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  41326. if (this._currentLOD === this.sourceMesh) {
  41327. return this;
  41328. }
  41329. return this._currentLOD;
  41330. };
  41331. InstancedMesh.prototype._syncSubMeshes = function () {
  41332. this.releaseSubMeshes();
  41333. if (this._sourceMesh.subMeshes) {
  41334. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  41335. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  41336. }
  41337. }
  41338. return this;
  41339. };
  41340. InstancedMesh.prototype._generatePointsArray = function () {
  41341. return this._sourceMesh._generatePointsArray();
  41342. };
  41343. /**
  41344. * Creates a new InstancedMesh from the current mesh.
  41345. * - name (string) : the cloned mesh name
  41346. * - newParent (optional Node) : the optional Node to parent the clone to.
  41347. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  41348. *
  41349. * Returns the clone.
  41350. */
  41351. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41352. var result = this._sourceMesh.createInstance(name);
  41353. // Deep copy
  41354. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  41355. // Bounding info
  41356. this.refreshBoundingInfo();
  41357. // Parent
  41358. if (newParent) {
  41359. result.parent = newParent;
  41360. }
  41361. if (!doNotCloneChildren) {
  41362. // Children
  41363. for (var index = 0; index < this.getScene().meshes.length; index++) {
  41364. var mesh = this.getScene().meshes[index];
  41365. if (mesh.parent === this) {
  41366. mesh.clone(mesh.name, result);
  41367. }
  41368. }
  41369. }
  41370. result.computeWorldMatrix(true);
  41371. return result;
  41372. };
  41373. /**
  41374. * Disposes the InstancedMesh.
  41375. * Returns nothing.
  41376. */
  41377. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  41378. // Remove from mesh
  41379. var index = this._sourceMesh.instances.indexOf(this);
  41380. this._sourceMesh.instances.splice(index, 1);
  41381. _super.prototype.dispose.call(this, doNotRecurse);
  41382. };
  41383. return InstancedMesh;
  41384. }(BABYLON.AbstractMesh));
  41385. BABYLON.InstancedMesh = InstancedMesh;
  41386. })(BABYLON || (BABYLON = {}));
  41387. //# sourceMappingURL=babylon.instancedMesh.js.map
  41388. /// <reference path="babylon.mesh.ts" />
  41389. var BABYLON;
  41390. (function (BABYLON) {
  41391. var LinesMesh = (function (_super) {
  41392. __extends(LinesMesh, _super);
  41393. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  41394. if (parent === void 0) { parent = null; }
  41395. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41396. _this.useVertexColor = useVertexColor;
  41397. _this.color = new BABYLON.Color3(1, 1, 1);
  41398. _this.alpha = 1;
  41399. if (source) {
  41400. _this.color = source.color.clone();
  41401. _this.alpha = source.alpha;
  41402. _this.useVertexColor = source.useVertexColor;
  41403. }
  41404. _this._intersectionThreshold = 0.1;
  41405. var options = {
  41406. attributes: [BABYLON.VertexBuffer.PositionKind],
  41407. uniforms: ["world", "viewProjection"],
  41408. needAlphaBlending: false,
  41409. };
  41410. if (!useVertexColor) {
  41411. options.uniforms.push("color");
  41412. options.needAlphaBlending = true;
  41413. }
  41414. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  41415. return _this;
  41416. }
  41417. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41418. /**
  41419. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41420. * This margin is expressed in world space coordinates, so its value may vary.
  41421. * Default value is 0.1
  41422. * @returns the intersection Threshold value.
  41423. */
  41424. get: function () {
  41425. return this._intersectionThreshold;
  41426. },
  41427. /**
  41428. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41429. * This margin is expressed in world space coordinates, so its value may vary.
  41430. * @param value the new threshold to apply
  41431. */
  41432. set: function (value) {
  41433. if (this._intersectionThreshold === value) {
  41434. return;
  41435. }
  41436. this._intersectionThreshold = value;
  41437. if (this.geometry) {
  41438. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  41439. }
  41440. },
  41441. enumerable: true,
  41442. configurable: true
  41443. });
  41444. /**
  41445. * Returns the string "LineMesh"
  41446. */
  41447. LinesMesh.prototype.getClassName = function () {
  41448. return "LinesMesh";
  41449. };
  41450. Object.defineProperty(LinesMesh.prototype, "material", {
  41451. get: function () {
  41452. return this._colorShader;
  41453. },
  41454. enumerable: true,
  41455. configurable: true
  41456. });
  41457. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  41458. get: function () {
  41459. return false;
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. LinesMesh.prototype.createInstance = function (name) {
  41465. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  41466. return null;
  41467. };
  41468. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  41469. // VBOs
  41470. this._geometry._bind(this._colorShader.getEffect());
  41471. // Color
  41472. if (!this.useVertexColor) {
  41473. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  41474. }
  41475. return this;
  41476. };
  41477. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  41478. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  41479. return this;
  41480. }
  41481. var engine = this.getScene().getEngine();
  41482. // Draw order
  41483. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  41484. return this;
  41485. };
  41486. LinesMesh.prototype.dispose = function (doNotRecurse) {
  41487. this._colorShader.dispose();
  41488. _super.prototype.dispose.call(this, doNotRecurse);
  41489. };
  41490. /**
  41491. * Returns a new LineMesh object cloned from the current one.
  41492. */
  41493. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41494. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  41495. };
  41496. return LinesMesh;
  41497. }(BABYLON.Mesh));
  41498. BABYLON.LinesMesh = LinesMesh;
  41499. })(BABYLON || (BABYLON = {}));
  41500. //# sourceMappingURL=babylon.linesMesh.js.map
  41501. var BABYLON;
  41502. (function (BABYLON) {
  41503. var ShaderMaterial = (function (_super) {
  41504. __extends(ShaderMaterial, _super);
  41505. function ShaderMaterial(name, scene, shaderPath, options) {
  41506. var _this = _super.call(this, name, scene) || this;
  41507. _this._textures = {};
  41508. _this._textureArrays = {};
  41509. _this._floats = {};
  41510. _this._floatsArrays = {};
  41511. _this._colors3 = {};
  41512. _this._colors3Arrays = {};
  41513. _this._colors4 = {};
  41514. _this._vectors2 = {};
  41515. _this._vectors3 = {};
  41516. _this._vectors4 = {};
  41517. _this._matrices = {};
  41518. _this._matrices3x3 = {};
  41519. _this._matrices2x2 = {};
  41520. _this._vectors3Arrays = {};
  41521. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41522. _this._shaderPath = shaderPath;
  41523. options.needAlphaBlending = options.needAlphaBlending || false;
  41524. options.needAlphaTesting = options.needAlphaTesting || false;
  41525. options.attributes = options.attributes || ["position", "normal", "uv"];
  41526. options.uniforms = options.uniforms || ["worldViewProjection"];
  41527. options.uniformBuffers = options.uniformBuffers || [];
  41528. options.samplers = options.samplers || [];
  41529. options.defines = options.defines || [];
  41530. _this._options = options;
  41531. return _this;
  41532. }
  41533. ShaderMaterial.prototype.getClassName = function () {
  41534. return "ShaderMaterial";
  41535. };
  41536. ShaderMaterial.prototype.needAlphaBlending = function () {
  41537. return this._options.needAlphaBlending;
  41538. };
  41539. ShaderMaterial.prototype.needAlphaTesting = function () {
  41540. return this._options.needAlphaTesting;
  41541. };
  41542. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41543. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41544. this._options.uniforms.push(uniformName);
  41545. }
  41546. };
  41547. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41548. if (this._options.samplers.indexOf(name) === -1) {
  41549. this._options.samplers.push(name);
  41550. }
  41551. this._textures[name] = texture;
  41552. return this;
  41553. };
  41554. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41555. if (this._options.samplers.indexOf(name) === -1) {
  41556. this._options.samplers.push(name);
  41557. }
  41558. this._checkUniform(name);
  41559. this._textureArrays[name] = textures;
  41560. return this;
  41561. };
  41562. ShaderMaterial.prototype.setFloat = function (name, value) {
  41563. this._checkUniform(name);
  41564. this._floats[name] = value;
  41565. return this;
  41566. };
  41567. ShaderMaterial.prototype.setFloats = function (name, value) {
  41568. this._checkUniform(name);
  41569. this._floatsArrays[name] = value;
  41570. return this;
  41571. };
  41572. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41573. this._checkUniform(name);
  41574. this._colors3[name] = value;
  41575. return this;
  41576. };
  41577. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  41578. this._checkUniform(name);
  41579. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  41580. color.toArray(arr, arr.length);
  41581. return arr;
  41582. }, []);
  41583. return this;
  41584. };
  41585. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41586. this._checkUniform(name);
  41587. this._colors4[name] = value;
  41588. return this;
  41589. };
  41590. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41591. this._checkUniform(name);
  41592. this._vectors2[name] = value;
  41593. return this;
  41594. };
  41595. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41596. this._checkUniform(name);
  41597. this._vectors3[name] = value;
  41598. return this;
  41599. };
  41600. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41601. this._checkUniform(name);
  41602. this._vectors4[name] = value;
  41603. return this;
  41604. };
  41605. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41606. this._checkUniform(name);
  41607. this._matrices[name] = value;
  41608. return this;
  41609. };
  41610. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41611. this._checkUniform(name);
  41612. this._matrices3x3[name] = value;
  41613. return this;
  41614. };
  41615. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41616. this._checkUniform(name);
  41617. this._matrices2x2[name] = value;
  41618. return this;
  41619. };
  41620. ShaderMaterial.prototype.setArray3 = function (name, value) {
  41621. this._checkUniform(name);
  41622. this._vectors3Arrays[name] = value;
  41623. return this;
  41624. };
  41625. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  41626. if (!mesh) {
  41627. return true;
  41628. }
  41629. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  41630. return false;
  41631. }
  41632. return false;
  41633. };
  41634. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41635. var scene = this.getScene();
  41636. var engine = scene.getEngine();
  41637. if (!this.checkReadyOnEveryCall) {
  41638. if (this._renderId === scene.getRenderId()) {
  41639. if (this._checkCache(scene, mesh, useInstances)) {
  41640. return true;
  41641. }
  41642. }
  41643. }
  41644. // Instances
  41645. var defines = [];
  41646. var attribs = [];
  41647. var fallbacks = new BABYLON.EffectFallbacks();
  41648. if (useInstances) {
  41649. defines.push("#define INSTANCES");
  41650. }
  41651. for (var index = 0; index < this._options.defines.length; index++) {
  41652. defines.push(this._options.defines[index]);
  41653. }
  41654. for (var index = 0; index < this._options.attributes.length; index++) {
  41655. attribs.push(this._options.attributes[index]);
  41656. }
  41657. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41658. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41659. defines.push("#define VERTEXCOLOR");
  41660. }
  41661. // Bones
  41662. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41663. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41664. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41665. if (mesh.numBoneInfluencers > 4) {
  41666. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41667. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41668. }
  41669. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41670. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41671. fallbacks.addCPUSkinningFallback(0, mesh);
  41672. if (this._options.uniforms.indexOf("mBones") === -1) {
  41673. this._options.uniforms.push("mBones");
  41674. }
  41675. }
  41676. else {
  41677. defines.push("#define NUM_BONE_INFLUENCERS 0");
  41678. }
  41679. // Textures
  41680. for (var name in this._textures) {
  41681. if (!this._textures[name].isReady()) {
  41682. return false;
  41683. }
  41684. }
  41685. // Alpha test
  41686. if (engine.getAlphaTesting()) {
  41687. defines.push("#define ALPHATEST");
  41688. }
  41689. var previousEffect = this._effect;
  41690. var join = defines.join("\n");
  41691. this._effect = engine.createEffect(this._shaderPath, {
  41692. attributes: attribs,
  41693. uniformsNames: this._options.uniforms,
  41694. uniformBuffersNames: this._options.uniformBuffers,
  41695. samplers: this._options.samplers,
  41696. defines: join,
  41697. fallbacks: fallbacks,
  41698. onCompiled: this.onCompiled,
  41699. onError: this.onError
  41700. }, engine);
  41701. if (!this._effect.isReady()) {
  41702. return false;
  41703. }
  41704. if (previousEffect !== this._effect) {
  41705. scene.resetCachedMaterial();
  41706. }
  41707. this._renderId = scene.getRenderId();
  41708. return true;
  41709. };
  41710. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41711. var scene = this.getScene();
  41712. if (this._options.uniforms.indexOf("world") !== -1) {
  41713. this._effect.setMatrix("world", world);
  41714. }
  41715. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41716. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41717. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41718. }
  41719. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41720. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41721. }
  41722. };
  41723. ShaderMaterial.prototype.bind = function (world, mesh) {
  41724. // Std values
  41725. this.bindOnlyWorldMatrix(world);
  41726. if (this.getScene().getCachedMaterial() !== this) {
  41727. if (this._options.uniforms.indexOf("view") !== -1) {
  41728. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41729. }
  41730. if (this._options.uniforms.indexOf("projection") !== -1) {
  41731. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41732. }
  41733. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41734. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41735. }
  41736. // Bones
  41737. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  41738. var name;
  41739. // Texture
  41740. for (name in this._textures) {
  41741. this._effect.setTexture(name, this._textures[name]);
  41742. }
  41743. // Texture arrays
  41744. for (name in this._textureArrays) {
  41745. this._effect.setTextureArray(name, this._textureArrays[name]);
  41746. }
  41747. // Float
  41748. for (name in this._floats) {
  41749. this._effect.setFloat(name, this._floats[name]);
  41750. }
  41751. // Float s
  41752. for (name in this._floatsArrays) {
  41753. this._effect.setArray(name, this._floatsArrays[name]);
  41754. }
  41755. // Color3
  41756. for (name in this._colors3) {
  41757. this._effect.setColor3(name, this._colors3[name]);
  41758. }
  41759. for (name in this._colors3Arrays) {
  41760. this._effect.setArray3(name, this._colors3Arrays[name]);
  41761. }
  41762. // Color4
  41763. for (name in this._colors4) {
  41764. var color = this._colors4[name];
  41765. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41766. }
  41767. // Vector2
  41768. for (name in this._vectors2) {
  41769. this._effect.setVector2(name, this._vectors2[name]);
  41770. }
  41771. // Vector3
  41772. for (name in this._vectors3) {
  41773. this._effect.setVector3(name, this._vectors3[name]);
  41774. }
  41775. // Vector4
  41776. for (name in this._vectors4) {
  41777. this._effect.setVector4(name, this._vectors4[name]);
  41778. }
  41779. // Matrix
  41780. for (name in this._matrices) {
  41781. this._effect.setMatrix(name, this._matrices[name]);
  41782. }
  41783. // Matrix 3x3
  41784. for (name in this._matrices3x3) {
  41785. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41786. }
  41787. // Matrix 2x2
  41788. for (name in this._matrices2x2) {
  41789. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41790. }
  41791. // Vector3Array
  41792. for (name in this._vectors3Arrays) {
  41793. this._effect.setArray3(name, this._vectors3Arrays[name]);
  41794. }
  41795. }
  41796. this._afterBind(mesh);
  41797. };
  41798. ShaderMaterial.prototype.getActiveTextures = function () {
  41799. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41800. for (var name in this._textures) {
  41801. activeTextures.push(this._textures[name]);
  41802. }
  41803. for (var name in this._textureArrays) {
  41804. var array = this._textureArrays[name];
  41805. for (var index = 0; index < array.length; index++) {
  41806. activeTextures.push(array[index]);
  41807. }
  41808. }
  41809. return activeTextures;
  41810. };
  41811. ShaderMaterial.prototype.hasTexture = function (texture) {
  41812. if (_super.prototype.hasTexture.call(this, texture)) {
  41813. return true;
  41814. }
  41815. for (var name in this._textures) {
  41816. if (this._textures[name] === texture) {
  41817. return true;
  41818. }
  41819. }
  41820. for (var name in this._textureArrays) {
  41821. var array = this._textureArrays[name];
  41822. for (var index = 0; index < array.length; index++) {
  41823. if (array[index] === texture) {
  41824. return true;
  41825. }
  41826. }
  41827. }
  41828. return false;
  41829. };
  41830. ShaderMaterial.prototype.clone = function (name) {
  41831. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  41832. return newShaderMaterial;
  41833. };
  41834. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41835. if (forceDisposeTextures) {
  41836. var name;
  41837. for (name in this._textures) {
  41838. this._textures[name].dispose();
  41839. }
  41840. for (name in this._textureArrays) {
  41841. var array = this._textureArrays[name];
  41842. for (var index = 0; index < array.length; index++) {
  41843. array[index].dispose();
  41844. }
  41845. }
  41846. }
  41847. this._textures = {};
  41848. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41849. };
  41850. ShaderMaterial.prototype.serialize = function () {
  41851. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41852. serializationObject.customType = "BABYLON.ShaderMaterial";
  41853. serializationObject.options = this._options;
  41854. serializationObject.shaderPath = this._shaderPath;
  41855. var name;
  41856. // Texture
  41857. serializationObject.textures = {};
  41858. for (name in this._textures) {
  41859. serializationObject.textures[name] = this._textures[name].serialize();
  41860. }
  41861. // Texture arrays
  41862. serializationObject.textureArrays = {};
  41863. for (name in this._textureArrays) {
  41864. serializationObject.textureArrays[name] = [];
  41865. var array = this._textureArrays[name];
  41866. for (var index = 0; index < array.length; index++) {
  41867. serializationObject.textureArrays[name].push(array[index].serialize());
  41868. }
  41869. }
  41870. // Float
  41871. serializationObject.floats = {};
  41872. for (name in this._floats) {
  41873. serializationObject.floats[name] = this._floats[name];
  41874. }
  41875. // Float s
  41876. serializationObject.floatArrays = {};
  41877. for (name in this._floatsArrays) {
  41878. serializationObject.floatArrays[name] = this._floatsArrays[name];
  41879. }
  41880. // Color3
  41881. serializationObject.colors3 = {};
  41882. for (name in this._colors3) {
  41883. serializationObject.colors3[name] = this._colors3[name].asArray();
  41884. }
  41885. // Color3 array
  41886. serializationObject.colors3Arrays = {};
  41887. for (name in this._colors3Arrays) {
  41888. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  41889. }
  41890. // Color4
  41891. serializationObject.colors4 = {};
  41892. for (name in this._colors4) {
  41893. serializationObject.colors4[name] = this._colors4[name].asArray();
  41894. }
  41895. // Vector2
  41896. serializationObject.vectors2 = {};
  41897. for (name in this._vectors2) {
  41898. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  41899. }
  41900. // Vector3
  41901. serializationObject.vectors3 = {};
  41902. for (name in this._vectors3) {
  41903. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  41904. }
  41905. // Vector4
  41906. serializationObject.vectors4 = {};
  41907. for (name in this._vectors4) {
  41908. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  41909. }
  41910. // Matrix
  41911. serializationObject.matrices = {};
  41912. for (name in this._matrices) {
  41913. serializationObject.matrices[name] = this._matrices[name].asArray();
  41914. }
  41915. // Matrix 3x3
  41916. serializationObject.matrices3x3 = {};
  41917. for (name in this._matrices3x3) {
  41918. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  41919. }
  41920. // Matrix 2x2
  41921. serializationObject.matrices2x2 = {};
  41922. for (name in this._matrices2x2) {
  41923. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  41924. }
  41925. // Vector3Array
  41926. serializationObject.vectors3Arrays = {};
  41927. for (name in this._vectors3Arrays) {
  41928. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  41929. }
  41930. return serializationObject;
  41931. };
  41932. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41933. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41934. var name;
  41935. // Texture
  41936. for (name in source.textures) {
  41937. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41938. }
  41939. // Texture arrays
  41940. for (name in source.textureArrays) {
  41941. var array = source.textureArrays[name];
  41942. var textureArray = new Array();
  41943. for (var index = 0; index < array.length; index++) {
  41944. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  41945. }
  41946. material.setTextureArray(name, textureArray);
  41947. }
  41948. // Float
  41949. for (name in source.floats) {
  41950. material.setFloat(name, source.floats[name]);
  41951. }
  41952. // Float s
  41953. for (name in source.floatsArrays) {
  41954. material.setFloats(name, source.floatsArrays[name]);
  41955. }
  41956. // Color3
  41957. for (name in source.colors3) {
  41958. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41959. }
  41960. // Color3 arrays
  41961. for (name in source.colors3Arrays) {
  41962. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  41963. if (i % 3 === 0) {
  41964. arr.push([num]);
  41965. }
  41966. else {
  41967. arr[arr.length - 1].push(num);
  41968. }
  41969. return arr;
  41970. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  41971. material.setColor3Array(name, colors);
  41972. }
  41973. // Color4
  41974. for (name in source.colors4) {
  41975. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41976. }
  41977. // Vector2
  41978. for (name in source.vectors2) {
  41979. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41980. }
  41981. // Vector3
  41982. for (name in source.vectors3) {
  41983. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41984. }
  41985. // Vector4
  41986. for (name in source.vectors4) {
  41987. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41988. }
  41989. // Matrix
  41990. for (name in source.matrices) {
  41991. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41992. }
  41993. // Matrix 3x3
  41994. for (name in source.matrices3x3) {
  41995. material.setMatrix3x3(name, source.matrices3x3[name]);
  41996. }
  41997. // Matrix 2x2
  41998. for (name in source.matrices2x2) {
  41999. material.setMatrix2x2(name, source.matrices2x2[name]);
  42000. }
  42001. // Vector3Array
  42002. for (name in source.vectors3Arrays) {
  42003. material.setArray3(name, source.vectors3Arrays[name]);
  42004. }
  42005. return material;
  42006. };
  42007. return ShaderMaterial;
  42008. }(BABYLON.Material));
  42009. BABYLON.ShaderMaterial = ShaderMaterial;
  42010. })(BABYLON || (BABYLON = {}));
  42011. //# sourceMappingURL=babylon.shaderMaterial.js.map
  42012. var BABYLON;
  42013. (function (BABYLON) {
  42014. var MeshBuilder = (function () {
  42015. function MeshBuilder() {
  42016. }
  42017. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  42018. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  42019. return BABYLON.Mesh.DOUBLESIDE;
  42020. }
  42021. if (orientation === undefined || orientation === null) {
  42022. return BABYLON.Mesh.FRONTSIDE;
  42023. }
  42024. return orientation;
  42025. };
  42026. /**
  42027. * Creates a box mesh.
  42028. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  42029. * The parameter `size` sets the size (float) of each box side (default 1).
  42030. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  42031. * 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).
  42032. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  42033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42034. * 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).
  42035. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42037. */
  42038. MeshBuilder.CreateBox = function (name, options, scene) {
  42039. var box = new BABYLON.Mesh(name, scene);
  42040. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42041. box.sideOrientation = options.sideOrientation;
  42042. var vertexData = BABYLON.VertexData.CreateBox(options);
  42043. vertexData.applyToMesh(box, options.updatable);
  42044. return box;
  42045. };
  42046. /**
  42047. * Creates a sphere mesh.
  42048. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  42049. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  42050. * 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`).
  42051. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  42052. * 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
  42053. * 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).
  42054. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42055. * 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).
  42056. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42058. */
  42059. MeshBuilder.CreateSphere = function (name, options, scene) {
  42060. var sphere = new BABYLON.Mesh(name, scene);
  42061. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42062. sphere.sideOrientation = options.sideOrientation;
  42063. var vertexData = BABYLON.VertexData.CreateSphere(options);
  42064. vertexData.applyToMesh(sphere, options.updatable);
  42065. return sphere;
  42066. };
  42067. /**
  42068. * Creates a plane polygonal mesh. By default, this is a disc.
  42069. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  42070. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  42071. * 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.
  42072. * 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
  42073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42074. * 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).
  42075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42076. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42077. */
  42078. MeshBuilder.CreateDisc = function (name, options, scene) {
  42079. var disc = new BABYLON.Mesh(name, scene);
  42080. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42081. disc.sideOrientation = options.sideOrientation;
  42082. var vertexData = BABYLON.VertexData.CreateDisc(options);
  42083. vertexData.applyToMesh(disc, options.updatable);
  42084. return disc;
  42085. };
  42086. /**
  42087. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  42088. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  42089. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  42090. * 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`).
  42091. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  42092. * 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.
  42093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42094. * 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).
  42095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42097. */
  42098. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  42099. var sphere = new BABYLON.Mesh(name, scene);
  42100. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42101. sphere.sideOrientation = options.sideOrientation;
  42102. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  42103. vertexData.applyToMesh(sphere, options.updatable);
  42104. return sphere;
  42105. };
  42106. ;
  42107. /**
  42108. * Creates a ribbon mesh.
  42109. * 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.
  42110. *
  42111. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  42112. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  42113. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  42114. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  42115. * 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.
  42116. * 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.
  42117. * 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
  42118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42119. * 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).
  42120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42121. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42122. * 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.
  42123. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  42124. * 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
  42125. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  42126. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  42127. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42128. */
  42129. MeshBuilder.CreateRibbon = function (name, options, scene) {
  42130. var pathArray = options.pathArray;
  42131. var closeArray = options.closeArray;
  42132. var closePath = options.closePath;
  42133. var offset = options.offset;
  42134. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42135. var instance = options.instance;
  42136. var updatable = options.updatable;
  42137. if (instance) {
  42138. // positionFunction : ribbon case
  42139. // only pathArray and sideOrientation parameters are taken into account for positions update
  42140. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  42141. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  42142. var positionFunction = function (positions) {
  42143. var minlg = pathArray[0].length;
  42144. var i = 0;
  42145. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  42146. for (var si = 1; si <= ns; si++) {
  42147. for (var p = 0; p < pathArray.length; p++) {
  42148. var path = pathArray[p];
  42149. var l = path.length;
  42150. minlg = (minlg < l) ? minlg : l;
  42151. var j = 0;
  42152. while (j < minlg) {
  42153. positions[i] = path[j].x;
  42154. positions[i + 1] = path[j].y;
  42155. positions[i + 2] = path[j].z;
  42156. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  42157. BABYLON.Tmp.Vector3[0].x = path[j].x;
  42158. }
  42159. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  42160. BABYLON.Tmp.Vector3[1].x = path[j].x;
  42161. }
  42162. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  42163. BABYLON.Tmp.Vector3[0].y = path[j].y;
  42164. }
  42165. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  42166. BABYLON.Tmp.Vector3[1].y = path[j].y;
  42167. }
  42168. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  42169. BABYLON.Tmp.Vector3[0].z = path[j].z;
  42170. }
  42171. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  42172. BABYLON.Tmp.Vector3[1].z = path[j].z;
  42173. }
  42174. j++;
  42175. i += 3;
  42176. }
  42177. if (instance._closePath) {
  42178. positions[i] = path[0].x;
  42179. positions[i + 1] = path[0].y;
  42180. positions[i + 2] = path[0].z;
  42181. i += 3;
  42182. }
  42183. }
  42184. }
  42185. };
  42186. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42187. positionFunction(positions);
  42188. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  42189. instance._boundingInfo.update(instance._worldMatrix);
  42190. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  42191. if (options.colors) {
  42192. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42193. for (var c = 0; c < options.colors.length; c++) {
  42194. colors[c * 4] = options.colors[c].r;
  42195. colors[c * 4 + 1] = options.colors[c].g;
  42196. colors[c * 4 + 2] = options.colors[c].b;
  42197. colors[c * 4 + 3] = options.colors[c].a;
  42198. }
  42199. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  42200. }
  42201. if (options.uvs) {
  42202. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42203. for (var i = 0; i < options.uvs.length; i++) {
  42204. uvs[i * 2] = options.uvs[i].x;
  42205. uvs[i * 2 + 1] = options.uvs[i].y;
  42206. }
  42207. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  42208. }
  42209. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  42210. var indices = instance.getIndices();
  42211. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42212. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  42213. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  42214. if (instance._closePath) {
  42215. var indexFirst = 0;
  42216. var indexLast = 0;
  42217. for (var p = 0; p < pathArray.length; p++) {
  42218. indexFirst = instance._idx[p] * 3;
  42219. if (p + 1 < pathArray.length) {
  42220. indexLast = (instance._idx[p + 1] - 1) * 3;
  42221. }
  42222. else {
  42223. indexLast = normals.length - 3;
  42224. }
  42225. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  42226. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  42227. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  42228. normals[indexLast] = normals[indexFirst];
  42229. normals[indexLast + 1] = normals[indexFirst + 1];
  42230. normals[indexLast + 2] = normals[indexFirst + 2];
  42231. }
  42232. }
  42233. if (!(instance.areNormalsFrozen)) {
  42234. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  42235. }
  42236. }
  42237. return instance;
  42238. }
  42239. else {
  42240. var ribbon = new BABYLON.Mesh(name, scene);
  42241. ribbon.sideOrientation = sideOrientation;
  42242. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  42243. if (closePath) {
  42244. ribbon._idx = vertexData._idx;
  42245. }
  42246. ribbon._closePath = closePath;
  42247. ribbon._closeArray = closeArray;
  42248. vertexData.applyToMesh(ribbon, updatable);
  42249. return ribbon;
  42250. }
  42251. };
  42252. /**
  42253. * Creates a cylinder or a cone mesh.
  42254. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  42255. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  42256. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  42257. * 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.
  42258. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  42259. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  42260. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  42261. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  42262. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  42263. * 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).
  42264. * 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
  42265. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  42266. * 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
  42267. * 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.
  42268. * If `enclose` is false, a ring surface is one element.
  42269. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  42270. * 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
  42271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42272. * 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).
  42273. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42275. */
  42276. MeshBuilder.CreateCylinder = function (name, options, scene) {
  42277. var cylinder = new BABYLON.Mesh(name, scene);
  42278. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42279. cylinder.sideOrientation = options.sideOrientation;
  42280. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  42281. vertexData.applyToMesh(cylinder, options.updatable);
  42282. return cylinder;
  42283. };
  42284. /**
  42285. * Creates a torus mesh.
  42286. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  42287. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  42288. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  42289. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  42290. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42291. * 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).
  42292. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42293. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42294. */
  42295. MeshBuilder.CreateTorus = function (name, options, scene) {
  42296. var torus = new BABYLON.Mesh(name, scene);
  42297. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42298. torus.sideOrientation = options.sideOrientation;
  42299. var vertexData = BABYLON.VertexData.CreateTorus(options);
  42300. vertexData.applyToMesh(torus, options.updatable);
  42301. return torus;
  42302. };
  42303. /**
  42304. * Creates a torus knot mesh.
  42305. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  42306. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  42307. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  42308. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  42309. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  42310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42311. * 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).
  42312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42314. */
  42315. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  42316. var torusKnot = new BABYLON.Mesh(name, scene);
  42317. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42318. torusKnot.sideOrientation = options.sideOrientation;
  42319. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  42320. vertexData.applyToMesh(torusKnot, options.updatable);
  42321. return torusKnot;
  42322. };
  42323. /**
  42324. * Creates a line system mesh.
  42325. * A line system is a pool of many lines gathered in a single mesh.
  42326. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  42327. * 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.
  42328. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  42329. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  42330. * 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
  42331. * 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
  42332. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  42333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42334. */
  42335. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  42336. var instance = options.instance;
  42337. var lines = options.lines;
  42338. if (instance) {
  42339. var positionFunction = function (positions) {
  42340. var i = 0;
  42341. for (var l = 0; l < lines.length; l++) {
  42342. var points = lines[l];
  42343. for (var p = 0; p < points.length; p++) {
  42344. positions[i] = points[p].x;
  42345. positions[i + 1] = points[p].y;
  42346. positions[i + 2] = points[p].z;
  42347. i += 3;
  42348. }
  42349. }
  42350. };
  42351. instance.updateMeshPositions(positionFunction, false);
  42352. return instance;
  42353. }
  42354. // line system creation
  42355. var lineSystem = new BABYLON.LinesMesh(name, scene);
  42356. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  42357. vertexData.applyToMesh(lineSystem, options.updatable);
  42358. return lineSystem;
  42359. };
  42360. /**
  42361. * Creates a line mesh.
  42362. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  42363. * 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.
  42364. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  42365. * The parameter `points` is an array successive Vector3.
  42366. * 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
  42367. * When updating an instance, remember that only point positions can change, not the number of points.
  42368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42369. */
  42370. MeshBuilder.CreateLines = function (name, options, scene) {
  42371. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  42372. return lines;
  42373. };
  42374. /**
  42375. * Creates a dashed line mesh.
  42376. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  42377. * 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.
  42378. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  42379. * The parameter `points` is an array successive Vector3.
  42380. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  42381. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  42382. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  42383. * 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
  42384. * When updating an instance, remember that only point positions can change, not the number of points.
  42385. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42386. */
  42387. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  42388. var points = options.points;
  42389. var instance = options.instance;
  42390. var gapSize = options.gapSize;
  42391. var dashNb = options.dashNb;
  42392. var dashSize = options.dashSize;
  42393. if (instance) {
  42394. var positionFunction = function (positions) {
  42395. var curvect = BABYLON.Vector3.Zero();
  42396. var nbSeg = positions.length / 6;
  42397. var lg = 0;
  42398. var nb = 0;
  42399. var shft = 0;
  42400. var dashshft = 0;
  42401. var curshft = 0;
  42402. var p = 0;
  42403. var i = 0;
  42404. var j = 0;
  42405. for (i = 0; i < points.length - 1; i++) {
  42406. points[i + 1].subtractToRef(points[i], curvect);
  42407. lg += curvect.length();
  42408. }
  42409. shft = lg / nbSeg;
  42410. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  42411. for (i = 0; i < points.length - 1; i++) {
  42412. points[i + 1].subtractToRef(points[i], curvect);
  42413. nb = Math.floor(curvect.length() / shft);
  42414. curvect.normalize();
  42415. j = 0;
  42416. while (j < nb && p < positions.length) {
  42417. curshft = shft * j;
  42418. positions[p] = points[i].x + curshft * curvect.x;
  42419. positions[p + 1] = points[i].y + curshft * curvect.y;
  42420. positions[p + 2] = points[i].z + curshft * curvect.z;
  42421. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  42422. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  42423. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  42424. p += 6;
  42425. j++;
  42426. }
  42427. }
  42428. while (p < positions.length) {
  42429. positions[p] = points[i].x;
  42430. positions[p + 1] = points[i].y;
  42431. positions[p + 2] = points[i].z;
  42432. p += 3;
  42433. }
  42434. };
  42435. instance.updateMeshPositions(positionFunction, false);
  42436. return instance;
  42437. }
  42438. // dashed lines creation
  42439. var dashedLines = new BABYLON.LinesMesh(name, scene);
  42440. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  42441. vertexData.applyToMesh(dashedLines, options.updatable);
  42442. dashedLines.dashSize = dashSize;
  42443. dashedLines.gapSize = gapSize;
  42444. return dashedLines;
  42445. };
  42446. /**
  42447. * Creates an extruded shape mesh.
  42448. * 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.
  42449. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  42450. *
  42451. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  42452. * 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
  42453. * extruded along the Z axis.
  42454. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  42455. * 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.
  42456. * The parameter `scale` (float, default 1) is the value to scale the shape.
  42457. * 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
  42458. * 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
  42459. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  42460. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42461. * 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).
  42462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42463. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42464. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42465. */
  42466. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  42467. var path = options.path;
  42468. var shape = options.shape;
  42469. var scale = options.scale || 1;
  42470. var rotation = options.rotation || 0;
  42471. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  42472. var updatable = options.updatable;
  42473. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42474. var instance = options.instance;
  42475. var invertUV = options.invertUV || false;
  42476. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  42477. };
  42478. /**
  42479. * Creates an custom extruded shape mesh.
  42480. * 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.
  42481. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  42482. *
  42483. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  42484. * 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
  42485. * extruded along the Z axis.
  42486. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  42487. * 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
  42488. * and the distance of this point from the begining of the path :
  42489. * ```javascript
  42490. * var rotationFunction = function(i, distance) {
  42491. * // do things
  42492. * return rotationValue; }
  42493. * ```
  42494. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  42495. * 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
  42496. * and the distance of this point from the begining of the path :
  42497. * ```javascript
  42498. * var scaleFunction = function(i, distance) {
  42499. * // do things
  42500. * return scaleValue;}
  42501. * ```
  42502. * It must returns a float value that will be the scale value applied to the shape on each path point.
  42503. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  42504. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  42505. * 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
  42506. * 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
  42507. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  42508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42509. * 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).
  42510. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42511. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42513. */
  42514. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  42515. var path = options.path;
  42516. var shape = options.shape;
  42517. var scaleFunction = options.scaleFunction || (function () { return 1; });
  42518. var rotationFunction = options.rotationFunction || (function () { return 0; });
  42519. var ribbonCloseArray = options.ribbonCloseArray || false;
  42520. var ribbonClosePath = options.ribbonClosePath || false;
  42521. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  42522. var updatable = options.updatable;
  42523. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42524. var instance = options.instance;
  42525. var invertUV = options.invertUV || false;
  42526. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  42527. };
  42528. /**
  42529. * Creates lathe mesh.
  42530. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  42531. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  42532. *
  42533. * 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
  42534. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  42535. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  42536. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  42537. * 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.
  42538. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  42539. * 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
  42540. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42541. * 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).
  42542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42543. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42545. */
  42546. MeshBuilder.CreateLathe = function (name, options, scene) {
  42547. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  42548. var closed = (options.closed === undefined) ? true : options.closed;
  42549. var shape = options.shape;
  42550. var radius = options.radius || 1;
  42551. var tessellation = options.tessellation || 64;
  42552. var updatable = options.updatable;
  42553. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42554. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  42555. var pi2 = Math.PI * 2;
  42556. var paths = new Array();
  42557. var invertUV = options.invertUV || false;
  42558. var i = 0;
  42559. var p = 0;
  42560. var step = pi2 / tessellation * arc;
  42561. var rotated;
  42562. var path = new Array();
  42563. ;
  42564. for (i = 0; i <= tessellation; i++) {
  42565. var path = [];
  42566. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  42567. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  42568. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  42569. }
  42570. for (p = 0; p < shape.length; p++) {
  42571. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  42572. path.push(rotated);
  42573. }
  42574. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  42575. 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));
  42576. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  42577. }
  42578. paths.push(path);
  42579. }
  42580. // lathe ribbon
  42581. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  42582. return lathe;
  42583. };
  42584. /**
  42585. * Creates a plane mesh.
  42586. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  42587. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  42588. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  42589. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  42590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42591. * 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).
  42592. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42594. */
  42595. MeshBuilder.CreatePlane = function (name, options, scene) {
  42596. var plane = new BABYLON.Mesh(name, scene);
  42597. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42598. plane.sideOrientation = options.sideOrientation;
  42599. var vertexData = BABYLON.VertexData.CreatePlane(options);
  42600. vertexData.applyToMesh(plane, options.updatable);
  42601. if (options.sourcePlane) {
  42602. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  42603. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  42604. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  42605. plane.rotate(vectorProduct, product);
  42606. }
  42607. return plane;
  42608. };
  42609. /**
  42610. * Creates a ground mesh.
  42611. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  42612. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  42613. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  42614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42615. */
  42616. MeshBuilder.CreateGround = function (name, options, scene) {
  42617. var ground = new BABYLON.GroundMesh(name, scene);
  42618. ground._setReady(false);
  42619. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  42620. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  42621. ground._width = options.width || 1;
  42622. ground._height = options.height || 1;
  42623. ground._maxX = ground._width / 2;
  42624. ground._maxZ = ground._height / 2;
  42625. ground._minX = -ground._maxX;
  42626. ground._minZ = -ground._maxZ;
  42627. var vertexData = BABYLON.VertexData.CreateGround(options);
  42628. vertexData.applyToMesh(ground, options.updatable);
  42629. ground._setReady(true);
  42630. return ground;
  42631. };
  42632. /**
  42633. * Creates a tiled ground mesh.
  42634. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  42635. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  42636. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  42637. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  42638. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  42639. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  42640. * numbers of subdivisions on the ground width and height of each tile.
  42641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42642. */
  42643. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  42644. var tiledGround = new BABYLON.Mesh(name, scene);
  42645. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  42646. vertexData.applyToMesh(tiledGround, options.updatable);
  42647. return tiledGround;
  42648. };
  42649. /**
  42650. * Creates a ground mesh from a height map.
  42651. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  42652. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  42653. * The parameter `url` sets the URL of the height map image resource.
  42654. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  42655. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  42656. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  42657. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  42658. * 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.
  42659. * 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).
  42660. * This function is passed the newly built mesh :
  42661. * ```javascript
  42662. * function(mesh) { // do things
  42663. * return; }
  42664. * ```
  42665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42666. */
  42667. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  42668. var width = options.width || 10.0;
  42669. var height = options.height || 10.0;
  42670. var subdivisions = options.subdivisions || 1 | 0;
  42671. var minHeight = options.minHeight || 0.0;
  42672. var maxHeight = options.maxHeight || 10.0;
  42673. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  42674. var updatable = options.updatable;
  42675. var onReady = options.onReady;
  42676. var ground = new BABYLON.GroundMesh(name, scene);
  42677. ground._subdivisionsX = subdivisions;
  42678. ground._subdivisionsY = subdivisions;
  42679. ground._width = width;
  42680. ground._height = height;
  42681. ground._maxX = ground._width / 2.0;
  42682. ground._maxZ = ground._height / 2.0;
  42683. ground._minX = -ground._maxX;
  42684. ground._minZ = -ground._maxZ;
  42685. ground._setReady(false);
  42686. var onload = function (img) {
  42687. // Getting height map data
  42688. var canvas = document.createElement("canvas");
  42689. var context = canvas.getContext("2d");
  42690. var bufferWidth = img.width;
  42691. var bufferHeight = img.height;
  42692. canvas.width = bufferWidth;
  42693. canvas.height = bufferHeight;
  42694. context.drawImage(img, 0, 0);
  42695. // Create VertexData from map data
  42696. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  42697. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  42698. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  42699. width: width, height: height,
  42700. subdivisions: subdivisions,
  42701. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  42702. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  42703. });
  42704. vertexData.applyToMesh(ground, updatable);
  42705. ground._setReady(true);
  42706. //execute ready callback, if set
  42707. if (onReady) {
  42708. onReady(ground);
  42709. }
  42710. };
  42711. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  42712. return ground;
  42713. };
  42714. /**
  42715. * Creates a polygon mesh.
  42716. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  42717. * 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.
  42718. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42720. * 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).
  42721. * Remember you can only change the shape positions, not their number when updating a polygon.
  42722. */
  42723. MeshBuilder.CreatePolygon = function (name, options, scene) {
  42724. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42725. var shape = options.shape;
  42726. var holes = options.holes || [];
  42727. var depth = options.depth || 0;
  42728. var contours = [];
  42729. var hole = [];
  42730. for (var i = 0; i < shape.length; i++) {
  42731. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  42732. }
  42733. var epsilon = 0.00000001;
  42734. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  42735. contours.pop();
  42736. }
  42737. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  42738. for (var hNb = 0; hNb < holes.length; hNb++) {
  42739. hole = [];
  42740. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  42741. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  42742. }
  42743. polygonTriangulation.addHole(hole);
  42744. }
  42745. var polygon = polygonTriangulation.build(options.updatable, depth);
  42746. polygon.sideOrientation = options.sideOrientation;
  42747. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  42748. vertexData.applyToMesh(polygon, options.updatable);
  42749. return polygon;
  42750. };
  42751. ;
  42752. /**
  42753. * Creates an extruded polygon mesh, with depth in the Y direction.
  42754. * 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).
  42755. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  42756. */
  42757. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  42758. return MeshBuilder.CreatePolygon(name, options, scene);
  42759. };
  42760. ;
  42761. /**
  42762. * Creates a tube mesh.
  42763. * 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.
  42764. *
  42765. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  42766. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  42767. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  42768. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  42769. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  42770. * 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.
  42771. * It must return a radius value (positive float) :
  42772. * ```javascript
  42773. * var radiusFunction = function(i, distance) {
  42774. * // do things
  42775. * return radius; }
  42776. * ```
  42777. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  42778. * 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
  42779. * 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
  42780. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42781. * 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).
  42782. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42783. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42785. */
  42786. MeshBuilder.CreateTube = function (name, options, scene) {
  42787. var path = options.path;
  42788. var radius = options.radius || 1.0;
  42789. var tessellation = options.tessellation || 64 | 0;
  42790. var radiusFunction = options.radiusFunction;
  42791. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  42792. var invertUV = options.invertUV || false;
  42793. var updatable = options.updatable;
  42794. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42795. var instance = options.instance;
  42796. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  42797. // tube geometry
  42798. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  42799. var tangents = path3D.getTangents();
  42800. var normals = path3D.getNormals();
  42801. var distances = path3D.getDistances();
  42802. var pi2 = Math.PI * 2;
  42803. var step = pi2 / tessellation * arc;
  42804. var returnRadius = function () { return radius; };
  42805. var radiusFunctionFinal = radiusFunction || returnRadius;
  42806. var circlePath;
  42807. var rad;
  42808. var normal;
  42809. var rotated;
  42810. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  42811. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  42812. for (var i = 0; i < path.length; i++) {
  42813. rad = radiusFunctionFinal(i, distances[i]); // current radius
  42814. circlePath = Array(); // current circle array
  42815. normal = normals[i]; // current normal
  42816. for (var t = 0; t < tessellation; t++) {
  42817. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  42818. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  42819. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  42820. rotated.scaleInPlace(rad).addInPlace(path[i]);
  42821. circlePath[t] = rotated;
  42822. }
  42823. circlePaths[index] = circlePath;
  42824. index++;
  42825. }
  42826. // cap
  42827. var capPath = function (nbPoints, pathIndex) {
  42828. var pointCap = Array();
  42829. for (var i = 0; i < nbPoints; i++) {
  42830. pointCap.push(path[pathIndex]);
  42831. }
  42832. return pointCap;
  42833. };
  42834. switch (cap) {
  42835. case BABYLON.Mesh.NO_CAP:
  42836. break;
  42837. case BABYLON.Mesh.CAP_START:
  42838. circlePaths[0] = capPath(tessellation, 0);
  42839. circlePaths[1] = circlePaths[2].slice(0);
  42840. break;
  42841. case BABYLON.Mesh.CAP_END:
  42842. circlePaths[index] = circlePaths[index - 1].slice(0);
  42843. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  42844. break;
  42845. case BABYLON.Mesh.CAP_ALL:
  42846. circlePaths[0] = capPath(tessellation, 0);
  42847. circlePaths[1] = circlePaths[2].slice(0);
  42848. circlePaths[index] = circlePaths[index - 1].slice(0);
  42849. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  42850. break;
  42851. default:
  42852. break;
  42853. }
  42854. return circlePaths;
  42855. };
  42856. var path3D;
  42857. var pathArray;
  42858. if (instance) {
  42859. var arc = options.arc || instance.arc;
  42860. path3D = (instance.path3D).update(path);
  42861. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  42862. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  42863. instance.path3D = path3D;
  42864. instance.pathArray = pathArray;
  42865. instance.arc = arc;
  42866. return instance;
  42867. }
  42868. // tube creation
  42869. path3D = new BABYLON.Path3D(path);
  42870. var newPathArray = new Array();
  42871. cap = (cap < 0 || cap > 3) ? 0 : cap;
  42872. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  42873. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  42874. tube.pathArray = pathArray;
  42875. tube.path3D = path3D;
  42876. tube.tessellation = tessellation;
  42877. tube.cap = cap;
  42878. tube.arc = options.arc;
  42879. return tube;
  42880. };
  42881. /**
  42882. * Creates a polyhedron mesh.
  42883. *
  42884. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  42885. * 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
  42886. * to choose the wanted type.
  42887. * The parameter `size` (positive float, default 1) sets the polygon size.
  42888. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  42889. * 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`.
  42890. * 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
  42891. * 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)`).
  42892. * 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
  42893. * 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.
  42894. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42895. * 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).
  42896. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42898. */
  42899. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  42900. var polyhedron = new BABYLON.Mesh(name, scene);
  42901. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42902. polyhedron.sideOrientation = options.sideOrientation;
  42903. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  42904. vertexData.applyToMesh(polyhedron, options.updatable);
  42905. return polyhedron;
  42906. };
  42907. /**
  42908. * Creates a decal mesh.
  42909. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  42910. * 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.
  42911. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  42912. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  42913. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  42914. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  42915. */
  42916. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  42917. var indices = sourceMesh.getIndices();
  42918. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42919. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42920. var position = options.position || BABYLON.Vector3.Zero();
  42921. var normal = options.normal || BABYLON.Vector3.Up();
  42922. var size = options.size || BABYLON.Vector3.One();
  42923. var angle = options.angle || 0;
  42924. // Getting correct rotation
  42925. if (!normal) {
  42926. var target = new BABYLON.Vector3(0, 0, 1);
  42927. var camera = sourceMesh.getScene().activeCamera;
  42928. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  42929. normal = camera.globalPosition.subtract(cameraWorldTarget);
  42930. }
  42931. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  42932. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  42933. var pitch = Math.atan2(normal.y, len);
  42934. // Matrix
  42935. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  42936. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  42937. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  42938. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  42939. var vertexData = new BABYLON.VertexData();
  42940. vertexData.indices = [];
  42941. vertexData.positions = [];
  42942. vertexData.normals = [];
  42943. vertexData.uvs = [];
  42944. var currentVertexDataIndex = 0;
  42945. var extractDecalVector3 = function (indexId) {
  42946. var vertexId = indices[indexId];
  42947. var result = new BABYLON.PositionNormalVertex();
  42948. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  42949. // Send vector to decal local world
  42950. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  42951. // Get normal
  42952. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  42953. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  42954. return result;
  42955. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  42956. var clip = function (vertices, axis) {
  42957. if (vertices.length === 0) {
  42958. return vertices;
  42959. }
  42960. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  42961. var clipVertices = function (v0, v1) {
  42962. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  42963. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  42964. };
  42965. var result = new Array();
  42966. for (var index = 0; index < vertices.length; index += 3) {
  42967. var v1Out;
  42968. var v2Out;
  42969. var v3Out;
  42970. var total = 0;
  42971. var nV1, nV2, nV3, nV4;
  42972. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  42973. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  42974. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  42975. v1Out = d1 > 0;
  42976. v2Out = d2 > 0;
  42977. v3Out = d3 > 0;
  42978. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  42979. switch (total) {
  42980. case 0:
  42981. result.push(vertices[index]);
  42982. result.push(vertices[index + 1]);
  42983. result.push(vertices[index + 2]);
  42984. break;
  42985. case 1:
  42986. if (v1Out) {
  42987. nV1 = vertices[index + 1];
  42988. nV2 = vertices[index + 2];
  42989. nV3 = clipVertices(vertices[index], nV1);
  42990. nV4 = clipVertices(vertices[index], nV2);
  42991. }
  42992. if (v2Out) {
  42993. nV1 = vertices[index];
  42994. nV2 = vertices[index + 2];
  42995. nV3 = clipVertices(vertices[index + 1], nV1);
  42996. nV4 = clipVertices(vertices[index + 1], nV2);
  42997. result.push(nV3);
  42998. result.push(nV2.clone());
  42999. result.push(nV1.clone());
  43000. result.push(nV2.clone());
  43001. result.push(nV3.clone());
  43002. result.push(nV4);
  43003. break;
  43004. }
  43005. if (v3Out) {
  43006. nV1 = vertices[index];
  43007. nV2 = vertices[index + 1];
  43008. nV3 = clipVertices(vertices[index + 2], nV1);
  43009. nV4 = clipVertices(vertices[index + 2], nV2);
  43010. }
  43011. result.push(nV1.clone());
  43012. result.push(nV2.clone());
  43013. result.push(nV3);
  43014. result.push(nV4);
  43015. result.push(nV3.clone());
  43016. result.push(nV2.clone());
  43017. break;
  43018. case 2:
  43019. if (!v1Out) {
  43020. nV1 = vertices[index].clone();
  43021. nV2 = clipVertices(nV1, vertices[index + 1]);
  43022. nV3 = clipVertices(nV1, vertices[index + 2]);
  43023. result.push(nV1);
  43024. result.push(nV2);
  43025. result.push(nV3);
  43026. }
  43027. if (!v2Out) {
  43028. nV1 = vertices[index + 1].clone();
  43029. nV2 = clipVertices(nV1, vertices[index + 2]);
  43030. nV3 = clipVertices(nV1, vertices[index]);
  43031. result.push(nV1);
  43032. result.push(nV2);
  43033. result.push(nV3);
  43034. }
  43035. if (!v3Out) {
  43036. nV1 = vertices[index + 2].clone();
  43037. nV2 = clipVertices(nV1, vertices[index]);
  43038. nV3 = clipVertices(nV1, vertices[index + 1]);
  43039. result.push(nV1);
  43040. result.push(nV2);
  43041. result.push(nV3);
  43042. }
  43043. break;
  43044. case 3:
  43045. break;
  43046. }
  43047. }
  43048. return result;
  43049. };
  43050. for (var index = 0; index < indices.length; index += 3) {
  43051. var faceVertices = new Array();
  43052. faceVertices.push(extractDecalVector3(index));
  43053. faceVertices.push(extractDecalVector3(index + 1));
  43054. faceVertices.push(extractDecalVector3(index + 2));
  43055. // Clip
  43056. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  43057. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  43058. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  43059. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  43060. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  43061. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  43062. if (faceVertices.length === 0) {
  43063. continue;
  43064. }
  43065. // Add UVs and get back to world
  43066. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  43067. var vertex = faceVertices[vIndex];
  43068. //TODO check for Int32Array | Uint32Array | Uint16Array
  43069. vertexData.indices.push(currentVertexDataIndex);
  43070. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  43071. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  43072. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  43073. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  43074. currentVertexDataIndex++;
  43075. }
  43076. }
  43077. // Return mesh
  43078. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  43079. vertexData.applyToMesh(decal);
  43080. decal.position = position.clone();
  43081. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  43082. return decal;
  43083. };
  43084. // Privates
  43085. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  43086. // extrusion geometry
  43087. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  43088. var tangents = path3D.getTangents();
  43089. var normals = path3D.getNormals();
  43090. var binormals = path3D.getBinormals();
  43091. var distances = path3D.getDistances();
  43092. var angle = 0;
  43093. var returnScale = function () { return scale; };
  43094. var returnRotation = function () { return rotation; };
  43095. var rotate = custom ? rotateFunction : returnRotation;
  43096. var scl = custom ? scaleFunction : returnScale;
  43097. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43098. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43099. for (var i = 0; i < curve.length; i++) {
  43100. var shapePath = new Array();
  43101. var angleStep = rotate(i, distances[i]);
  43102. var scaleRatio = scl(i, distances[i]);
  43103. for (var p = 0; p < shape.length; p++) {
  43104. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  43105. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  43106. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  43107. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  43108. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  43109. shapePath[p] = rotated;
  43110. }
  43111. shapePaths[index] = shapePath;
  43112. angle += angleStep;
  43113. index++;
  43114. }
  43115. // cap
  43116. var capPath = function (shapePath) {
  43117. var pointCap = Array();
  43118. var barycenter = BABYLON.Vector3.Zero();
  43119. var i;
  43120. for (i = 0; i < shapePath.length; i++) {
  43121. barycenter.addInPlace(shapePath[i]);
  43122. }
  43123. barycenter.scaleInPlace(1.0 / shapePath.length);
  43124. for (i = 0; i < shapePath.length; i++) {
  43125. pointCap.push(barycenter);
  43126. }
  43127. return pointCap;
  43128. };
  43129. switch (cap) {
  43130. case BABYLON.Mesh.NO_CAP:
  43131. break;
  43132. case BABYLON.Mesh.CAP_START:
  43133. shapePaths[0] = capPath(shapePaths[2]);
  43134. shapePaths[1] = shapePaths[2];
  43135. break;
  43136. case BABYLON.Mesh.CAP_END:
  43137. shapePaths[index] = shapePaths[index - 1];
  43138. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  43139. break;
  43140. case BABYLON.Mesh.CAP_ALL:
  43141. shapePaths[0] = capPath(shapePaths[2]);
  43142. shapePaths[1] = shapePaths[2];
  43143. shapePaths[index] = shapePaths[index - 1];
  43144. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  43145. break;
  43146. default:
  43147. break;
  43148. }
  43149. return shapePaths;
  43150. };
  43151. var path3D;
  43152. var pathArray;
  43153. if (instance) {
  43154. path3D = (instance.path3D).update(curve);
  43155. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  43156. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  43157. return instance;
  43158. }
  43159. // extruded shape creation
  43160. path3D = new BABYLON.Path3D(curve);
  43161. var newShapePaths = new Array();
  43162. cap = (cap < 0 || cap > 3) ? 0 : cap;
  43163. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  43164. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  43165. extrudedGeneric.pathArray = pathArray;
  43166. extrudedGeneric.path3D = path3D;
  43167. extrudedGeneric.cap = cap;
  43168. return extrudedGeneric;
  43169. };
  43170. return MeshBuilder;
  43171. }());
  43172. BABYLON.MeshBuilder = MeshBuilder;
  43173. })(BABYLON || (BABYLON = {}));
  43174. //# sourceMappingURL=babylon.meshBuilder.js.map
  43175. var BABYLON;
  43176. (function (BABYLON) {
  43177. var AudioEngine = (function () {
  43178. function AudioEngine() {
  43179. this._audioContext = null;
  43180. this._audioContextInitialized = false;
  43181. this.canUseWebAudio = false;
  43182. this.WarnedWebAudioUnsupported = false;
  43183. this.unlocked = false;
  43184. this.isMP3supported = false;
  43185. this.isOGGsupported = false;
  43186. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  43187. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  43188. this.canUseWebAudio = true;
  43189. }
  43190. var audioElem = document.createElement('audio');
  43191. try {
  43192. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  43193. this.isMP3supported = true;
  43194. }
  43195. }
  43196. catch (e) {
  43197. // protect error during capability check.
  43198. }
  43199. try {
  43200. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  43201. this.isOGGsupported = true;
  43202. }
  43203. }
  43204. catch (e) {
  43205. // protect error during capability check.
  43206. }
  43207. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  43208. this._unlockiOSaudio();
  43209. }
  43210. else {
  43211. this.unlocked = true;
  43212. }
  43213. }
  43214. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  43215. get: function () {
  43216. if (!this._audioContextInitialized) {
  43217. this._initializeAudioContext();
  43218. }
  43219. return this._audioContext;
  43220. },
  43221. enumerable: true,
  43222. configurable: true
  43223. });
  43224. AudioEngine.prototype._unlockiOSaudio = function () {
  43225. var _this = this;
  43226. var unlockaudio = function () {
  43227. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  43228. var source = _this.audioContext.createBufferSource();
  43229. source.buffer = buffer;
  43230. source.connect(_this.audioContext.destination);
  43231. source.start(0);
  43232. setTimeout(function () {
  43233. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  43234. _this.unlocked = true;
  43235. window.removeEventListener('touchend', unlockaudio, false);
  43236. if (_this.onAudioUnlocked) {
  43237. _this.onAudioUnlocked();
  43238. }
  43239. }
  43240. }, 0);
  43241. };
  43242. window.addEventListener('touchend', unlockaudio, false);
  43243. };
  43244. AudioEngine.prototype._initializeAudioContext = function () {
  43245. try {
  43246. if (this.canUseWebAudio) {
  43247. this._audioContext = new AudioContext();
  43248. // create a global volume gain node
  43249. this.masterGain = this._audioContext.createGain();
  43250. this.masterGain.gain.value = 1;
  43251. this.masterGain.connect(this._audioContext.destination);
  43252. this._audioContextInitialized = true;
  43253. }
  43254. }
  43255. catch (e) {
  43256. this.canUseWebAudio = false;
  43257. BABYLON.Tools.Error("Web Audio: " + e.message);
  43258. }
  43259. };
  43260. AudioEngine.prototype.dispose = function () {
  43261. if (this.canUseWebAudio && this._audioContextInitialized) {
  43262. if (this._connectedAnalyser) {
  43263. this._connectedAnalyser.stopDebugCanvas();
  43264. this._connectedAnalyser.dispose();
  43265. this.masterGain.disconnect();
  43266. this.masterGain.connect(this._audioContext.destination);
  43267. this._connectedAnalyser = null;
  43268. }
  43269. this.masterGain.gain.value = 1;
  43270. }
  43271. this.WarnedWebAudioUnsupported = false;
  43272. };
  43273. AudioEngine.prototype.getGlobalVolume = function () {
  43274. if (this.canUseWebAudio && this._audioContextInitialized) {
  43275. return this.masterGain.gain.value;
  43276. }
  43277. else {
  43278. return -1;
  43279. }
  43280. };
  43281. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  43282. if (this.canUseWebAudio && this._audioContextInitialized) {
  43283. this.masterGain.gain.value = newVolume;
  43284. }
  43285. };
  43286. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  43287. if (this._connectedAnalyser) {
  43288. this._connectedAnalyser.stopDebugCanvas();
  43289. }
  43290. if (this.canUseWebAudio && this._audioContextInitialized) {
  43291. this._connectedAnalyser = analyser;
  43292. this.masterGain.disconnect();
  43293. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  43294. }
  43295. };
  43296. return AudioEngine;
  43297. }());
  43298. BABYLON.AudioEngine = AudioEngine;
  43299. })(BABYLON || (BABYLON = {}));
  43300. //# sourceMappingURL=babylon.audioEngine.js.map
  43301. var BABYLON;
  43302. (function (BABYLON) {
  43303. var Sound = (function () {
  43304. /**
  43305. * Create a sound and attach it to a scene
  43306. * @param name Name of your sound
  43307. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  43308. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  43309. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  43310. */
  43311. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  43312. var _this = this;
  43313. this.autoplay = false;
  43314. this.loop = false;
  43315. this.useCustomAttenuation = false;
  43316. this.spatialSound = false;
  43317. this.refDistance = 1;
  43318. this.rolloffFactor = 1;
  43319. this.maxDistance = 100;
  43320. this.distanceModel = "linear";
  43321. this._panningModel = "equalpower";
  43322. this._playbackRate = 1;
  43323. this._streaming = false;
  43324. this._startTime = 0;
  43325. this._startOffset = 0;
  43326. this._position = BABYLON.Vector3.Zero();
  43327. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  43328. this._volume = 1;
  43329. this._isLoaded = false;
  43330. this._isReadyToPlay = false;
  43331. this.isPlaying = false;
  43332. this.isPaused = false;
  43333. this._isDirectional = false;
  43334. // Used if you'd like to create a directional sound.
  43335. // If not set, the sound will be omnidirectional
  43336. this._coneInnerAngle = 360;
  43337. this._coneOuterAngle = 360;
  43338. this._coneOuterGain = 0;
  43339. this._isOutputConnected = false;
  43340. this._urlType = "Unknown";
  43341. this.name = name;
  43342. this._scene = scene;
  43343. this._readyToPlayCallback = readyToPlayCallback;
  43344. // Default custom attenuation function is a linear attenuation
  43345. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  43346. if (currentDistance < maxDistance) {
  43347. return currentVolume * (1 - currentDistance / maxDistance);
  43348. }
  43349. else {
  43350. return 0;
  43351. }
  43352. };
  43353. if (options) {
  43354. this.autoplay = options.autoplay || false;
  43355. this.loop = options.loop || false;
  43356. // if volume === 0, we need another way to check this option
  43357. if (options.volume !== undefined) {
  43358. this._volume = options.volume;
  43359. }
  43360. this.spatialSound = options.spatialSound || false;
  43361. this.maxDistance = options.maxDistance || 100;
  43362. this.useCustomAttenuation = options.useCustomAttenuation || false;
  43363. this.rolloffFactor = options.rolloffFactor || 1;
  43364. this.refDistance = options.refDistance || 1;
  43365. this.distanceModel = options.distanceModel || "linear";
  43366. this._playbackRate = options.playbackRate || 1;
  43367. this._streaming = options.streaming || false;
  43368. }
  43369. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43370. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  43371. this._soundGain.gain.value = this._volume;
  43372. this._inputAudioNode = this._soundGain;
  43373. this._ouputAudioNode = this._soundGain;
  43374. if (this.spatialSound) {
  43375. this._createSpatialParameters();
  43376. }
  43377. this._scene.mainSoundTrack.AddSound(this);
  43378. var validParameter = true;
  43379. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  43380. if (urlOrArrayBuffer) {
  43381. if (typeof (urlOrArrayBuffer) === "string")
  43382. this._urlType = "String";
  43383. if (Array.isArray(urlOrArrayBuffer))
  43384. this._urlType = "Array";
  43385. if (urlOrArrayBuffer instanceof ArrayBuffer)
  43386. this._urlType = "ArrayBuffer";
  43387. var urls = [];
  43388. var codecSupportedFound = false;
  43389. switch (this._urlType) {
  43390. case "ArrayBuffer":
  43391. if (urlOrArrayBuffer.byteLength > 0) {
  43392. codecSupportedFound = true;
  43393. this._soundLoaded(urlOrArrayBuffer);
  43394. }
  43395. break;
  43396. case "String":
  43397. urls.push(urlOrArrayBuffer);
  43398. case "Array":
  43399. if (urls.length === 0)
  43400. urls = urlOrArrayBuffer;
  43401. // If we found a supported format, we load it immediately and stop the loop
  43402. for (var i = 0; i < urls.length; i++) {
  43403. var url = urls[i];
  43404. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  43405. codecSupportedFound = true;
  43406. }
  43407. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  43408. codecSupportedFound = true;
  43409. }
  43410. if (url.indexOf(".wav", url.length - 4) !== -1) {
  43411. codecSupportedFound = true;
  43412. }
  43413. if (url.indexOf("blob:") !== -1) {
  43414. codecSupportedFound = true;
  43415. }
  43416. if (codecSupportedFound) {
  43417. // Loading sound using XHR2
  43418. if (!this._streaming) {
  43419. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  43420. }
  43421. else {
  43422. this._htmlAudioElement = new Audio(url);
  43423. this._htmlAudioElement.controls = false;
  43424. this._htmlAudioElement.loop = this.loop;
  43425. this._htmlAudioElement.crossOrigin = "anonymous";
  43426. this._htmlAudioElement.preload = "auto";
  43427. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  43428. _this._isReadyToPlay = true;
  43429. if (_this.autoplay) {
  43430. _this.play();
  43431. }
  43432. if (_this._readyToPlayCallback) {
  43433. _this._readyToPlayCallback();
  43434. }
  43435. });
  43436. document.body.appendChild(this._htmlAudioElement);
  43437. }
  43438. break;
  43439. }
  43440. }
  43441. break;
  43442. default:
  43443. validParameter = false;
  43444. break;
  43445. }
  43446. if (!validParameter) {
  43447. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  43448. }
  43449. else {
  43450. if (!codecSupportedFound) {
  43451. this._isReadyToPlay = true;
  43452. // Simulating a ready to play event to avoid breaking code path
  43453. if (this._readyToPlayCallback) {
  43454. window.setTimeout(function () {
  43455. _this._readyToPlayCallback();
  43456. }, 1000);
  43457. }
  43458. }
  43459. }
  43460. }
  43461. }
  43462. else {
  43463. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  43464. this._scene.mainSoundTrack.AddSound(this);
  43465. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  43466. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  43467. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  43468. }
  43469. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  43470. if (this._readyToPlayCallback) {
  43471. window.setTimeout(function () {
  43472. _this._readyToPlayCallback();
  43473. }, 1000);
  43474. }
  43475. }
  43476. }
  43477. Sound.prototype.dispose = function () {
  43478. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  43479. if (this.isPlaying) {
  43480. this.stop();
  43481. }
  43482. this._isReadyToPlay = false;
  43483. if (this.soundTrackId === -1) {
  43484. this._scene.mainSoundTrack.RemoveSound(this);
  43485. }
  43486. else {
  43487. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  43488. }
  43489. if (this._soundGain) {
  43490. this._soundGain.disconnect();
  43491. this._soundGain = null;
  43492. }
  43493. if (this._soundPanner) {
  43494. this._soundPanner.disconnect();
  43495. this._soundPanner = null;
  43496. }
  43497. if (this._soundSource) {
  43498. this._soundSource.disconnect();
  43499. this._soundSource = null;
  43500. }
  43501. this._audioBuffer = null;
  43502. if (this._htmlAudioElement) {
  43503. this._htmlAudioElement.pause();
  43504. this._htmlAudioElement.src = "";
  43505. document.body.removeChild(this._htmlAudioElement);
  43506. }
  43507. if (this._connectedMesh) {
  43508. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43509. this._connectedMesh = null;
  43510. }
  43511. }
  43512. };
  43513. Sound.prototype.isReady = function () {
  43514. return this._isReadyToPlay;
  43515. };
  43516. Sound.prototype._soundLoaded = function (audioData) {
  43517. var _this = this;
  43518. this._isLoaded = true;
  43519. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  43520. _this._audioBuffer = buffer;
  43521. _this._isReadyToPlay = true;
  43522. if (_this.autoplay) {
  43523. _this.play();
  43524. }
  43525. if (_this._readyToPlayCallback) {
  43526. _this._readyToPlayCallback();
  43527. }
  43528. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  43529. };
  43530. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  43531. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43532. this._audioBuffer = audioBuffer;
  43533. this._isReadyToPlay = true;
  43534. }
  43535. };
  43536. Sound.prototype.updateOptions = function (options) {
  43537. if (options) {
  43538. this.loop = options.loop || this.loop;
  43539. this.maxDistance = options.maxDistance || this.maxDistance;
  43540. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  43541. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  43542. this.refDistance = options.refDistance || this.refDistance;
  43543. this.distanceModel = options.distanceModel || this.distanceModel;
  43544. this._playbackRate = options.playbackRate || this._playbackRate;
  43545. this._updateSpatialParameters();
  43546. if (this.isPlaying) {
  43547. if (this._streaming) {
  43548. this._htmlAudioElement.playbackRate = this._playbackRate;
  43549. }
  43550. else {
  43551. this._soundSource.playbackRate.value = this._playbackRate;
  43552. }
  43553. }
  43554. }
  43555. };
  43556. Sound.prototype._createSpatialParameters = function () {
  43557. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43558. if (this._scene.headphone) {
  43559. this._panningModel = "HRTF";
  43560. }
  43561. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  43562. this._updateSpatialParameters();
  43563. this._soundPanner.connect(this._ouputAudioNode);
  43564. this._inputAudioNode = this._soundPanner;
  43565. }
  43566. };
  43567. Sound.prototype._updateSpatialParameters = function () {
  43568. if (this.spatialSound) {
  43569. if (this.useCustomAttenuation) {
  43570. // Tricks to disable in a way embedded Web Audio attenuation
  43571. this._soundPanner.distanceModel = "linear";
  43572. this._soundPanner.maxDistance = Number.MAX_VALUE;
  43573. this._soundPanner.refDistance = 1;
  43574. this._soundPanner.rolloffFactor = 1;
  43575. this._soundPanner.panningModel = this._panningModel;
  43576. }
  43577. else {
  43578. this._soundPanner.distanceModel = this.distanceModel;
  43579. this._soundPanner.maxDistance = this.maxDistance;
  43580. this._soundPanner.refDistance = this.refDistance;
  43581. this._soundPanner.rolloffFactor = this.rolloffFactor;
  43582. this._soundPanner.panningModel = this._panningModel;
  43583. }
  43584. }
  43585. };
  43586. Sound.prototype.switchPanningModelToHRTF = function () {
  43587. this._panningModel = "HRTF";
  43588. this._switchPanningModel();
  43589. };
  43590. Sound.prototype.switchPanningModelToEqualPower = function () {
  43591. this._panningModel = "equalpower";
  43592. this._switchPanningModel();
  43593. };
  43594. Sound.prototype._switchPanningModel = function () {
  43595. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  43596. this._soundPanner.panningModel = this._panningModel;
  43597. }
  43598. };
  43599. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  43600. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43601. if (this._isOutputConnected) {
  43602. this._ouputAudioNode.disconnect();
  43603. }
  43604. this._ouputAudioNode.connect(soundTrackAudioNode);
  43605. this._isOutputConnected = true;
  43606. }
  43607. };
  43608. /**
  43609. * Transform this sound into a directional source
  43610. * @param coneInnerAngle Size of the inner cone in degree
  43611. * @param coneOuterAngle Size of the outer cone in degree
  43612. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  43613. */
  43614. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  43615. if (coneOuterAngle < coneInnerAngle) {
  43616. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  43617. return;
  43618. }
  43619. this._coneInnerAngle = coneInnerAngle;
  43620. this._coneOuterAngle = coneOuterAngle;
  43621. this._coneOuterGain = coneOuterGain;
  43622. this._isDirectional = true;
  43623. if (this.isPlaying && this.loop) {
  43624. this.stop();
  43625. this.play();
  43626. }
  43627. };
  43628. Sound.prototype.setPosition = function (newPosition) {
  43629. this._position = newPosition;
  43630. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  43631. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  43632. }
  43633. };
  43634. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  43635. this._localDirection = newLocalDirection;
  43636. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  43637. this._updateDirection();
  43638. }
  43639. };
  43640. Sound.prototype._updateDirection = function () {
  43641. var mat = this._connectedMesh.getWorldMatrix();
  43642. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  43643. direction.normalize();
  43644. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  43645. };
  43646. Sound.prototype.updateDistanceFromListener = function () {
  43647. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  43648. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  43649. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  43650. }
  43651. };
  43652. Sound.prototype.setAttenuationFunction = function (callback) {
  43653. this._customAttenuationFunction = callback;
  43654. };
  43655. /**
  43656. * Play the sound
  43657. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  43658. * @param offset (optional) Start the sound setting it at a specific time
  43659. */
  43660. Sound.prototype.play = function (time, offset) {
  43661. var _this = this;
  43662. if (this._isReadyToPlay && this._scene.audioEnabled) {
  43663. try {
  43664. if (this._startOffset < 0) {
  43665. time = -this._startOffset;
  43666. this._startOffset = 0;
  43667. }
  43668. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43669. if (!this._soundSource || !this._streamingSource) {
  43670. if (this.spatialSound) {
  43671. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  43672. if (this._isDirectional) {
  43673. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  43674. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  43675. this._soundPanner.coneOuterGain = this._coneOuterGain;
  43676. if (this._connectedMesh) {
  43677. this._updateDirection();
  43678. }
  43679. else {
  43680. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  43681. }
  43682. }
  43683. }
  43684. }
  43685. if (this._streaming) {
  43686. if (!this._streamingSource) {
  43687. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  43688. this._htmlAudioElement.onended = function () { _this._onended(); };
  43689. this._htmlAudioElement.playbackRate = this._playbackRate;
  43690. }
  43691. this._streamingSource.disconnect();
  43692. this._streamingSource.connect(this._inputAudioNode);
  43693. this._htmlAudioElement.play();
  43694. }
  43695. else {
  43696. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  43697. this._soundSource.buffer = this._audioBuffer;
  43698. this._soundSource.connect(this._inputAudioNode);
  43699. this._soundSource.loop = this.loop;
  43700. this._soundSource.playbackRate.value = this._playbackRate;
  43701. this._soundSource.onended = function () { _this._onended(); };
  43702. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  43703. }
  43704. this._startTime = startTime;
  43705. this.isPlaying = true;
  43706. this.isPaused = false;
  43707. }
  43708. catch (ex) {
  43709. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  43710. }
  43711. }
  43712. };
  43713. Sound.prototype._onended = function () {
  43714. this.isPlaying = false;
  43715. if (this.onended) {
  43716. this.onended();
  43717. }
  43718. };
  43719. /**
  43720. * Stop the sound
  43721. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  43722. */
  43723. Sound.prototype.stop = function (time) {
  43724. if (this.isPlaying) {
  43725. if (this._streaming) {
  43726. this._htmlAudioElement.pause();
  43727. // Test needed for Firefox or it will generate an Invalid State Error
  43728. if (this._htmlAudioElement.currentTime > 0) {
  43729. this._htmlAudioElement.currentTime = 0;
  43730. }
  43731. }
  43732. else {
  43733. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43734. this._soundSource.stop(stopTime);
  43735. this._soundSource.onended = null;
  43736. if (!this.isPaused) {
  43737. this._startOffset = 0;
  43738. }
  43739. }
  43740. this.isPlaying = false;
  43741. }
  43742. };
  43743. Sound.prototype.pause = function () {
  43744. if (this.isPlaying) {
  43745. this.isPaused = true;
  43746. if (this._streaming) {
  43747. this._htmlAudioElement.pause();
  43748. }
  43749. else {
  43750. this.stop(0);
  43751. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  43752. }
  43753. }
  43754. };
  43755. Sound.prototype.setVolume = function (newVolume, time) {
  43756. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43757. if (time) {
  43758. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  43759. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  43760. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  43761. }
  43762. else {
  43763. this._soundGain.gain.value = newVolume;
  43764. }
  43765. }
  43766. this._volume = newVolume;
  43767. };
  43768. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  43769. this._playbackRate = newPlaybackRate;
  43770. if (this.isPlaying) {
  43771. if (this._streaming) {
  43772. this._htmlAudioElement.playbackRate = this._playbackRate;
  43773. }
  43774. else {
  43775. this._soundSource.playbackRate.value = this._playbackRate;
  43776. }
  43777. }
  43778. };
  43779. Sound.prototype.getVolume = function () {
  43780. return this._volume;
  43781. };
  43782. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  43783. var _this = this;
  43784. if (this._connectedMesh) {
  43785. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43786. this._registerFunc = null;
  43787. }
  43788. this._connectedMesh = meshToConnectTo;
  43789. if (!this.spatialSound) {
  43790. this.spatialSound = true;
  43791. this._createSpatialParameters();
  43792. if (this.isPlaying && this.loop) {
  43793. this.stop();
  43794. this.play();
  43795. }
  43796. }
  43797. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  43798. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  43799. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  43800. };
  43801. Sound.prototype.detachFromMesh = function () {
  43802. if (this._connectedMesh) {
  43803. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43804. this._registerFunc = null;
  43805. this._connectedMesh = null;
  43806. }
  43807. };
  43808. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  43809. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  43810. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  43811. this._updateDirection();
  43812. }
  43813. };
  43814. Sound.prototype.clone = function () {
  43815. var _this = this;
  43816. if (!this._streaming) {
  43817. var setBufferAndRun = function () {
  43818. if (_this._isReadyToPlay) {
  43819. clonedSound._audioBuffer = _this.getAudioBuffer();
  43820. clonedSound._isReadyToPlay = true;
  43821. if (clonedSound.autoplay) {
  43822. clonedSound.play();
  43823. }
  43824. }
  43825. else {
  43826. window.setTimeout(setBufferAndRun, 300);
  43827. }
  43828. };
  43829. var currentOptions = {
  43830. autoplay: this.autoplay, loop: this.loop,
  43831. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  43832. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  43833. refDistance: this.refDistance, distanceModel: this.distanceModel
  43834. };
  43835. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  43836. if (this.useCustomAttenuation) {
  43837. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  43838. }
  43839. clonedSound.setPosition(this._position);
  43840. clonedSound.setPlaybackRate(this._playbackRate);
  43841. setBufferAndRun();
  43842. return clonedSound;
  43843. }
  43844. else {
  43845. return null;
  43846. }
  43847. };
  43848. Sound.prototype.getAudioBuffer = function () {
  43849. return this._audioBuffer;
  43850. };
  43851. Sound.prototype.serialize = function () {
  43852. var serializationObject = {
  43853. name: this.name,
  43854. url: this.name,
  43855. autoplay: this.autoplay,
  43856. loop: this.loop,
  43857. volume: this._volume,
  43858. spatialSound: this.spatialSound,
  43859. maxDistance: this.maxDistance,
  43860. rolloffFactor: this.rolloffFactor,
  43861. refDistance: this.refDistance,
  43862. distanceModel: this.distanceModel,
  43863. playbackRate: this._playbackRate,
  43864. panningModel: this._panningModel,
  43865. soundTrackId: this.soundTrackId
  43866. };
  43867. if (this.spatialSound) {
  43868. if (this._connectedMesh)
  43869. serializationObject.connectedMeshId = this._connectedMesh.id;
  43870. serializationObject.position = this._position.asArray();
  43871. serializationObject.refDistance = this.refDistance;
  43872. serializationObject.distanceModel = this.distanceModel;
  43873. serializationObject.isDirectional = this._isDirectional;
  43874. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  43875. serializationObject.coneInnerAngle = this._coneInnerAngle;
  43876. serializationObject.coneOuterAngle = this._coneOuterAngle;
  43877. serializationObject.coneOuterGain = this._coneOuterGain;
  43878. }
  43879. return serializationObject;
  43880. };
  43881. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  43882. var soundName = parsedSound.name;
  43883. var soundUrl;
  43884. if (parsedSound.url) {
  43885. soundUrl = rootUrl + parsedSound.url;
  43886. }
  43887. else {
  43888. soundUrl = rootUrl + soundName;
  43889. }
  43890. var options = {
  43891. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  43892. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  43893. rolloffFactor: parsedSound.rolloffFactor,
  43894. refDistance: parsedSound.refDistance,
  43895. distanceModel: parsedSound.distanceModel,
  43896. playbackRate: parsedSound.playbackRate
  43897. };
  43898. var newSound;
  43899. if (!sourceSound) {
  43900. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  43901. scene._addPendingData(newSound);
  43902. }
  43903. else {
  43904. var setBufferAndRun = function () {
  43905. if (sourceSound._isReadyToPlay) {
  43906. newSound._audioBuffer = sourceSound.getAudioBuffer();
  43907. newSound._isReadyToPlay = true;
  43908. if (newSound.autoplay) {
  43909. newSound.play();
  43910. }
  43911. }
  43912. else {
  43913. window.setTimeout(setBufferAndRun, 300);
  43914. }
  43915. };
  43916. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  43917. setBufferAndRun();
  43918. }
  43919. if (parsedSound.position) {
  43920. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  43921. newSound.setPosition(soundPosition);
  43922. }
  43923. if (parsedSound.isDirectional) {
  43924. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  43925. if (parsedSound.localDirectionToMesh) {
  43926. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  43927. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  43928. }
  43929. }
  43930. if (parsedSound.connectedMeshId) {
  43931. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  43932. if (connectedMesh) {
  43933. newSound.attachToMesh(connectedMesh);
  43934. }
  43935. }
  43936. return newSound;
  43937. };
  43938. return Sound;
  43939. }());
  43940. BABYLON.Sound = Sound;
  43941. })(BABYLON || (BABYLON = {}));
  43942. //# sourceMappingURL=babylon.sound.js.map
  43943. var BABYLON;
  43944. (function (BABYLON) {
  43945. var SoundTrack = (function () {
  43946. function SoundTrack(scene, options) {
  43947. this.id = -1;
  43948. this._isMainTrack = false;
  43949. this._isInitialized = false;
  43950. this._scene = scene;
  43951. this.soundCollection = new Array();
  43952. this._options = options;
  43953. if (!this._isMainTrack) {
  43954. this._scene.soundTracks.push(this);
  43955. this.id = this._scene.soundTracks.length - 1;
  43956. }
  43957. }
  43958. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  43959. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43960. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  43961. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  43962. if (this._options) {
  43963. if (this._options.volume) {
  43964. this._outputAudioNode.gain.value = this._options.volume;
  43965. }
  43966. if (this._options.mainTrack) {
  43967. this._isMainTrack = this._options.mainTrack;
  43968. }
  43969. }
  43970. this._isInitialized = true;
  43971. }
  43972. };
  43973. SoundTrack.prototype.dispose = function () {
  43974. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43975. if (this._connectedAnalyser) {
  43976. this._connectedAnalyser.stopDebugCanvas();
  43977. }
  43978. while (this.soundCollection.length) {
  43979. this.soundCollection[0].dispose();
  43980. }
  43981. if (this._outputAudioNode) {
  43982. this._outputAudioNode.disconnect();
  43983. }
  43984. this._outputAudioNode = null;
  43985. }
  43986. };
  43987. SoundTrack.prototype.AddSound = function (sound) {
  43988. if (!this._isInitialized) {
  43989. this._initializeSoundTrackAudioGraph();
  43990. }
  43991. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43992. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  43993. }
  43994. if (sound.soundTrackId) {
  43995. if (sound.soundTrackId === -1) {
  43996. this._scene.mainSoundTrack.RemoveSound(sound);
  43997. }
  43998. else {
  43999. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44000. }
  44001. }
  44002. this.soundCollection.push(sound);
  44003. sound.soundTrackId = this.id;
  44004. };
  44005. SoundTrack.prototype.RemoveSound = function (sound) {
  44006. var index = this.soundCollection.indexOf(sound);
  44007. if (index !== -1) {
  44008. this.soundCollection.splice(index, 1);
  44009. }
  44010. };
  44011. SoundTrack.prototype.setVolume = function (newVolume) {
  44012. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44013. this._outputAudioNode.gain.value = newVolume;
  44014. }
  44015. };
  44016. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  44017. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44018. for (var i = 0; i < this.soundCollection.length; i++) {
  44019. this.soundCollection[i].switchPanningModelToHRTF();
  44020. }
  44021. }
  44022. };
  44023. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  44024. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44025. for (var i = 0; i < this.soundCollection.length; i++) {
  44026. this.soundCollection[i].switchPanningModelToEqualPower();
  44027. }
  44028. }
  44029. };
  44030. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  44031. if (this._connectedAnalyser) {
  44032. this._connectedAnalyser.stopDebugCanvas();
  44033. }
  44034. this._connectedAnalyser = analyser;
  44035. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44036. this._outputAudioNode.disconnect();
  44037. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  44038. }
  44039. };
  44040. return SoundTrack;
  44041. }());
  44042. BABYLON.SoundTrack = SoundTrack;
  44043. })(BABYLON || (BABYLON = {}));
  44044. //# sourceMappingURL=babylon.soundtrack.js.map
  44045. var BABYLON;
  44046. (function (BABYLON) {
  44047. var Analyser = (function () {
  44048. function Analyser(scene) {
  44049. this.SMOOTHING = 0.75;
  44050. this.FFT_SIZE = 512;
  44051. this.BARGRAPHAMPLITUDE = 256;
  44052. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  44053. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  44054. this._scene = scene;
  44055. this._audioEngine = BABYLON.Engine.audioEngine;
  44056. if (this._audioEngine.canUseWebAudio) {
  44057. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  44058. this._webAudioAnalyser.minDecibels = -140;
  44059. this._webAudioAnalyser.maxDecibels = 0;
  44060. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44061. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44062. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  44063. }
  44064. }
  44065. Analyser.prototype.getFrequencyBinCount = function () {
  44066. if (this._audioEngine.canUseWebAudio) {
  44067. return this._webAudioAnalyser.frequencyBinCount;
  44068. }
  44069. else {
  44070. return 0;
  44071. }
  44072. };
  44073. Analyser.prototype.getByteFrequencyData = function () {
  44074. if (this._audioEngine.canUseWebAudio) {
  44075. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44076. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44077. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  44078. }
  44079. return this._byteFreqs;
  44080. };
  44081. Analyser.prototype.getByteTimeDomainData = function () {
  44082. if (this._audioEngine.canUseWebAudio) {
  44083. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44084. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44085. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  44086. }
  44087. return this._byteTime;
  44088. };
  44089. Analyser.prototype.getFloatFrequencyData = function () {
  44090. if (this._audioEngine.canUseWebAudio) {
  44091. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44092. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44093. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  44094. }
  44095. return this._floatFreqs;
  44096. };
  44097. Analyser.prototype.drawDebugCanvas = function () {
  44098. var _this = this;
  44099. if (this._audioEngine.canUseWebAudio) {
  44100. if (!this._debugCanvas) {
  44101. this._debugCanvas = document.createElement("canvas");
  44102. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  44103. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  44104. this._debugCanvas.style.position = "absolute";
  44105. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  44106. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  44107. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  44108. document.body.appendChild(this._debugCanvas);
  44109. this._registerFunc = function () {
  44110. _this.drawDebugCanvas();
  44111. };
  44112. this._scene.registerBeforeRender(this._registerFunc);
  44113. }
  44114. if (this._registerFunc) {
  44115. var workingArray = this.getByteFrequencyData();
  44116. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  44117. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  44118. // Draw the frequency domain chart.
  44119. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  44120. var value = workingArray[i];
  44121. var percent = value / this.BARGRAPHAMPLITUDE;
  44122. var height = this.DEBUGCANVASSIZE.height * percent;
  44123. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  44124. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  44125. var hue = i / this.getFrequencyBinCount() * 360;
  44126. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  44127. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  44128. }
  44129. }
  44130. }
  44131. };
  44132. Analyser.prototype.stopDebugCanvas = function () {
  44133. if (this._debugCanvas) {
  44134. this._scene.unregisterBeforeRender(this._registerFunc);
  44135. this._registerFunc = null;
  44136. document.body.removeChild(this._debugCanvas);
  44137. this._debugCanvas = null;
  44138. this._debugCanvasContext = null;
  44139. }
  44140. };
  44141. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  44142. if (this._audioEngine.canUseWebAudio) {
  44143. inputAudioNode.connect(this._webAudioAnalyser);
  44144. this._webAudioAnalyser.connect(outputAudioNode);
  44145. }
  44146. };
  44147. Analyser.prototype.dispose = function () {
  44148. if (this._audioEngine.canUseWebAudio) {
  44149. this._webAudioAnalyser.disconnect();
  44150. }
  44151. };
  44152. return Analyser;
  44153. }());
  44154. BABYLON.Analyser = Analyser;
  44155. })(BABYLON || (BABYLON = {}));
  44156. //# sourceMappingURL=babylon.analyser.js.map
  44157. var BABYLON;
  44158. (function (BABYLON) {
  44159. var CubeTexture = (function (_super) {
  44160. __extends(CubeTexture, _super);
  44161. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  44162. if (onLoad === void 0) { onLoad = null; }
  44163. if (onError === void 0) { onError = null; }
  44164. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  44165. if (prefiltered === void 0) { prefiltered = false; }
  44166. if (forcedExtension === void 0) { forcedExtension = null; }
  44167. var _this = _super.call(this, scene) || this;
  44168. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  44169. _this.name = rootUrl;
  44170. _this.url = rootUrl;
  44171. _this._noMipmap = noMipmap;
  44172. _this.hasAlpha = false;
  44173. _this._format = format;
  44174. _this._prefiltered = prefiltered;
  44175. _this.isCube = true;
  44176. _this._textureMatrix = BABYLON.Matrix.Identity();
  44177. if (prefiltered) {
  44178. _this.gammaSpace = false;
  44179. }
  44180. if (!rootUrl && !files) {
  44181. return _this;
  44182. }
  44183. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  44184. if (!files) {
  44185. if (!extensions) {
  44186. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  44187. }
  44188. files = [];
  44189. for (var index = 0; index < extensions.length; index++) {
  44190. files.push(rootUrl + extensions[index]);
  44191. }
  44192. _this._extensions = extensions;
  44193. }
  44194. _this._files = files;
  44195. if (!_this._texture) {
  44196. if (!scene.useDelayedTextureLoading) {
  44197. if (prefiltered) {
  44198. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  44199. }
  44200. else {
  44201. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  44202. }
  44203. }
  44204. else {
  44205. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  44206. }
  44207. }
  44208. else if (onLoad) {
  44209. if (_this._texture.isReady) {
  44210. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  44211. }
  44212. else {
  44213. _this._texture.onLoadedCallbacks.push(onLoad);
  44214. }
  44215. }
  44216. return _this;
  44217. }
  44218. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  44219. return new CubeTexture("", scene, null, noMipmap, files);
  44220. };
  44221. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  44222. if (forcedExtension === void 0) { forcedExtension = null; }
  44223. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  44224. };
  44225. // Methods
  44226. CubeTexture.prototype.delayLoad = function () {
  44227. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  44228. return;
  44229. }
  44230. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  44231. this._texture = this._getFromCache(this.url, this._noMipmap);
  44232. if (!this._texture) {
  44233. if (this._prefiltered) {
  44234. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  44235. }
  44236. else {
  44237. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  44238. }
  44239. }
  44240. };
  44241. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  44242. return this._textureMatrix;
  44243. };
  44244. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  44245. this._textureMatrix = value;
  44246. };
  44247. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  44248. var texture = BABYLON.SerializationHelper.Parse(function () {
  44249. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  44250. }, parsedTexture, scene);
  44251. // Animations
  44252. if (parsedTexture.animations) {
  44253. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  44254. var parsedAnimation = parsedTexture.animations[animationIndex];
  44255. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44256. }
  44257. }
  44258. return texture;
  44259. };
  44260. CubeTexture.prototype.clone = function () {
  44261. var _this = this;
  44262. return BABYLON.SerializationHelper.Clone(function () {
  44263. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  44264. }, this);
  44265. };
  44266. return CubeTexture;
  44267. }(BABYLON.BaseTexture));
  44268. BABYLON.CubeTexture = CubeTexture;
  44269. })(BABYLON || (BABYLON = {}));
  44270. //# sourceMappingURL=babylon.cubeTexture.js.map
  44271. var BABYLON;
  44272. (function (BABYLON) {
  44273. var RenderTargetTexture = (function (_super) {
  44274. __extends(RenderTargetTexture, _super);
  44275. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  44276. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  44277. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44278. if (isCube === void 0) { isCube = false; }
  44279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44280. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  44281. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  44282. if (isMulti === void 0) { isMulti = false; }
  44283. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  44284. _this.isCube = isCube;
  44285. /**
  44286. * Use this list to define the list of mesh you want to render.
  44287. */
  44288. _this.renderList = new Array();
  44289. _this.renderParticles = true;
  44290. _this.renderSprites = false;
  44291. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  44292. // Events
  44293. /**
  44294. * An event triggered when the texture is unbind.
  44295. * @type {BABYLON.Observable}
  44296. */
  44297. _this.onBeforeBindObservable = new BABYLON.Observable();
  44298. /**
  44299. * An event triggered when the texture is unbind.
  44300. * @type {BABYLON.Observable}
  44301. */
  44302. _this.onAfterUnbindObservable = new BABYLON.Observable();
  44303. /**
  44304. * An event triggered before rendering the texture
  44305. * @type {BABYLON.Observable}
  44306. */
  44307. _this.onBeforeRenderObservable = new BABYLON.Observable();
  44308. /**
  44309. * An event triggered after rendering the texture
  44310. * @type {BABYLON.Observable}
  44311. */
  44312. _this.onAfterRenderObservable = new BABYLON.Observable();
  44313. /**
  44314. * An event triggered after the texture clear
  44315. * @type {BABYLON.Observable}
  44316. */
  44317. _this.onClearObservable = new BABYLON.Observable();
  44318. _this._currentRefreshId = -1;
  44319. _this._refreshRate = 1;
  44320. _this._samples = 1;
  44321. scene = _this.getScene();
  44322. _this.name = name;
  44323. _this.isRenderTarget = true;
  44324. _this._size = size;
  44325. _this._generateMipMaps = generateMipMaps;
  44326. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  44327. // Rendering groups
  44328. _this._renderingManager = new BABYLON.RenderingManager(scene);
  44329. if (isMulti) {
  44330. return _this;
  44331. }
  44332. _this._renderTargetOptions = {
  44333. generateMipMaps: generateMipMaps,
  44334. type: type,
  44335. samplingMode: samplingMode,
  44336. generateDepthBuffer: generateDepthBuffer,
  44337. generateStencilBuffer: generateStencilBuffer
  44338. };
  44339. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  44340. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44341. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44342. }
  44343. if (isCube) {
  44344. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  44345. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  44346. _this._textureMatrix = BABYLON.Matrix.Identity();
  44347. }
  44348. else {
  44349. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  44350. }
  44351. return _this;
  44352. }
  44353. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  44354. get: function () {
  44355. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  44356. },
  44357. enumerable: true,
  44358. configurable: true
  44359. });
  44360. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  44361. get: function () {
  44362. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  44363. },
  44364. enumerable: true,
  44365. configurable: true
  44366. });
  44367. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  44368. get: function () {
  44369. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  44370. },
  44371. enumerable: true,
  44372. configurable: true
  44373. });
  44374. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  44375. set: function (callback) {
  44376. if (this._onAfterUnbindObserver) {
  44377. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  44378. }
  44379. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  44380. },
  44381. enumerable: true,
  44382. configurable: true
  44383. });
  44384. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  44385. set: function (callback) {
  44386. if (this._onBeforeRenderObserver) {
  44387. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  44388. }
  44389. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  44390. },
  44391. enumerable: true,
  44392. configurable: true
  44393. });
  44394. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  44395. set: function (callback) {
  44396. if (this._onAfterRenderObserver) {
  44397. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  44398. }
  44399. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  44400. },
  44401. enumerable: true,
  44402. configurable: true
  44403. });
  44404. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  44405. set: function (callback) {
  44406. if (this._onClearObserver) {
  44407. this.onClearObservable.remove(this._onClearObserver);
  44408. }
  44409. this._onClearObserver = this.onClearObservable.add(callback);
  44410. },
  44411. enumerable: true,
  44412. configurable: true
  44413. });
  44414. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  44415. get: function () {
  44416. return this._renderTargetOptions;
  44417. },
  44418. enumerable: true,
  44419. configurable: true
  44420. });
  44421. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  44422. get: function () {
  44423. return this._samples;
  44424. },
  44425. set: function (value) {
  44426. if (this._samples === value) {
  44427. return;
  44428. }
  44429. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  44430. },
  44431. enumerable: true,
  44432. configurable: true
  44433. });
  44434. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  44435. this._currentRefreshId = -1;
  44436. };
  44437. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  44438. get: function () {
  44439. return this._refreshRate;
  44440. },
  44441. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44442. set: function (value) {
  44443. this._refreshRate = value;
  44444. this.resetRefreshCounter();
  44445. },
  44446. enumerable: true,
  44447. configurable: true
  44448. });
  44449. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  44450. if (!this._postProcessManager) {
  44451. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  44452. this._postProcesses = new Array();
  44453. }
  44454. this._postProcesses.push(postProcess);
  44455. this._postProcesses[0].autoClear = false;
  44456. };
  44457. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  44458. if (!this._postProcesses) {
  44459. return;
  44460. }
  44461. if (dispose) {
  44462. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  44463. var postProcess = _a[_i];
  44464. postProcess.dispose();
  44465. postProcess = null;
  44466. }
  44467. }
  44468. this._postProcesses = [];
  44469. };
  44470. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  44471. if (!this._postProcesses) {
  44472. return;
  44473. }
  44474. var index = this._postProcesses.indexOf(postProcess);
  44475. if (index === -1) {
  44476. return;
  44477. }
  44478. this._postProcesses.splice(index, 1);
  44479. if (this._postProcesses.length > 0) {
  44480. this._postProcesses[0].autoClear = false;
  44481. }
  44482. };
  44483. RenderTargetTexture.prototype._shouldRender = function () {
  44484. if (this._currentRefreshId === -1) {
  44485. this._currentRefreshId = 1;
  44486. return true;
  44487. }
  44488. if (this.refreshRate === this._currentRefreshId) {
  44489. this._currentRefreshId = 1;
  44490. return true;
  44491. }
  44492. this._currentRefreshId++;
  44493. return false;
  44494. };
  44495. RenderTargetTexture.prototype.isReady = function () {
  44496. if (!this.getScene().renderTargetsEnabled) {
  44497. return false;
  44498. }
  44499. return _super.prototype.isReady.call(this);
  44500. };
  44501. RenderTargetTexture.prototype.getRenderSize = function () {
  44502. return this._size;
  44503. };
  44504. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  44505. get: function () {
  44506. return true;
  44507. },
  44508. enumerable: true,
  44509. configurable: true
  44510. });
  44511. RenderTargetTexture.prototype.scale = function (ratio) {
  44512. var newSize = this._size * ratio;
  44513. this.resize(newSize);
  44514. };
  44515. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  44516. if (this.isCube) {
  44517. return this._textureMatrix;
  44518. }
  44519. return _super.prototype.getReflectionTextureMatrix.call(this);
  44520. };
  44521. RenderTargetTexture.prototype.resize = function (size) {
  44522. this.releaseInternalTexture();
  44523. if (this.isCube) {
  44524. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  44525. }
  44526. else {
  44527. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  44528. }
  44529. };
  44530. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  44531. var scene = this.getScene();
  44532. var engine = scene.getEngine();
  44533. if (this.useCameraPostProcesses !== undefined) {
  44534. useCameraPostProcess = this.useCameraPostProcesses;
  44535. }
  44536. if (this._waitingRenderList) {
  44537. this.renderList = [];
  44538. for (var index = 0; index < this._waitingRenderList.length; index++) {
  44539. var id = this._waitingRenderList[index];
  44540. this.renderList.push(scene.getMeshByID(id));
  44541. }
  44542. delete this._waitingRenderList;
  44543. }
  44544. // Is predicate defined?
  44545. if (this.renderListPredicate) {
  44546. this.renderList.splice(0); // Clear previous renderList
  44547. var sceneMeshes = this.getScene().meshes;
  44548. for (var index = 0; index < sceneMeshes.length; index++) {
  44549. var mesh = sceneMeshes[index];
  44550. if (this.renderListPredicate(mesh)) {
  44551. this.renderList.push(mesh);
  44552. }
  44553. }
  44554. }
  44555. if (this.renderList && this.renderList.length === 0) {
  44556. return;
  44557. }
  44558. this.onBeforeBindObservable.notifyObservers(this);
  44559. // Set custom projection.
  44560. // Needs to be before binding to prevent changing the aspect ratio.
  44561. var camera;
  44562. if (this.activeCamera) {
  44563. camera = this.activeCamera;
  44564. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  44565. if (this.activeCamera !== scene.activeCamera) {
  44566. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  44567. }
  44568. }
  44569. else {
  44570. camera = scene.activeCamera;
  44571. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  44572. }
  44573. // Prepare renderingManager
  44574. this._renderingManager.reset();
  44575. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  44576. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  44577. var sceneRenderId = scene.getRenderId();
  44578. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  44579. var mesh = currentRenderList[meshIndex];
  44580. if (mesh) {
  44581. if (!mesh.isReady()) {
  44582. // Reset _currentRefreshId
  44583. this.resetRefreshCounter();
  44584. continue;
  44585. }
  44586. mesh._preActivateForIntermediateRendering(sceneRenderId);
  44587. var isMasked = void 0;
  44588. if (!this.renderList) {
  44589. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  44590. }
  44591. else {
  44592. isMasked = false;
  44593. }
  44594. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  44595. mesh._activate(sceneRenderId);
  44596. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  44597. var subMesh = mesh.subMeshes[subIndex];
  44598. scene._activeIndices.addCount(subMesh.indexCount, false);
  44599. this._renderingManager.dispatch(subMesh);
  44600. }
  44601. }
  44602. }
  44603. }
  44604. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  44605. var particleSystem = scene.particleSystems[particleIndex];
  44606. var emitter = particleSystem.emitter;
  44607. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  44608. continue;
  44609. }
  44610. if (currentRenderList.indexOf(emitter) >= 0) {
  44611. this._renderingManager.dispatchParticles(particleSystem);
  44612. }
  44613. }
  44614. if (this.isCube) {
  44615. for (var face = 0; face < 6; face++) {
  44616. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  44617. scene.incrementRenderId();
  44618. scene.resetCachedMaterial();
  44619. }
  44620. }
  44621. else {
  44622. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  44623. }
  44624. this.onAfterUnbindObservable.notifyObservers(this);
  44625. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  44626. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  44627. }
  44628. engine.setViewport(scene.activeCamera.viewport);
  44629. scene.resetCachedMaterial();
  44630. };
  44631. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  44632. var _this = this;
  44633. var scene = this.getScene();
  44634. var engine = scene.getEngine();
  44635. // Bind
  44636. if (this._postProcessManager) {
  44637. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  44638. }
  44639. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  44640. if (this.isCube) {
  44641. engine.bindFramebuffer(this._texture, faceIndex);
  44642. }
  44643. else {
  44644. engine.bindFramebuffer(this._texture);
  44645. }
  44646. }
  44647. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  44648. // Clear
  44649. if (this.onClearObservable.hasObservers()) {
  44650. this.onClearObservable.notifyObservers(engine);
  44651. }
  44652. else {
  44653. engine.clear(scene.clearColor, true, true, true);
  44654. }
  44655. if (!this._doNotChangeAspectRatio) {
  44656. scene.updateTransformMatrix(true);
  44657. }
  44658. // Render
  44659. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  44660. if (this._postProcessManager) {
  44661. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  44662. }
  44663. else if (useCameraPostProcess) {
  44664. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  44665. }
  44666. if (!this._doNotChangeAspectRatio) {
  44667. scene.updateTransformMatrix(true);
  44668. }
  44669. // Dump ?
  44670. if (dumpForDebug) {
  44671. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  44672. }
  44673. // Unbind
  44674. if (!this.isCube || faceIndex === 5) {
  44675. if (this.isCube) {
  44676. if (faceIndex === 5) {
  44677. engine.generateMipMapsForCubemap(this._texture);
  44678. }
  44679. }
  44680. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  44681. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  44682. });
  44683. }
  44684. else {
  44685. this.onAfterRenderObservable.notifyObservers(faceIndex);
  44686. }
  44687. };
  44688. /**
  44689. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  44690. * This allowed control for front to back rendering or reversly depending of the special needs.
  44691. *
  44692. * @param renderingGroupId The rendering group id corresponding to its index
  44693. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  44694. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  44695. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  44696. */
  44697. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  44698. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  44699. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  44700. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  44701. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  44702. };
  44703. /**
  44704. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  44705. *
  44706. * @param renderingGroupId The rendering group id corresponding to its index
  44707. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  44708. */
  44709. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  44710. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  44711. };
  44712. RenderTargetTexture.prototype.clone = function () {
  44713. var textureSize = this.getSize();
  44714. 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);
  44715. // Base texture
  44716. newTexture.hasAlpha = this.hasAlpha;
  44717. newTexture.level = this.level;
  44718. // RenderTarget Texture
  44719. newTexture.coordinatesMode = this.coordinatesMode;
  44720. newTexture.renderList = this.renderList.slice(0);
  44721. return newTexture;
  44722. };
  44723. RenderTargetTexture.prototype.serialize = function () {
  44724. if (!this.name) {
  44725. return null;
  44726. }
  44727. var serializationObject = _super.prototype.serialize.call(this);
  44728. serializationObject.renderTargetSize = this.getRenderSize();
  44729. serializationObject.renderList = [];
  44730. for (var index = 0; index < this.renderList.length; index++) {
  44731. serializationObject.renderList.push(this.renderList[index].id);
  44732. }
  44733. return serializationObject;
  44734. };
  44735. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  44736. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  44737. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  44738. };
  44739. RenderTargetTexture.prototype.dispose = function () {
  44740. if (this._postProcessManager) {
  44741. this._postProcessManager.dispose();
  44742. this._postProcessManager = null;
  44743. }
  44744. this.clearPostProcesses(true);
  44745. this.renderList = null;
  44746. // Remove from custom render targets
  44747. var scene = this.getScene();
  44748. var index = scene.customRenderTargets.indexOf(this);
  44749. if (index >= 0) {
  44750. scene.customRenderTargets.splice(index, 1);
  44751. }
  44752. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  44753. var camera = _a[_i];
  44754. index = camera.customRenderTargets.indexOf(this);
  44755. if (index >= 0) {
  44756. camera.customRenderTargets.splice(index, 1);
  44757. }
  44758. }
  44759. _super.prototype.dispose.call(this);
  44760. };
  44761. return RenderTargetTexture;
  44762. }(BABYLON.Texture));
  44763. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  44764. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  44765. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  44766. BABYLON.RenderTargetTexture = RenderTargetTexture;
  44767. })(BABYLON || (BABYLON = {}));
  44768. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  44769. var BABYLON;
  44770. (function (BABYLON) {
  44771. ;
  44772. var MultiRenderTarget = (function (_super) {
  44773. __extends(MultiRenderTarget, _super);
  44774. function MultiRenderTarget(name, size, count, scene, options) {
  44775. var _this = this;
  44776. options = options || {};
  44777. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  44778. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  44779. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  44780. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  44781. if (!_this.isSupported) {
  44782. _this.dispose();
  44783. return;
  44784. }
  44785. var types = [];
  44786. var samplingModes = [];
  44787. for (var i = 0; i < count; i++) {
  44788. if (options.types && options.types[i]) {
  44789. types.push(options.types[i]);
  44790. }
  44791. else {
  44792. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  44793. }
  44794. if (options.samplingModes && options.samplingModes[i]) {
  44795. samplingModes.push(options.samplingModes[i]);
  44796. }
  44797. else {
  44798. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44799. }
  44800. }
  44801. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  44802. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  44803. _this._count = count;
  44804. _this._size = size;
  44805. _this._multiRenderTargetOptions = {
  44806. samplingModes: samplingModes,
  44807. generateMipMaps: generateMipMaps,
  44808. generateDepthBuffer: generateDepthBuffer,
  44809. generateStencilBuffer: generateStencilBuffer,
  44810. generateDepthTexture: generateDepthTexture,
  44811. types: types,
  44812. textureCount: count
  44813. };
  44814. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  44815. _this._createInternalTextures();
  44816. return _this;
  44817. }
  44818. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  44819. get: function () {
  44820. var engine = this.getScene().getEngine();
  44821. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  44822. },
  44823. enumerable: true,
  44824. configurable: true
  44825. });
  44826. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  44827. get: function () {
  44828. return this._textures;
  44829. },
  44830. enumerable: true,
  44831. configurable: true
  44832. });
  44833. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  44834. get: function () {
  44835. return this._textures[this._textures.length - 1];
  44836. },
  44837. enumerable: true,
  44838. configurable: true
  44839. });
  44840. MultiRenderTarget.prototype._createInternalTextures = function () {
  44841. this._textures = [];
  44842. for (var i = 0; i < this._webGLTextures.length; i++) {
  44843. var texture = new BABYLON.Texture(null, this.getScene());
  44844. texture._texture = this._webGLTextures[i];
  44845. this._textures.push(texture);
  44846. }
  44847. // Keeps references to frame buffer and stencil/depth buffer
  44848. this._texture = this._webGLTextures[0];
  44849. };
  44850. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  44851. get: function () {
  44852. return this._samples;
  44853. },
  44854. set: function (value) {
  44855. if (this._samples === value) {
  44856. return;
  44857. }
  44858. for (var i = 0; i < this._webGLTextures.length; i++) {
  44859. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  44860. }
  44861. },
  44862. enumerable: true,
  44863. configurable: true
  44864. });
  44865. MultiRenderTarget.prototype.resize = function (size) {
  44866. this.releaseInternalTextures();
  44867. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  44868. this._createInternalTextures();
  44869. };
  44870. MultiRenderTarget.prototype.dispose = function () {
  44871. this.releaseInternalTextures();
  44872. _super.prototype.dispose.call(this);
  44873. };
  44874. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  44875. if (!this._webGLTextures) {
  44876. return;
  44877. }
  44878. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  44879. if (this._webGLTextures[i] !== undefined) {
  44880. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  44881. this._webGLTextures.splice(i, 1);
  44882. }
  44883. }
  44884. };
  44885. return MultiRenderTarget;
  44886. }(BABYLON.RenderTargetTexture));
  44887. BABYLON.MultiRenderTarget = MultiRenderTarget;
  44888. })(BABYLON || (BABYLON = {}));
  44889. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  44890. /// <reference path="babylon.renderTargetTexture.ts" />
  44891. var BABYLON;
  44892. (function (BABYLON) {
  44893. var MirrorTexture = (function (_super) {
  44894. __extends(MirrorTexture, _super);
  44895. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  44896. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44898. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  44899. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  44900. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  44901. _this._transformMatrix = BABYLON.Matrix.Zero();
  44902. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  44903. _this._blurKernelX = 0;
  44904. _this._blurKernelY = 0;
  44905. _this._blurRatio = 1.0;
  44906. _this.onBeforeRenderObservable.add(function () {
  44907. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  44908. _this._savedViewMatrix = scene.getViewMatrix();
  44909. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  44910. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  44911. scene.clipPlane = _this.mirrorPlane;
  44912. scene.getEngine().cullBackFaces = false;
  44913. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  44914. });
  44915. _this.onAfterRenderObservable.add(function () {
  44916. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  44917. scene.getEngine().cullBackFaces = true;
  44918. scene._mirroredCameraPosition = null;
  44919. delete scene.clipPlane;
  44920. });
  44921. return _this;
  44922. }
  44923. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  44924. get: function () {
  44925. return this._blurRatio;
  44926. },
  44927. set: function (value) {
  44928. if (this._blurRatio === value) {
  44929. return;
  44930. }
  44931. this._blurRatio = value;
  44932. this._preparePostProcesses();
  44933. },
  44934. enumerable: true,
  44935. configurable: true
  44936. });
  44937. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  44938. set: function (value) {
  44939. this.blurKernelX = value;
  44940. this.blurKernelY = value;
  44941. },
  44942. enumerable: true,
  44943. configurable: true
  44944. });
  44945. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  44946. get: function () {
  44947. return this._blurKernelX;
  44948. },
  44949. set: function (value) {
  44950. if (this._blurKernelX === value) {
  44951. return;
  44952. }
  44953. this._blurKernelX = value;
  44954. this._preparePostProcesses();
  44955. },
  44956. enumerable: true,
  44957. configurable: true
  44958. });
  44959. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  44960. get: function () {
  44961. return this._blurKernelY;
  44962. },
  44963. set: function (value) {
  44964. if (this._blurKernelY === value) {
  44965. return;
  44966. }
  44967. this._blurKernelY = value;
  44968. this._preparePostProcesses();
  44969. },
  44970. enumerable: true,
  44971. configurable: true
  44972. });
  44973. MirrorTexture.prototype._preparePostProcesses = function () {
  44974. this.clearPostProcesses(true);
  44975. if (this._blurKernelX && this._blurKernelY) {
  44976. var engine = this.getScene().getEngine();
  44977. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44978. 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);
  44979. this._blurX.autoClear = false;
  44980. if (this._blurRatio === 1 && this.samples < 2) {
  44981. this._blurX.outputTexture = this._texture;
  44982. }
  44983. else {
  44984. this._blurX.alwaysForcePOT = true;
  44985. }
  44986. 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);
  44987. this._blurY.autoClear = false;
  44988. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  44989. this.addPostProcess(this._blurX);
  44990. this.addPostProcess(this._blurY);
  44991. }
  44992. };
  44993. MirrorTexture.prototype.clone = function () {
  44994. var textureSize = this.getSize();
  44995. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  44996. // Base texture
  44997. newTexture.hasAlpha = this.hasAlpha;
  44998. newTexture.level = this.level;
  44999. // Mirror Texture
  45000. newTexture.mirrorPlane = this.mirrorPlane.clone();
  45001. newTexture.renderList = this.renderList.slice(0);
  45002. return newTexture;
  45003. };
  45004. MirrorTexture.prototype.serialize = function () {
  45005. if (!this.name) {
  45006. return null;
  45007. }
  45008. var serializationObject = _super.prototype.serialize.call(this);
  45009. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  45010. return serializationObject;
  45011. };
  45012. return MirrorTexture;
  45013. }(BABYLON.RenderTargetTexture));
  45014. BABYLON.MirrorTexture = MirrorTexture;
  45015. })(BABYLON || (BABYLON = {}));
  45016. //# sourceMappingURL=babylon.mirrorTexture.js.map
  45017. /// <reference path="babylon.renderTargetTexture.ts" />
  45018. var BABYLON;
  45019. (function (BABYLON) {
  45020. /**
  45021. * Creates a refraction texture used by refraction channel of the standard material.
  45022. * @param name the texture name
  45023. * @param size size of the underlying texture
  45024. * @param scene root scene
  45025. */
  45026. var RefractionTexture = (function (_super) {
  45027. __extends(RefractionTexture, _super);
  45028. function RefractionTexture(name, size, scene, generateMipMaps) {
  45029. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  45030. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  45031. _this.depth = 2.0;
  45032. _this.onBeforeRenderObservable.add(function () {
  45033. scene.clipPlane = _this.refractionPlane;
  45034. });
  45035. _this.onAfterRenderObservable.add(function () {
  45036. delete scene.clipPlane;
  45037. });
  45038. return _this;
  45039. }
  45040. RefractionTexture.prototype.clone = function () {
  45041. var textureSize = this.getSize();
  45042. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  45043. // Base texture
  45044. newTexture.hasAlpha = this.hasAlpha;
  45045. newTexture.level = this.level;
  45046. // Refraction Texture
  45047. newTexture.refractionPlane = this.refractionPlane.clone();
  45048. newTexture.renderList = this.renderList.slice(0);
  45049. newTexture.depth = this.depth;
  45050. return newTexture;
  45051. };
  45052. RefractionTexture.prototype.serialize = function () {
  45053. if (!this.name) {
  45054. return null;
  45055. }
  45056. var serializationObject = _super.prototype.serialize.call(this);
  45057. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  45058. serializationObject.depth = this.depth;
  45059. return serializationObject;
  45060. };
  45061. return RefractionTexture;
  45062. }(BABYLON.RenderTargetTexture));
  45063. BABYLON.RefractionTexture = RefractionTexture;
  45064. })(BABYLON || (BABYLON = {}));
  45065. //# sourceMappingURL=babylon.refractionTexture.js.map
  45066. /// <reference path="babylon.texture.ts" />
  45067. var BABYLON;
  45068. (function (BABYLON) {
  45069. var DynamicTexture = (function (_super) {
  45070. __extends(DynamicTexture, _super);
  45071. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  45072. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45073. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45074. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  45075. _this.name = name;
  45076. var engine = _this.getScene().getEngine();
  45077. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45078. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45079. _this._generateMipMaps = generateMipMaps;
  45080. if (options.getContext) {
  45081. _this._canvas = options;
  45082. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45083. }
  45084. else {
  45085. _this._canvas = document.createElement("canvas");
  45086. if (options.width) {
  45087. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45088. }
  45089. else {
  45090. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  45091. }
  45092. }
  45093. var textureSize = _this.getSize();
  45094. _this._canvas.width = textureSize.width;
  45095. _this._canvas.height = textureSize.height;
  45096. _this._context = _this._canvas.getContext("2d");
  45097. return _this;
  45098. }
  45099. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  45100. get: function () {
  45101. return true;
  45102. },
  45103. enumerable: true,
  45104. configurable: true
  45105. });
  45106. DynamicTexture.prototype._recreate = function (textureSize) {
  45107. this._canvas.width = textureSize.width;
  45108. this._canvas.height = textureSize.height;
  45109. this.releaseInternalTexture();
  45110. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  45111. };
  45112. DynamicTexture.prototype.scale = function (ratio) {
  45113. var textureSize = this.getSize();
  45114. textureSize.width *= ratio;
  45115. textureSize.height *= ratio;
  45116. this._recreate(textureSize);
  45117. };
  45118. DynamicTexture.prototype.scaleTo = function (width, height) {
  45119. var textureSize = this.getSize();
  45120. textureSize.width = width;
  45121. textureSize.height = height;
  45122. this._recreate(textureSize);
  45123. };
  45124. DynamicTexture.prototype.getContext = function () {
  45125. return this._context;
  45126. };
  45127. DynamicTexture.prototype.clear = function () {
  45128. var size = this.getSize();
  45129. this._context.fillRect(0, 0, size.width, size.height);
  45130. };
  45131. DynamicTexture.prototype.update = function (invertY) {
  45132. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  45133. };
  45134. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  45135. if (update === void 0) { update = true; }
  45136. var size = this.getSize();
  45137. if (clearColor) {
  45138. this._context.fillStyle = clearColor;
  45139. this._context.fillRect(0, 0, size.width, size.height);
  45140. }
  45141. this._context.font = font;
  45142. if (x === null || x === undefined) {
  45143. var textSize = this._context.measureText(text);
  45144. x = (size.width - textSize.width) / 2;
  45145. }
  45146. if (y === null || y === undefined) {
  45147. var fontSize = parseInt((font.replace(/\D/g, '')));
  45148. ;
  45149. y = (size.height / 2) + (fontSize / 3.65);
  45150. }
  45151. this._context.fillStyle = color;
  45152. this._context.fillText(text, x, y);
  45153. if (update) {
  45154. this.update(invertY);
  45155. }
  45156. };
  45157. DynamicTexture.prototype.clone = function () {
  45158. var textureSize = this.getSize();
  45159. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  45160. // Base texture
  45161. newTexture.hasAlpha = this.hasAlpha;
  45162. newTexture.level = this.level;
  45163. // Dynamic Texture
  45164. newTexture.wrapU = this.wrapU;
  45165. newTexture.wrapV = this.wrapV;
  45166. return newTexture;
  45167. };
  45168. return DynamicTexture;
  45169. }(BABYLON.Texture));
  45170. BABYLON.DynamicTexture = DynamicTexture;
  45171. })(BABYLON || (BABYLON = {}));
  45172. //# sourceMappingURL=babylon.dynamicTexture.js.map
  45173. var BABYLON;
  45174. (function (BABYLON) {
  45175. var VideoTexture = (function (_super) {
  45176. __extends(VideoTexture, _super);
  45177. /**
  45178. * Creates a video texture.
  45179. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  45180. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  45181. * @param {BABYLON.Scene} scene is obviously the current scene.
  45182. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  45183. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  45184. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  45185. */
  45186. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  45187. if (generateMipMaps === void 0) { generateMipMaps = false; }
  45188. if (invertY === void 0) { invertY = false; }
  45189. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45190. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45191. _this._autoLaunch = true;
  45192. var urls;
  45193. _this.name = name;
  45194. if (urlsOrVideo instanceof HTMLVideoElement) {
  45195. _this.video = urlsOrVideo;
  45196. }
  45197. else {
  45198. urls = urlsOrVideo;
  45199. _this.video = document.createElement("video");
  45200. _this.video.autoplay = false;
  45201. _this.video.loop = true;
  45202. }
  45203. _this._generateMipMaps = generateMipMaps;
  45204. _this._samplingMode = samplingMode;
  45205. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  45206. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45207. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45208. }
  45209. else {
  45210. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45211. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45212. _this._generateMipMaps = false;
  45213. }
  45214. if (urls) {
  45215. _this.video.addEventListener("canplay", function () {
  45216. _this._createTexture();
  45217. });
  45218. urls.forEach(function (url) {
  45219. var source = document.createElement("source");
  45220. source.src = url;
  45221. _this.video.appendChild(source);
  45222. });
  45223. }
  45224. else {
  45225. _this._createTexture();
  45226. }
  45227. _this._lastUpdate = BABYLON.Tools.Now;
  45228. return _this;
  45229. }
  45230. VideoTexture.prototype.__setTextureReady = function () {
  45231. this._texture.isReady = true;
  45232. };
  45233. VideoTexture.prototype._createTexture = function () {
  45234. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  45235. if (this._autoLaunch) {
  45236. this._autoLaunch = false;
  45237. this.video.play();
  45238. }
  45239. this._setTextureReady = this.__setTextureReady.bind(this);
  45240. this.video.addEventListener("playing", this._setTextureReady);
  45241. };
  45242. VideoTexture.prototype.update = function () {
  45243. var now = BABYLON.Tools.Now;
  45244. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  45245. return false;
  45246. }
  45247. this._lastUpdate = now;
  45248. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  45249. return true;
  45250. };
  45251. VideoTexture.prototype.dispose = function () {
  45252. _super.prototype.dispose.call(this);
  45253. this.video.removeEventListener("playing", this._setTextureReady);
  45254. };
  45255. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  45256. var video = document.createElement("video");
  45257. var constraintsDeviceId;
  45258. if (constraints && constraints.deviceId) {
  45259. constraintsDeviceId = {
  45260. exact: constraints.deviceId
  45261. };
  45262. }
  45263. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  45264. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  45265. if (navigator.getUserMedia) {
  45266. navigator.getUserMedia({
  45267. video: {
  45268. deviceId: constraintsDeviceId,
  45269. width: {
  45270. min: (constraints && constraints.minWidth) || 256,
  45271. max: (constraints && constraints.maxWidth) || 640
  45272. },
  45273. height: {
  45274. min: (constraints && constraints.minHeight) || 256,
  45275. max: (constraints && constraints.maxHeight) || 480
  45276. }
  45277. }
  45278. }, function (stream) {
  45279. if (video.mozSrcObject !== undefined) {
  45280. video.mozSrcObject = stream;
  45281. }
  45282. else {
  45283. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  45284. }
  45285. video.play();
  45286. if (onReady) {
  45287. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  45288. }
  45289. }, function (e) {
  45290. BABYLON.Tools.Error(e.name);
  45291. });
  45292. }
  45293. };
  45294. return VideoTexture;
  45295. }(BABYLON.Texture));
  45296. BABYLON.VideoTexture = VideoTexture;
  45297. })(BABYLON || (BABYLON = {}));
  45298. //# sourceMappingURL=babylon.videoTexture.js.map
  45299. var BABYLON;
  45300. (function (BABYLON) {
  45301. var RawTexture = (function (_super) {
  45302. __extends(RawTexture, _super);
  45303. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45304. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45305. if (invertY === void 0) { invertY = false; }
  45306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45307. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45308. _this.format = format;
  45309. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45310. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45311. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45312. return _this;
  45313. }
  45314. RawTexture.prototype.update = function (data) {
  45315. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45316. };
  45317. // Statics
  45318. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45319. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45320. if (invertY === void 0) { invertY = false; }
  45321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45322. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45323. };
  45324. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45325. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45326. if (invertY === void 0) { invertY = false; }
  45327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45328. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45329. };
  45330. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45331. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45332. if (invertY === void 0) { invertY = false; }
  45333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45334. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45335. };
  45336. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45337. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45338. if (invertY === void 0) { invertY = false; }
  45339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45340. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45341. };
  45342. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45343. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45344. if (invertY === void 0) { invertY = false; }
  45345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45346. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45347. };
  45348. return RawTexture;
  45349. }(BABYLON.Texture));
  45350. BABYLON.RawTexture = RawTexture;
  45351. })(BABYLON || (BABYLON = {}));
  45352. //# sourceMappingURL=babylon.rawTexture.js.map
  45353. var BABYLON;
  45354. (function (BABYLON) {
  45355. var PostProcess = (function () {
  45356. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  45357. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  45358. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45359. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  45360. if (blockCompilation === void 0) { blockCompilation = false; }
  45361. this.name = name;
  45362. this.width = -1;
  45363. this.height = -1;
  45364. this.autoClear = true;
  45365. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  45366. /*
  45367. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  45368. Can only be used on a single postprocess or on the last one of a chain.
  45369. */
  45370. this.enablePixelPerfectMode = false;
  45371. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  45372. this.alwaysForcePOT = false;
  45373. this.samples = 1;
  45374. this._reusable = false;
  45375. this._textures = new BABYLON.SmartArray(2);
  45376. this._currentRenderTextureInd = 0;
  45377. this._scaleRatio = new BABYLON.Vector2(1, 1);
  45378. this._texelSize = BABYLON.Vector2.Zero();
  45379. // Events
  45380. /**
  45381. * An event triggered when the postprocess is activated.
  45382. * @type {BABYLON.Observable}
  45383. */
  45384. this.onActivateObservable = new BABYLON.Observable();
  45385. /**
  45386. * An event triggered when the postprocess changes its size.
  45387. * @type {BABYLON.Observable}
  45388. */
  45389. this.onSizeChangedObservable = new BABYLON.Observable();
  45390. /**
  45391. * An event triggered when the postprocess applies its effect.
  45392. * @type {BABYLON.Observable}
  45393. */
  45394. this.onApplyObservable = new BABYLON.Observable();
  45395. /**
  45396. * An event triggered before rendering the postprocess
  45397. * @type {BABYLON.Observable}
  45398. */
  45399. this.onBeforeRenderObservable = new BABYLON.Observable();
  45400. /**
  45401. * An event triggered after rendering the postprocess
  45402. * @type {BABYLON.Observable}
  45403. */
  45404. this.onAfterRenderObservable = new BABYLON.Observable();
  45405. if (camera != null) {
  45406. this._camera = camera;
  45407. this._scene = camera.getScene();
  45408. camera.attachPostProcess(this);
  45409. this._engine = this._scene.getEngine();
  45410. }
  45411. else {
  45412. this._engine = engine;
  45413. }
  45414. this._options = options;
  45415. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  45416. this._reusable = reusable || false;
  45417. this._textureType = textureType;
  45418. this._samplers = samplers || [];
  45419. this._samplers.push("textureSampler");
  45420. this._fragmentUrl = fragmentUrl;
  45421. this._vertexUrl = vertexUrl;
  45422. this._parameters = parameters || [];
  45423. this._parameters.push("scale");
  45424. this._indexParameters = indexParameters;
  45425. if (!blockCompilation) {
  45426. this.updateEffect(defines);
  45427. }
  45428. }
  45429. Object.defineProperty(PostProcess.prototype, "onActivate", {
  45430. set: function (callback) {
  45431. if (this._onActivateObserver) {
  45432. this.onActivateObservable.remove(this._onActivateObserver);
  45433. }
  45434. this._onActivateObserver = this.onActivateObservable.add(callback);
  45435. },
  45436. enumerable: true,
  45437. configurable: true
  45438. });
  45439. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  45440. set: function (callback) {
  45441. if (this._onSizeChangedObserver) {
  45442. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  45443. }
  45444. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  45445. },
  45446. enumerable: true,
  45447. configurable: true
  45448. });
  45449. Object.defineProperty(PostProcess.prototype, "onApply", {
  45450. set: function (callback) {
  45451. if (this._onApplyObserver) {
  45452. this.onApplyObservable.remove(this._onApplyObserver);
  45453. }
  45454. this._onApplyObserver = this.onApplyObservable.add(callback);
  45455. },
  45456. enumerable: true,
  45457. configurable: true
  45458. });
  45459. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  45460. set: function (callback) {
  45461. if (this._onBeforeRenderObserver) {
  45462. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45463. }
  45464. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45465. },
  45466. enumerable: true,
  45467. configurable: true
  45468. });
  45469. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  45470. set: function (callback) {
  45471. if (this._onAfterRenderObserver) {
  45472. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45473. }
  45474. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45475. },
  45476. enumerable: true,
  45477. configurable: true
  45478. });
  45479. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  45480. get: function () {
  45481. return this._textures.data[this._currentRenderTextureInd];
  45482. },
  45483. set: function (value) {
  45484. this._forcedOutputTexture = value;
  45485. },
  45486. enumerable: true,
  45487. configurable: true
  45488. });
  45489. PostProcess.prototype.getCamera = function () {
  45490. return this._camera;
  45491. };
  45492. Object.defineProperty(PostProcess.prototype, "texelSize", {
  45493. get: function () {
  45494. if (this._shareOutputWithPostProcess) {
  45495. return this._shareOutputWithPostProcess.texelSize;
  45496. }
  45497. if (this._forcedOutputTexture) {
  45498. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  45499. }
  45500. return this._texelSize;
  45501. },
  45502. enumerable: true,
  45503. configurable: true
  45504. });
  45505. PostProcess.prototype.getEngine = function () {
  45506. return this._engine;
  45507. };
  45508. PostProcess.prototype.getEffect = function () {
  45509. return this._effect;
  45510. };
  45511. PostProcess.prototype.shareOutputWith = function (postProcess) {
  45512. this._disposeTextures();
  45513. this._shareOutputWithPostProcess = postProcess;
  45514. return this;
  45515. };
  45516. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  45517. 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);
  45518. };
  45519. PostProcess.prototype.isReusable = function () {
  45520. return this._reusable;
  45521. };
  45522. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  45523. PostProcess.prototype.markTextureDirty = function () {
  45524. this.width = -1;
  45525. };
  45526. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  45527. var _this = this;
  45528. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  45529. camera = camera || this._camera;
  45530. var scene = camera.getScene();
  45531. var engine = scene.getEngine();
  45532. var maxSize = engine.getCaps().maxTextureSize;
  45533. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  45534. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  45535. var desiredWidth = this._options.width || requiredWidth;
  45536. var desiredHeight = this._options.height || requiredHeight;
  45537. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  45538. if (!this._options.width) {
  45539. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  45540. }
  45541. if (!this._options.height) {
  45542. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  45543. }
  45544. }
  45545. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  45546. if (this._textures.length > 0) {
  45547. for (var i = 0; i < this._textures.length; i++) {
  45548. this._engine._releaseTexture(this._textures.data[i]);
  45549. }
  45550. this._textures.reset();
  45551. }
  45552. this.width = desiredWidth;
  45553. this.height = desiredHeight;
  45554. var textureSize = { width: this.width, height: this.height };
  45555. var textureOptions = {
  45556. generateMipMaps: false,
  45557. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  45558. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  45559. samplingMode: this.renderTargetSamplingMode,
  45560. type: this._textureType
  45561. };
  45562. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  45563. if (this._reusable) {
  45564. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  45565. }
  45566. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  45567. this.onSizeChangedObservable.notifyObservers(this);
  45568. }
  45569. this._textures.forEach(function (texture) {
  45570. if (texture.samples !== _this.samples) {
  45571. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  45572. }
  45573. });
  45574. }
  45575. var target;
  45576. if (this._shareOutputWithPostProcess) {
  45577. target = this._shareOutputWithPostProcess.outputTexture;
  45578. }
  45579. else if (this._forcedOutputTexture) {
  45580. target = this._forcedOutputTexture;
  45581. this.width = this._forcedOutputTexture._width;
  45582. this.height = this._forcedOutputTexture._height;
  45583. }
  45584. else {
  45585. target = this.outputTexture;
  45586. }
  45587. if (this.enablePixelPerfectMode) {
  45588. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  45589. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  45590. }
  45591. else {
  45592. this._scaleRatio.copyFromFloats(1, 1);
  45593. this._engine.bindFramebuffer(target);
  45594. }
  45595. this.onActivateObservable.notifyObservers(camera);
  45596. // Clear
  45597. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  45598. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  45599. }
  45600. if (this._reusable) {
  45601. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  45602. }
  45603. };
  45604. Object.defineProperty(PostProcess.prototype, "isSupported", {
  45605. get: function () {
  45606. return this._effect.isSupported;
  45607. },
  45608. enumerable: true,
  45609. configurable: true
  45610. });
  45611. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  45612. get: function () {
  45613. if (this._shareOutputWithPostProcess) {
  45614. return this._shareOutputWithPostProcess.aspectRatio;
  45615. }
  45616. if (this._forcedOutputTexture) {
  45617. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  45618. }
  45619. return this.width / this.height;
  45620. },
  45621. enumerable: true,
  45622. configurable: true
  45623. });
  45624. PostProcess.prototype.apply = function () {
  45625. // Check
  45626. if (!this._effect || !this._effect.isReady())
  45627. return null;
  45628. // States
  45629. this._engine.enableEffect(this._effect);
  45630. this._engine.setState(false);
  45631. this._engine.setDepthBuffer(false);
  45632. this._engine.setDepthWrite(false);
  45633. // Alpha
  45634. this._engine.setAlphaMode(this.alphaMode);
  45635. if (this.alphaConstants) {
  45636. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  45637. }
  45638. // Texture
  45639. var source;
  45640. if (this._shareOutputWithPostProcess) {
  45641. source = this._shareOutputWithPostProcess.outputTexture;
  45642. }
  45643. else if (this._forcedOutputTexture) {
  45644. source = this._forcedOutputTexture;
  45645. }
  45646. else {
  45647. source = this.outputTexture;
  45648. }
  45649. this._effect._bindTexture("textureSampler", source);
  45650. // Parameters
  45651. this._effect.setVector2("scale", this._scaleRatio);
  45652. this.onApplyObservable.notifyObservers(this._effect);
  45653. return this._effect;
  45654. };
  45655. PostProcess.prototype._disposeTextures = function () {
  45656. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  45657. return;
  45658. }
  45659. if (this._textures.length > 0) {
  45660. for (var i = 0; i < this._textures.length; i++) {
  45661. this._engine._releaseTexture(this._textures.data[i]);
  45662. }
  45663. }
  45664. this._textures.dispose();
  45665. };
  45666. PostProcess.prototype.dispose = function (camera) {
  45667. camera = camera || this._camera;
  45668. this._disposeTextures();
  45669. if (!camera) {
  45670. return;
  45671. }
  45672. camera.detachPostProcess(this);
  45673. var index = camera._postProcesses.indexOf(this);
  45674. if (index === 0 && camera._postProcesses.length > 0) {
  45675. this._camera._postProcesses[0].markTextureDirty();
  45676. }
  45677. this.onActivateObservable.clear();
  45678. this.onAfterRenderObservable.clear();
  45679. this.onApplyObservable.clear();
  45680. this.onBeforeRenderObservable.clear();
  45681. this.onSizeChangedObservable.clear();
  45682. };
  45683. return PostProcess;
  45684. }());
  45685. BABYLON.PostProcess = PostProcess;
  45686. })(BABYLON || (BABYLON = {}));
  45687. //# sourceMappingURL=babylon.postProcess.js.map
  45688. var BABYLON;
  45689. (function (BABYLON) {
  45690. var PassPostProcess = (function (_super) {
  45691. __extends(PassPostProcess, _super);
  45692. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  45693. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45694. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  45695. }
  45696. return PassPostProcess;
  45697. }(BABYLON.PostProcess));
  45698. BABYLON.PassPostProcess = PassPostProcess;
  45699. })(BABYLON || (BABYLON = {}));
  45700. //# sourceMappingURL=babylon.passPostProcess.js.map
  45701. var BABYLON;
  45702. (function (BABYLON) {
  45703. var ShadowGenerator = (function () {
  45704. /**
  45705. * Creates a ShadowGenerator object.
  45706. * A ShadowGenerator is the required tool to use the shadows.
  45707. * Each light casting shadows needs to use its own ShadowGenerator.
  45708. * Required parameters :
  45709. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  45710. * - `light`: the light object generating the shadows.
  45711. * - `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.
  45712. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  45713. */
  45714. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  45715. // Members
  45716. this._bias = 0.00005;
  45717. this._blurBoxOffset = 1;
  45718. this._blurScale = 2;
  45719. this._blurKernel = 1;
  45720. this._useKernelBlur = false;
  45721. this._filter = ShadowGenerator.FILTER_NONE;
  45722. this._darkness = 0;
  45723. this._transparencyShadow = false;
  45724. /**
  45725. * Controls the extent to which the shadows fade out at the edge of the frustum
  45726. * Used only by directionals and spots
  45727. */
  45728. this.frustumEdgeFalloff = 0;
  45729. this.forceBackFacesOnly = false;
  45730. this._lightDirection = BABYLON.Vector3.Zero();
  45731. this._viewMatrix = BABYLON.Matrix.Zero();
  45732. this._projectionMatrix = BABYLON.Matrix.Zero();
  45733. this._transformMatrix = BABYLON.Matrix.Zero();
  45734. this._worldViewProjection = BABYLON.Matrix.Zero();
  45735. this._currentFaceIndex = 0;
  45736. this._currentFaceIndexCache = 0;
  45737. this._isCube = false;
  45738. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  45739. this._mapSize = mapSize;
  45740. this._light = light;
  45741. this._scene = light.getScene();
  45742. light._shadowGenerator = this;
  45743. // Texture type fallback from float to int if not supported.
  45744. var caps = this._scene.getEngine().getCaps();
  45745. if (!useFullFloatFirst) {
  45746. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  45747. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45748. }
  45749. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  45750. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45751. }
  45752. else {
  45753. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45754. }
  45755. }
  45756. else {
  45757. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  45758. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45759. }
  45760. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  45761. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45762. }
  45763. else {
  45764. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45765. }
  45766. }
  45767. this._initializeGenerator();
  45768. }
  45769. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  45770. // Static
  45771. get: function () {
  45772. return ShadowGenerator._FILTER_NONE;
  45773. },
  45774. enumerable: true,
  45775. configurable: true
  45776. });
  45777. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  45778. get: function () {
  45779. return ShadowGenerator._FILTER_POISSONSAMPLING;
  45780. },
  45781. enumerable: true,
  45782. configurable: true
  45783. });
  45784. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  45785. get: function () {
  45786. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  45787. },
  45788. enumerable: true,
  45789. configurable: true
  45790. });
  45791. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  45792. get: function () {
  45793. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  45794. },
  45795. enumerable: true,
  45796. configurable: true
  45797. });
  45798. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  45799. get: function () {
  45800. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  45801. },
  45802. enumerable: true,
  45803. configurable: true
  45804. });
  45805. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  45806. get: function () {
  45807. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  45808. },
  45809. enumerable: true,
  45810. configurable: true
  45811. });
  45812. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  45813. get: function () {
  45814. return this._bias;
  45815. },
  45816. set: function (bias) {
  45817. this._bias = bias;
  45818. },
  45819. enumerable: true,
  45820. configurable: true
  45821. });
  45822. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  45823. get: function () {
  45824. return this._blurBoxOffset;
  45825. },
  45826. set: function (value) {
  45827. if (this._blurBoxOffset === value) {
  45828. return;
  45829. }
  45830. this._blurBoxOffset = value;
  45831. this._disposeBlurPostProcesses();
  45832. },
  45833. enumerable: true,
  45834. configurable: true
  45835. });
  45836. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  45837. get: function () {
  45838. return this._blurScale;
  45839. },
  45840. set: function (value) {
  45841. if (this._blurScale === value) {
  45842. return;
  45843. }
  45844. this._blurScale = value;
  45845. this._disposeBlurPostProcesses();
  45846. },
  45847. enumerable: true,
  45848. configurable: true
  45849. });
  45850. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  45851. get: function () {
  45852. return this._blurKernel;
  45853. },
  45854. set: function (value) {
  45855. if (this._blurKernel === value) {
  45856. return;
  45857. }
  45858. this._blurKernel = value;
  45859. this._disposeBlurPostProcesses();
  45860. },
  45861. enumerable: true,
  45862. configurable: true
  45863. });
  45864. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  45865. get: function () {
  45866. return this._useKernelBlur;
  45867. },
  45868. set: function (value) {
  45869. if (this._useKernelBlur === value) {
  45870. return;
  45871. }
  45872. this._useKernelBlur = value;
  45873. this._disposeBlurPostProcesses();
  45874. },
  45875. enumerable: true,
  45876. configurable: true
  45877. });
  45878. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  45879. get: function () {
  45880. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  45881. },
  45882. set: function (value) {
  45883. this._depthScale = value;
  45884. },
  45885. enumerable: true,
  45886. configurable: true
  45887. });
  45888. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  45889. get: function () {
  45890. return this._filter;
  45891. },
  45892. set: function (value) {
  45893. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  45894. if (this._light.needCube()) {
  45895. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  45896. this.useExponentialShadowMap = true;
  45897. return;
  45898. }
  45899. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  45900. this.useCloseExponentialShadowMap = true;
  45901. return;
  45902. }
  45903. }
  45904. if (this._filter === value) {
  45905. return;
  45906. }
  45907. this._filter = value;
  45908. this._disposeBlurPostProcesses();
  45909. this._applyFilterValues();
  45910. this._light._markMeshesAsLightDirty();
  45911. },
  45912. enumerable: true,
  45913. configurable: true
  45914. });
  45915. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  45916. get: function () {
  45917. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  45918. },
  45919. set: function (value) {
  45920. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  45921. },
  45922. enumerable: true,
  45923. configurable: true
  45924. });
  45925. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  45926. get: function () {
  45927. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  45928. return this.useExponentialShadowMap;
  45929. },
  45930. set: function (value) {
  45931. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  45932. this.useExponentialShadowMap = value;
  45933. },
  45934. enumerable: true,
  45935. configurable: true
  45936. });
  45937. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  45938. get: function () {
  45939. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  45940. return this.useBlurExponentialShadowMap;
  45941. },
  45942. set: function (value) {
  45943. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  45944. this.useBlurExponentialShadowMap = value;
  45945. },
  45946. enumerable: true,
  45947. configurable: true
  45948. });
  45949. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  45950. get: function () {
  45951. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  45952. },
  45953. set: function (value) {
  45954. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  45955. },
  45956. enumerable: true,
  45957. configurable: true
  45958. });
  45959. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  45960. get: function () {
  45961. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  45962. },
  45963. set: function (value) {
  45964. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  45965. },
  45966. enumerable: true,
  45967. configurable: true
  45968. });
  45969. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  45970. get: function () {
  45971. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  45972. },
  45973. set: function (value) {
  45974. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  45975. },
  45976. enumerable: true,
  45977. configurable: true
  45978. });
  45979. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  45980. get: function () {
  45981. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  45982. },
  45983. set: function (value) {
  45984. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  45985. },
  45986. enumerable: true,
  45987. configurable: true
  45988. });
  45989. /**
  45990. * Returns the darkness value (float).
  45991. */
  45992. ShadowGenerator.prototype.getDarkness = function () {
  45993. return this._darkness;
  45994. };
  45995. /**
  45996. * Sets the ShadowGenerator darkness value (float <= 1.0).
  45997. * Returns the ShadowGenerator.
  45998. */
  45999. ShadowGenerator.prototype.setDarkness = function (darkness) {
  46000. if (darkness >= 1.0)
  46001. this._darkness = 1.0;
  46002. else if (darkness <= 0.0)
  46003. this._darkness = 0.0;
  46004. else
  46005. this._darkness = darkness;
  46006. return this;
  46007. };
  46008. /**
  46009. * Sets the ability to have transparent shadow (boolean).
  46010. * Returns the ShadowGenerator.
  46011. */
  46012. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  46013. this._transparencyShadow = hasShadow;
  46014. return this;
  46015. };
  46016. /**
  46017. * Returns a RenderTargetTexture object : the shadow map texture.
  46018. */
  46019. ShadowGenerator.prototype.getShadowMap = function () {
  46020. return this._shadowMap;
  46021. };
  46022. /**
  46023. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  46024. */
  46025. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  46026. if (this._shadowMap2) {
  46027. return this._shadowMap2;
  46028. }
  46029. return this._shadowMap;
  46030. };
  46031. /**
  46032. * Returns the associated light object.
  46033. */
  46034. ShadowGenerator.prototype.getLight = function () {
  46035. return this._light;
  46036. };
  46037. ShadowGenerator.prototype._initializeGenerator = function () {
  46038. this._light._markMeshesAsLightDirty();
  46039. this._initializeShadowMap();
  46040. };
  46041. ShadowGenerator.prototype._initializeShadowMap = function () {
  46042. var _this = this;
  46043. // Render target
  46044. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  46045. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46046. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46047. this._shadowMap.anisotropicFilteringLevel = 1;
  46048. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46049. this._shadowMap.renderParticles = false;
  46050. // Record Face Index before render.
  46051. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  46052. _this._currentFaceIndex = faceIndex;
  46053. });
  46054. // Custom render function.
  46055. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  46056. // Blur if required afer render.
  46057. this._shadowMap.onAfterUnbindObservable.add(function () {
  46058. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  46059. return;
  46060. }
  46061. if (!_this._blurPostProcesses) {
  46062. _this._initializeBlurRTTAndPostProcesses();
  46063. }
  46064. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  46065. });
  46066. // Clear according to the chosen filter.
  46067. this._shadowMap.onClearObservable.add(function (engine) {
  46068. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  46069. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  46070. }
  46071. else {
  46072. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46073. }
  46074. });
  46075. };
  46076. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  46077. var _this = this;
  46078. var engine = this._scene.getEngine();
  46079. var targetSize = this._mapSize / this.blurScale;
  46080. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  46081. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  46082. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46083. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46084. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46085. }
  46086. if (this.useKernelBlur) {
  46087. 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);
  46088. this._kernelBlurXPostprocess.width = targetSize;
  46089. this._kernelBlurXPostprocess.height = targetSize;
  46090. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  46091. effect.setTexture("textureSampler", _this._shadowMap);
  46092. });
  46093. 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);
  46094. this._kernelBlurXPostprocess.autoClear = false;
  46095. this._kernelBlurYPostprocess.autoClear = false;
  46096. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46097. this._kernelBlurXPostprocess.packedFloat = true;
  46098. this._kernelBlurYPostprocess.packedFloat = true;
  46099. }
  46100. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  46101. }
  46102. else {
  46103. 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);
  46104. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  46105. effect.setFloat2("screenSize", targetSize, targetSize);
  46106. effect.setTexture("textureSampler", _this._shadowMap);
  46107. });
  46108. this._boxBlurPostprocess.autoClear = false;
  46109. this._blurPostProcesses = [this._boxBlurPostprocess];
  46110. }
  46111. };
  46112. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46113. var index;
  46114. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46115. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  46116. }
  46117. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46118. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  46119. }
  46120. if (this._transparencyShadow) {
  46121. for (index = 0; index < transparentSubMeshes.length; index++) {
  46122. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  46123. }
  46124. }
  46125. };
  46126. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  46127. var _this = this;
  46128. var mesh = subMesh.getRenderingMesh();
  46129. var scene = this._scene;
  46130. var engine = scene.getEngine();
  46131. // Culling
  46132. engine.setState(subMesh.getMaterial().backFaceCulling);
  46133. // Managing instances
  46134. var batch = mesh._getInstancesRenderList(subMesh._id);
  46135. if (batch.mustReturn) {
  46136. return;
  46137. }
  46138. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  46139. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  46140. engine.enableEffect(this._effect);
  46141. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  46142. var material = subMesh.getMaterial();
  46143. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  46144. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  46145. this._effect.setVector3("lightPosition", this.getLight().position);
  46146. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  46147. // Alpha test
  46148. if (material && material.needAlphaTesting()) {
  46149. var alphaTexture = material.getAlphaTestTexture();
  46150. if (alphaTexture) {
  46151. this._effect.setTexture("diffuseSampler", alphaTexture);
  46152. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  46153. }
  46154. }
  46155. // Bones
  46156. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46157. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46158. }
  46159. if (this.forceBackFacesOnly) {
  46160. engine.setState(true, 0, false, true);
  46161. }
  46162. // Draw
  46163. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46164. if (this.forceBackFacesOnly) {
  46165. engine.setState(true, 0, false, false);
  46166. }
  46167. }
  46168. else {
  46169. // Need to reset refresh rate of the shadowMap
  46170. this._shadowMap.resetRefreshCounter();
  46171. }
  46172. };
  46173. ShadowGenerator.prototype._applyFilterValues = function () {
  46174. if (this.filter === ShadowGenerator.FILTER_NONE) {
  46175. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  46176. }
  46177. else {
  46178. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46179. }
  46180. };
  46181. /**
  46182. * Force shader compilation including textures ready check
  46183. */
  46184. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  46185. var _this = this;
  46186. var scene = this._scene;
  46187. var engine = scene.getEngine();
  46188. var subMeshes = new Array();
  46189. var currentIndex = 0;
  46190. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  46191. var mesh = _a[_i];
  46192. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  46193. }
  46194. var checkReady = function () {
  46195. if (!_this._scene || !_this._scene.getEngine()) {
  46196. return;
  46197. }
  46198. var subMesh = subMeshes[currentIndex];
  46199. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  46200. currentIndex++;
  46201. if (currentIndex >= subMeshes.length) {
  46202. if (onCompiled) {
  46203. onCompiled(_this);
  46204. }
  46205. return;
  46206. }
  46207. }
  46208. setTimeout(checkReady, 16);
  46209. };
  46210. if (subMeshes.length > 0) {
  46211. checkReady();
  46212. }
  46213. };
  46214. /**
  46215. * Boolean : true when the ShadowGenerator is finally computed.
  46216. */
  46217. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  46218. var defines = [];
  46219. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46220. defines.push("#define FLOAT");
  46221. }
  46222. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  46223. defines.push("#define ESM");
  46224. }
  46225. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46226. var mesh = subMesh.getMesh();
  46227. var material = subMesh.getMaterial();
  46228. // Alpha test
  46229. if (material && material.needAlphaTesting()) {
  46230. var alphaTexture = material.getAlphaTestTexture();
  46231. if (alphaTexture) {
  46232. defines.push("#define ALPHATEST");
  46233. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46234. attribs.push(BABYLON.VertexBuffer.UVKind);
  46235. defines.push("#define UV1");
  46236. }
  46237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46238. if (alphaTexture.coordinatesIndex === 1) {
  46239. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46240. defines.push("#define UV2");
  46241. }
  46242. }
  46243. }
  46244. }
  46245. // Bones
  46246. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46247. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46248. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46249. if (mesh.numBoneInfluencers > 4) {
  46250. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46251. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46252. }
  46253. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46254. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46255. }
  46256. else {
  46257. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46258. }
  46259. // Instances
  46260. if (useInstances) {
  46261. defines.push("#define INSTANCES");
  46262. attribs.push("world0");
  46263. attribs.push("world1");
  46264. attribs.push("world2");
  46265. attribs.push("world3");
  46266. }
  46267. // Get correct effect
  46268. var join = defines.join("\n");
  46269. if (this._cachedDefines !== join) {
  46270. this._cachedDefines = join;
  46271. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  46272. }
  46273. return this._effect.isReady();
  46274. };
  46275. /**
  46276. * This creates the defines related to the standard BJS materials.
  46277. */
  46278. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  46279. var scene = this._scene;
  46280. var light = this._light;
  46281. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  46282. return;
  46283. }
  46284. defines["SHADOW" + lightIndex] = true;
  46285. if (this.usePoissonSampling) {
  46286. defines["SHADOWPCF" + lightIndex] = true;
  46287. }
  46288. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  46289. defines["SHADOWESM" + lightIndex] = true;
  46290. }
  46291. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  46292. defines["SHADOWCLOSEESM" + lightIndex] = true;
  46293. }
  46294. if (light.needCube()) {
  46295. defines["SHADOWCUBE" + lightIndex] = true;
  46296. }
  46297. };
  46298. /**
  46299. * This binds shadow lights related to the standard BJS materials.
  46300. * It implies the unifroms available on the materials are the standard BJS ones.
  46301. */
  46302. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  46303. var light = this._light;
  46304. var scene = this._scene;
  46305. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  46306. return;
  46307. }
  46308. if (!light.needCube()) {
  46309. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  46310. }
  46311. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  46312. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  46313. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  46314. };
  46315. // Methods
  46316. /**
  46317. * Returns a Matrix object : the updated transformation matrix.
  46318. */
  46319. ShadowGenerator.prototype.getTransformMatrix = function () {
  46320. var scene = this._scene;
  46321. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  46322. return this._transformMatrix;
  46323. }
  46324. this._currentRenderID = scene.getRenderId();
  46325. this._currentFaceIndexCache = this._currentFaceIndex;
  46326. var lightPosition = this._light.position;
  46327. if (this._light.computeTransformedInformation()) {
  46328. lightPosition = this._light.transformedPosition;
  46329. }
  46330. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  46331. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  46332. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  46333. }
  46334. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  46335. this._cachedPosition = lightPosition.clone();
  46336. this._cachedDirection = this._lightDirection.clone();
  46337. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  46338. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  46339. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  46340. }
  46341. return this._transformMatrix;
  46342. };
  46343. ShadowGenerator.prototype.recreateShadowMap = function () {
  46344. // Track render list.
  46345. var renderList = this._shadowMap.renderList;
  46346. // Clean up existing data.
  46347. this._disposeRTTandPostProcesses();
  46348. // Reinitializes.
  46349. this._initializeGenerator();
  46350. // Reaffect the filter to ensure a correct fallback if necessary.
  46351. this.filter = this.filter;
  46352. // Reaffect the filter.
  46353. this._applyFilterValues();
  46354. // Reaffect Render List.
  46355. this._shadowMap.renderList = renderList;
  46356. };
  46357. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  46358. if (this._shadowMap2) {
  46359. this._shadowMap2.dispose();
  46360. this._shadowMap2 = null;
  46361. }
  46362. if (this._downSamplePostprocess) {
  46363. this._downSamplePostprocess.dispose();
  46364. this._downSamplePostprocess = null;
  46365. }
  46366. if (this._boxBlurPostprocess) {
  46367. this._boxBlurPostprocess.dispose();
  46368. this._boxBlurPostprocess = null;
  46369. }
  46370. if (this._kernelBlurXPostprocess) {
  46371. this._kernelBlurXPostprocess.dispose();
  46372. this._kernelBlurXPostprocess = null;
  46373. }
  46374. if (this._kernelBlurYPostprocess) {
  46375. this._kernelBlurYPostprocess.dispose();
  46376. this._kernelBlurYPostprocess = null;
  46377. }
  46378. this._blurPostProcesses = null;
  46379. };
  46380. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  46381. if (this._shadowMap) {
  46382. this._shadowMap.dispose();
  46383. this._shadowMap = null;
  46384. }
  46385. this._disposeBlurPostProcesses();
  46386. };
  46387. /**
  46388. * Disposes the ShadowGenerator.
  46389. * Returns nothing.
  46390. */
  46391. ShadowGenerator.prototype.dispose = function () {
  46392. this._disposeRTTandPostProcesses();
  46393. this._light._shadowGenerator = null;
  46394. this._light._markMeshesAsLightDirty();
  46395. };
  46396. /**
  46397. * Serializes the ShadowGenerator and returns a serializationObject.
  46398. */
  46399. ShadowGenerator.prototype.serialize = function () {
  46400. var serializationObject = {};
  46401. var shadowMap = this.getShadowMap();
  46402. serializationObject.lightId = this._light.id;
  46403. serializationObject.mapSize = shadowMap.getRenderSize();
  46404. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  46405. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  46406. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  46407. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  46408. serializationObject.usePoissonSampling = this.usePoissonSampling;
  46409. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  46410. serializationObject.depthScale = this.depthScale;
  46411. serializationObject.darkness = this.getDarkness();
  46412. serializationObject.blurBoxOffset = this.blurBoxOffset;
  46413. serializationObject.blurKernel = this.blurKernel;
  46414. serializationObject.blurScale = this.blurScale;
  46415. serializationObject.useKernelBlur = this.useKernelBlur;
  46416. serializationObject.transparencyShadow = this._transparencyShadow;
  46417. serializationObject.renderList = [];
  46418. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  46419. var mesh = shadowMap.renderList[meshIndex];
  46420. serializationObject.renderList.push(mesh.id);
  46421. }
  46422. return serializationObject;
  46423. };
  46424. /**
  46425. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  46426. */
  46427. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  46428. //casting to point light, as light is missing the position attr and typescript complains.
  46429. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  46430. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  46431. var shadowMap = shadowGenerator.getShadowMap();
  46432. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  46433. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  46434. meshes.forEach(function (mesh) {
  46435. shadowMap.renderList.push(mesh);
  46436. });
  46437. }
  46438. if (parsedShadowGenerator.usePoissonSampling) {
  46439. shadowGenerator.usePoissonSampling = true;
  46440. }
  46441. else if (parsedShadowGenerator.useExponentialShadowMap) {
  46442. shadowGenerator.useExponentialShadowMap = true;
  46443. }
  46444. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  46445. shadowGenerator.useBlurExponentialShadowMap = true;
  46446. }
  46447. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  46448. shadowGenerator.useCloseExponentialShadowMap = true;
  46449. }
  46450. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  46451. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  46452. }
  46453. else if (parsedShadowGenerator.useVarianceShadowMap) {
  46454. shadowGenerator.useExponentialShadowMap = true;
  46455. }
  46456. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  46457. shadowGenerator.useBlurExponentialShadowMap = true;
  46458. }
  46459. if (parsedShadowGenerator.depthScale) {
  46460. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  46461. }
  46462. if (parsedShadowGenerator.blurScale) {
  46463. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  46464. }
  46465. if (parsedShadowGenerator.blurBoxOffset) {
  46466. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  46467. }
  46468. if (parsedShadowGenerator.useKernelBlur) {
  46469. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  46470. }
  46471. if (parsedShadowGenerator.blurKernel) {
  46472. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  46473. }
  46474. if (parsedShadowGenerator.bias !== undefined) {
  46475. shadowGenerator.bias = parsedShadowGenerator.bias;
  46476. }
  46477. if (parsedShadowGenerator.darkness) {
  46478. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  46479. }
  46480. if (parsedShadowGenerator.transparencyShadow) {
  46481. shadowGenerator.setTransparencyShadow(true);
  46482. }
  46483. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  46484. return shadowGenerator;
  46485. };
  46486. return ShadowGenerator;
  46487. }());
  46488. ShadowGenerator._FILTER_NONE = 0;
  46489. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  46490. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  46491. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  46492. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  46493. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  46494. BABYLON.ShadowGenerator = ShadowGenerator;
  46495. })(BABYLON || (BABYLON = {}));
  46496. //# sourceMappingURL=babylon.shadowGenerator.js.map
  46497. var BABYLON;
  46498. (function (BABYLON) {
  46499. var DefaultLoadingScreen = (function () {
  46500. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  46501. if (_loadingText === void 0) { _loadingText = ""; }
  46502. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  46503. var _this = this;
  46504. this._renderingCanvas = _renderingCanvas;
  46505. this._loadingText = _loadingText;
  46506. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  46507. // Resize
  46508. this._resizeLoadingUI = function () {
  46509. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  46510. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  46511. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  46512. _this._loadingDiv.style.left = canvasRect.left + "px";
  46513. _this._loadingDiv.style.top = canvasRect.top + "px";
  46514. _this._loadingDiv.style.width = canvasRect.width + "px";
  46515. _this._loadingDiv.style.height = canvasRect.height + "px";
  46516. };
  46517. }
  46518. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  46519. if (this._loadingDiv) {
  46520. // Do not add a loading screen if there is already one
  46521. return;
  46522. }
  46523. this._loadingDiv = document.createElement("div");
  46524. this._loadingDiv.id = "babylonjsLoadingDiv";
  46525. this._loadingDiv.style.opacity = "0";
  46526. this._loadingDiv.style.transition = "opacity 1.5s ease";
  46527. // Loading text
  46528. this._loadingTextDiv = document.createElement("div");
  46529. this._loadingTextDiv.style.position = "absolute";
  46530. this._loadingTextDiv.style.left = "0";
  46531. this._loadingTextDiv.style.top = "50%";
  46532. this._loadingTextDiv.style.marginTop = "80px";
  46533. this._loadingTextDiv.style.width = "100%";
  46534. this._loadingTextDiv.style.height = "20px";
  46535. this._loadingTextDiv.style.fontFamily = "Arial";
  46536. this._loadingTextDiv.style.fontSize = "14px";
  46537. this._loadingTextDiv.style.color = "white";
  46538. this._loadingTextDiv.style.textAlign = "center";
  46539. this._loadingTextDiv.innerHTML = "Loading";
  46540. this._loadingDiv.appendChild(this._loadingTextDiv);
  46541. //set the predefined text
  46542. this._loadingTextDiv.innerHTML = this._loadingText;
  46543. // Generating keyframes
  46544. var style = document.createElement('style');
  46545. style.type = 'text/css';
  46546. 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 }";
  46547. style.innerHTML = keyFrames;
  46548. document.getElementsByTagName('head')[0].appendChild(style);
  46549. // Loading img
  46550. var imgBack = new Image();
  46551. 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";
  46552. imgBack.style.position = "absolute";
  46553. imgBack.style.left = "50%";
  46554. imgBack.style.top = "50%";
  46555. imgBack.style.marginLeft = "-60px";
  46556. imgBack.style.marginTop = "-60px";
  46557. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  46558. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  46559. imgBack.style.transformOrigin = "50% 50%";
  46560. imgBack.style.webkitTransformOrigin = "50% 50%";
  46561. this._loadingDiv.appendChild(imgBack);
  46562. this._resizeLoadingUI();
  46563. window.addEventListener("resize", this._resizeLoadingUI);
  46564. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  46565. document.body.appendChild(this._loadingDiv);
  46566. this._loadingDiv.style.opacity = "1";
  46567. };
  46568. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  46569. var _this = this;
  46570. if (!this._loadingDiv) {
  46571. return;
  46572. }
  46573. var onTransitionEnd = function () {
  46574. if (!_this._loadingDiv) {
  46575. return;
  46576. }
  46577. document.body.removeChild(_this._loadingDiv);
  46578. window.removeEventListener("resize", _this._resizeLoadingUI);
  46579. _this._loadingDiv = null;
  46580. };
  46581. this._loadingDiv.style.opacity = "0";
  46582. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  46583. };
  46584. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  46585. set: function (text) {
  46586. this._loadingText = text;
  46587. if (this._loadingTextDiv) {
  46588. this._loadingTextDiv.innerHTML = this._loadingText;
  46589. }
  46590. },
  46591. enumerable: true,
  46592. configurable: true
  46593. });
  46594. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  46595. get: function () {
  46596. return this._loadingDivBackgroundColor;
  46597. },
  46598. set: function (color) {
  46599. this._loadingDivBackgroundColor = color;
  46600. if (!this._loadingDiv) {
  46601. return;
  46602. }
  46603. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  46604. },
  46605. enumerable: true,
  46606. configurable: true
  46607. });
  46608. return DefaultLoadingScreen;
  46609. }());
  46610. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  46611. })(BABYLON || (BABYLON = {}));
  46612. //# sourceMappingURL=babylon.loadingScreen.js.map
  46613. var BABYLON;
  46614. (function (BABYLON) {
  46615. var SceneLoader = (function () {
  46616. function SceneLoader() {
  46617. }
  46618. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  46619. get: function () {
  46620. return 0;
  46621. },
  46622. enumerable: true,
  46623. configurable: true
  46624. });
  46625. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  46626. get: function () {
  46627. return 1;
  46628. },
  46629. enumerable: true,
  46630. configurable: true
  46631. });
  46632. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  46633. get: function () {
  46634. return 2;
  46635. },
  46636. enumerable: true,
  46637. configurable: true
  46638. });
  46639. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  46640. get: function () {
  46641. return 3;
  46642. },
  46643. enumerable: true,
  46644. configurable: true
  46645. });
  46646. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  46647. get: function () {
  46648. return SceneLoader._ForceFullSceneLoadingForIncremental;
  46649. },
  46650. set: function (value) {
  46651. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  46652. },
  46653. enumerable: true,
  46654. configurable: true
  46655. });
  46656. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  46657. get: function () {
  46658. return SceneLoader._ShowLoadingScreen;
  46659. },
  46660. set: function (value) {
  46661. SceneLoader._ShowLoadingScreen = value;
  46662. },
  46663. enumerable: true,
  46664. configurable: true
  46665. });
  46666. Object.defineProperty(SceneLoader, "loggingLevel", {
  46667. get: function () {
  46668. return SceneLoader._loggingLevel;
  46669. },
  46670. set: function (value) {
  46671. SceneLoader._loggingLevel = value;
  46672. },
  46673. enumerable: true,
  46674. configurable: true
  46675. });
  46676. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  46677. get: function () {
  46678. return SceneLoader._CleanBoneMatrixWeights;
  46679. },
  46680. set: function (value) {
  46681. SceneLoader._CleanBoneMatrixWeights = value;
  46682. },
  46683. enumerable: true,
  46684. configurable: true
  46685. });
  46686. SceneLoader._getDefaultPlugin = function () {
  46687. return SceneLoader._registeredPlugins[".babylon"];
  46688. };
  46689. SceneLoader._getPluginForExtension = function (extension) {
  46690. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  46691. if (registeredPlugin) {
  46692. return registeredPlugin;
  46693. }
  46694. return SceneLoader._getDefaultPlugin();
  46695. };
  46696. SceneLoader._getPluginForDirectLoad = function (data) {
  46697. for (var extension in SceneLoader._registeredPlugins) {
  46698. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  46699. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  46700. return SceneLoader._registeredPlugins[extension];
  46701. }
  46702. }
  46703. return SceneLoader._getDefaultPlugin();
  46704. };
  46705. SceneLoader._getPluginForFilename = function (sceneFilename) {
  46706. if (sceneFilename.name) {
  46707. sceneFilename = sceneFilename.name;
  46708. }
  46709. var dotPosition = sceneFilename.lastIndexOf(".");
  46710. var queryStringPosition = sceneFilename.indexOf("?");
  46711. if (queryStringPosition === -1) {
  46712. queryStringPosition = sceneFilename.length;
  46713. }
  46714. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  46715. return SceneLoader._getPluginForExtension(extension);
  46716. };
  46717. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  46718. SceneLoader._getDirectLoad = function (sceneFilename) {
  46719. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  46720. return sceneFilename.substr(5);
  46721. }
  46722. return null;
  46723. };
  46724. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  46725. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  46726. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  46727. var plugin = registeredPlugin.plugin;
  46728. var useArrayBuffer = registeredPlugin.isBinary;
  46729. var database;
  46730. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  46731. var dataCallback = function (data) {
  46732. if (scene.isDisposed) {
  46733. onError("Scene has been disposed");
  46734. return;
  46735. }
  46736. scene.database = database;
  46737. try {
  46738. onSuccess(plugin, data);
  46739. }
  46740. catch (e) {
  46741. onError(null, e);
  46742. }
  46743. };
  46744. var manifestChecked = function (success) {
  46745. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  46746. onError(request.status + " " + request.statusText);
  46747. });
  46748. };
  46749. if (directLoad) {
  46750. dataCallback(directLoad);
  46751. return;
  46752. }
  46753. if (rootUrl.indexOf("file:") === -1) {
  46754. if (scene.getEngine().enableOfflineSupport) {
  46755. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  46756. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  46757. }
  46758. else {
  46759. manifestChecked(true);
  46760. }
  46761. }
  46762. else {
  46763. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  46764. }
  46765. };
  46766. // Public functions
  46767. SceneLoader.GetPluginForExtension = function (extension) {
  46768. return SceneLoader._getPluginForExtension(extension).plugin;
  46769. };
  46770. SceneLoader.RegisterPlugin = function (plugin) {
  46771. if (typeof plugin.extensions === "string") {
  46772. var extension = plugin.extensions;
  46773. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  46774. plugin: plugin,
  46775. isBinary: false
  46776. };
  46777. }
  46778. else {
  46779. var extensions = plugin.extensions;
  46780. Object.keys(extensions).forEach(function (extension) {
  46781. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  46782. plugin: plugin,
  46783. isBinary: extensions[extension].isBinary
  46784. };
  46785. });
  46786. }
  46787. };
  46788. /**
  46789. * Import meshes into a scene
  46790. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  46791. * @param rootUrl a string that defines the root url for scene and resources
  46792. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  46793. * @param scene the instance of BABYLON.Scene to append to
  46794. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  46795. * @param onProgress a callback with a progress event for each file being loaded
  46796. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  46797. */
  46798. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  46799. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  46800. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  46801. return;
  46802. }
  46803. var loadingToken = {};
  46804. scene._addPendingData(loadingToken);
  46805. var errorHandler = function (message, exception) {
  46806. if (onError) {
  46807. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  46808. }
  46809. scene._removePendingData(loadingToken);
  46810. };
  46811. var progressHandler = function (event) {
  46812. if (onProgress) {
  46813. onProgress(event);
  46814. }
  46815. };
  46816. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  46817. if (plugin.importMesh) {
  46818. var syncedPlugin = plugin;
  46819. var meshes = [];
  46820. var particleSystems = [];
  46821. var skeletons = [];
  46822. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  46823. return;
  46824. }
  46825. if (onSuccess) {
  46826. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  46827. onSuccess(meshes, particleSystems, skeletons);
  46828. scene._removePendingData(loadingToken);
  46829. }
  46830. }
  46831. else {
  46832. var asyncedPlugin = plugin;
  46833. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  46834. if (onSuccess) {
  46835. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  46836. onSuccess(meshes, particleSystems, skeletons);
  46837. scene._removePendingData(loadingToken);
  46838. }
  46839. }, progressHandler, errorHandler);
  46840. }
  46841. }, progressHandler, errorHandler);
  46842. };
  46843. /**
  46844. * Load a scene
  46845. * @param rootUrl a string that defines the root url for scene and resources
  46846. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  46847. * @param engine is the instance of BABYLON.Engine to use to create the scene
  46848. * @param onSuccess a callback with the scene when import succeeds
  46849. * @param onProgress a callback with a progress event for each file being loaded
  46850. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  46851. */
  46852. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  46853. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  46854. };
  46855. /**
  46856. * Append a scene
  46857. * @param rootUrl a string that defines the root url for scene and resources
  46858. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  46859. * @param scene is the instance of BABYLON.Scene to append to
  46860. * @param onSuccess a callback with the scene when import succeeds
  46861. * @param onProgress a callback with a progress event for each file being loaded
  46862. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  46863. */
  46864. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  46865. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  46866. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  46867. return;
  46868. }
  46869. if (SceneLoader.ShowLoadingScreen) {
  46870. scene.getEngine().displayLoadingUI();
  46871. }
  46872. var loadingToken = {};
  46873. scene._addPendingData(loadingToken);
  46874. var errorHandler = function (message, exception) {
  46875. if (onError) {
  46876. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  46877. }
  46878. scene._removePendingData(loadingToken);
  46879. scene.getEngine().hideLoadingUI();
  46880. };
  46881. var progressHandler = function (event) {
  46882. if (onProgress) {
  46883. onProgress(event);
  46884. }
  46885. };
  46886. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  46887. if (plugin.load) {
  46888. var syncedPlugin = plugin;
  46889. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  46890. return;
  46891. }
  46892. if (onSuccess) {
  46893. onSuccess(scene);
  46894. }
  46895. scene.loadingPluginName = plugin.name;
  46896. scene._removePendingData(loadingToken);
  46897. }
  46898. else {
  46899. var asyncedPlugin = plugin;
  46900. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  46901. if (onSuccess) {
  46902. onSuccess(scene);
  46903. }
  46904. scene.loadingPluginName = plugin.name;
  46905. scene._removePendingData(loadingToken);
  46906. }, progressHandler, errorHandler);
  46907. }
  46908. if (SceneLoader.ShowLoadingScreen) {
  46909. scene.executeWhenReady(function () {
  46910. scene.getEngine().hideLoadingUI();
  46911. });
  46912. }
  46913. }, progressHandler, errorHandler);
  46914. };
  46915. return SceneLoader;
  46916. }());
  46917. // Flags
  46918. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  46919. SceneLoader._ShowLoadingScreen = true;
  46920. SceneLoader._CleanBoneMatrixWeights = false;
  46921. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  46922. // Members
  46923. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  46924. SceneLoader._registeredPlugins = {};
  46925. BABYLON.SceneLoader = SceneLoader;
  46926. ;
  46927. })(BABYLON || (BABYLON = {}));
  46928. //# sourceMappingURL=babylon.sceneLoader.js.map
  46929. var BABYLON;
  46930. (function (BABYLON) {
  46931. var Internals;
  46932. (function (Internals) {
  46933. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  46934. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  46935. var parsedMaterial = parsedData.materials[index];
  46936. if (parsedMaterial.id === id) {
  46937. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  46938. }
  46939. }
  46940. return null;
  46941. };
  46942. var isDescendantOf = function (mesh, names, hierarchyIds) {
  46943. for (var i in names) {
  46944. if (mesh.name === names[i]) {
  46945. hierarchyIds.push(mesh.id);
  46946. return true;
  46947. }
  46948. }
  46949. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  46950. hierarchyIds.push(mesh.id);
  46951. return true;
  46952. }
  46953. return false;
  46954. };
  46955. var logOperation = function (operation, producer) {
  46956. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  46957. };
  46958. BABYLON.SceneLoader.RegisterPlugin({
  46959. name: "babylon.js",
  46960. extensions: ".babylon",
  46961. canDirectLoad: function (data) {
  46962. if (data.indexOf("babylon") !== -1) {
  46963. return true;
  46964. }
  46965. return false;
  46966. },
  46967. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  46968. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  46969. // when SceneLoader.debugLogging = true (default), or exception encountered.
  46970. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  46971. // and avoid problems with multiple concurrent .babylon loads.
  46972. var log = "importMesh has failed JSON parse";
  46973. try {
  46974. var parsedData = JSON.parse(data);
  46975. log = "";
  46976. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  46977. if (!meshesNames) {
  46978. meshesNames = null;
  46979. }
  46980. else if (!Array.isArray(meshesNames)) {
  46981. meshesNames = [meshesNames];
  46982. }
  46983. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  46984. var loadedSkeletonsIds = [];
  46985. var loadedMaterialsIds = [];
  46986. var hierarchyIds = [];
  46987. var index;
  46988. var cache;
  46989. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  46990. var parsedMesh = parsedData.meshes[index];
  46991. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  46992. if (meshesNames !== null) {
  46993. // Remove found mesh name from list.
  46994. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  46995. }
  46996. //Geometry?
  46997. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  46998. //does the file contain geometries?
  46999. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  47000. //find the correct geometry and add it to the scene
  47001. var found = false;
  47002. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47003. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  47004. return;
  47005. }
  47006. else {
  47007. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47008. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47009. switch (geometryType) {
  47010. case "boxes":
  47011. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47012. break;
  47013. case "spheres":
  47014. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47015. break;
  47016. case "cylinders":
  47017. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47018. break;
  47019. case "toruses":
  47020. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47021. break;
  47022. case "grounds":
  47023. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47024. break;
  47025. case "planes":
  47026. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47027. break;
  47028. case "torusKnots":
  47029. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47030. break;
  47031. case "vertexData":
  47032. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47033. break;
  47034. }
  47035. found = true;
  47036. }
  47037. });
  47038. }
  47039. });
  47040. if (found === false) {
  47041. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47042. }
  47043. }
  47044. }
  47045. // Material ?
  47046. if (parsedMesh.materialId) {
  47047. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47048. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  47049. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47050. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47051. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47052. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47053. var subMatId = parsedMultiMaterial.materials[matIndex];
  47054. loadedMaterialsIds.push(subMatId);
  47055. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47056. log += "\n\tMaterial " + mat.toString(fullDetails);
  47057. }
  47058. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47059. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47060. materialFound = true;
  47061. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47062. break;
  47063. }
  47064. }
  47065. }
  47066. if (materialFound === false) {
  47067. loadedMaterialsIds.push(parsedMesh.materialId);
  47068. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47069. if (!mat) {
  47070. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47071. }
  47072. else {
  47073. log += "\n\tMaterial " + mat.toString(fullDetails);
  47074. }
  47075. }
  47076. }
  47077. // Skeleton ?
  47078. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  47079. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47080. if (skeletonAlreadyLoaded === false) {
  47081. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47082. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47083. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47084. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47085. skeletons.push(skeleton);
  47086. loadedSkeletonsIds.push(parsedSkeleton.id);
  47087. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47088. }
  47089. }
  47090. }
  47091. }
  47092. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47093. meshes.push(mesh);
  47094. log += "\n\tMesh " + mesh.toString(fullDetails);
  47095. }
  47096. }
  47097. // Connecting parents
  47098. var currentMesh;
  47099. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47100. currentMesh = scene.meshes[index];
  47101. if (currentMesh._waitingParentId) {
  47102. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47103. currentMesh._waitingParentId = undefined;
  47104. }
  47105. }
  47106. // freeze and compute world matrix application
  47107. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47108. currentMesh = scene.meshes[index];
  47109. if (currentMesh._waitingFreezeWorldMatrix) {
  47110. currentMesh.freezeWorldMatrix();
  47111. currentMesh._waitingFreezeWorldMatrix = undefined;
  47112. }
  47113. else {
  47114. currentMesh.computeWorldMatrix(true);
  47115. }
  47116. }
  47117. }
  47118. // Particles
  47119. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  47120. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47121. var parsedParticleSystem = parsedData.particleSystems[index];
  47122. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  47123. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  47124. }
  47125. }
  47126. }
  47127. return true;
  47128. }
  47129. catch (err) {
  47130. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  47131. log = null;
  47132. throw err;
  47133. }
  47134. finally {
  47135. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47136. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47137. }
  47138. }
  47139. },
  47140. load: function (scene, data, rootUrl) {
  47141. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47142. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47143. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47144. // and avoid problems with multiple concurrent .babylon loads.
  47145. var log = "importScene has failed JSON parse";
  47146. try {
  47147. var parsedData = JSON.parse(data);
  47148. log = "";
  47149. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47150. // Scene
  47151. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  47152. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  47153. }
  47154. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  47155. scene.autoClear = parsedData.autoClear;
  47156. }
  47157. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  47158. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  47159. }
  47160. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  47161. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  47162. }
  47163. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  47164. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  47165. }
  47166. // Fog
  47167. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  47168. scene.fogMode = parsedData.fogMode;
  47169. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  47170. scene.fogStart = parsedData.fogStart;
  47171. scene.fogEnd = parsedData.fogEnd;
  47172. scene.fogDensity = parsedData.fogDensity;
  47173. log += "\tFog mode for scene: ";
  47174. switch (scene.fogMode) {
  47175. // getters not compiling, so using hardcoded
  47176. case 1:
  47177. log += "exp\n";
  47178. break;
  47179. case 2:
  47180. log += "exp2\n";
  47181. break;
  47182. case 3:
  47183. log += "linear\n";
  47184. break;
  47185. }
  47186. }
  47187. //Physics
  47188. if (parsedData.physicsEnabled) {
  47189. var physicsPlugin;
  47190. if (parsedData.physicsEngine === "cannon") {
  47191. physicsPlugin = new BABYLON.CannonJSPlugin();
  47192. }
  47193. else if (parsedData.physicsEngine === "oimo") {
  47194. physicsPlugin = new BABYLON.OimoJSPlugin();
  47195. }
  47196. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  47197. //else - default engine, which is currently oimo
  47198. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  47199. scene.enablePhysics(physicsGravity, physicsPlugin);
  47200. }
  47201. // Metadata
  47202. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  47203. scene.metadata = parsedData.metadata;
  47204. }
  47205. //collisions, if defined. otherwise, default is true
  47206. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  47207. scene.collisionsEnabled = parsedData.collisionsEnabled;
  47208. }
  47209. scene.workerCollisions = !!parsedData.workerCollisions;
  47210. var index;
  47211. var cache;
  47212. // Lights
  47213. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  47214. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  47215. var parsedLight = parsedData.lights[index];
  47216. var light = BABYLON.Light.Parse(parsedLight, scene);
  47217. log += (index === 0 ? "\n\tLights:" : "");
  47218. log += "\n\t\t" + light.toString(fullDetails);
  47219. }
  47220. }
  47221. // Animations
  47222. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  47223. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  47224. var parsedAnimation = parsedData.animations[index];
  47225. var animation = BABYLON.Animation.Parse(parsedAnimation);
  47226. scene.animations.push(animation);
  47227. log += (index === 0 ? "\n\tAnimations:" : "");
  47228. log += "\n\t\t" + animation.toString(fullDetails);
  47229. }
  47230. }
  47231. if (parsedData.autoAnimate) {
  47232. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  47233. }
  47234. // Materials
  47235. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  47236. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47237. var parsedMaterial = parsedData.materials[index];
  47238. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47239. log += (index === 0 ? "\n\tMaterials:" : "");
  47240. log += "\n\t\t" + mat.toString(fullDetails);
  47241. }
  47242. }
  47243. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  47244. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  47245. var parsedMultiMaterial = parsedData.multiMaterials[index];
  47246. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47247. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  47248. log += "\n\t\t" + mmat.toString(fullDetails);
  47249. }
  47250. }
  47251. // Morph targets
  47252. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  47253. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  47254. var managerData = _a[_i];
  47255. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  47256. }
  47257. }
  47258. // Skeletons
  47259. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  47260. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  47261. var parsedSkeleton = parsedData.skeletons[index];
  47262. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47263. log += (index === 0 ? "\n\tSkeletons:" : "");
  47264. log += "\n\t\t" + skeleton.toString(fullDetails);
  47265. }
  47266. }
  47267. // Geometries
  47268. var geometries = parsedData.geometries;
  47269. if (geometries !== undefined && geometries !== null) {
  47270. // Boxes
  47271. var boxes = geometries.boxes;
  47272. if (boxes !== undefined && boxes !== null) {
  47273. for (index = 0, cache = boxes.length; index < cache; index++) {
  47274. var parsedBox = boxes[index];
  47275. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  47276. }
  47277. }
  47278. // Spheres
  47279. var spheres = geometries.spheres;
  47280. if (spheres !== undefined && spheres !== null) {
  47281. for (index = 0, cache = spheres.length; index < cache; index++) {
  47282. var parsedSphere = spheres[index];
  47283. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  47284. }
  47285. }
  47286. // Cylinders
  47287. var cylinders = geometries.cylinders;
  47288. if (cylinders !== undefined && cylinders !== null) {
  47289. for (index = 0, cache = cylinders.length; index < cache; index++) {
  47290. var parsedCylinder = cylinders[index];
  47291. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  47292. }
  47293. }
  47294. // Toruses
  47295. var toruses = geometries.toruses;
  47296. if (toruses !== undefined && toruses !== null) {
  47297. for (index = 0, cache = toruses.length; index < cache; index++) {
  47298. var parsedTorus = toruses[index];
  47299. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  47300. }
  47301. }
  47302. // Grounds
  47303. var grounds = geometries.grounds;
  47304. if (grounds !== undefined && grounds !== null) {
  47305. for (index = 0, cache = grounds.length; index < cache; index++) {
  47306. var parsedGround = grounds[index];
  47307. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  47308. }
  47309. }
  47310. // Planes
  47311. var planes = geometries.planes;
  47312. if (planes !== undefined && planes !== null) {
  47313. for (index = 0, cache = planes.length; index < cache; index++) {
  47314. var parsedPlane = planes[index];
  47315. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  47316. }
  47317. }
  47318. // TorusKnots
  47319. var torusKnots = geometries.torusKnots;
  47320. if (torusKnots !== undefined && torusKnots !== null) {
  47321. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  47322. var parsedTorusKnot = torusKnots[index];
  47323. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  47324. }
  47325. }
  47326. // VertexData
  47327. var vertexData = geometries.vertexData;
  47328. if (vertexData !== undefined && vertexData !== null) {
  47329. for (index = 0, cache = vertexData.length; index < cache; index++) {
  47330. var parsedVertexData = vertexData[index];
  47331. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  47332. }
  47333. }
  47334. }
  47335. // Meshes
  47336. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  47337. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47338. var parsedMesh = parsedData.meshes[index];
  47339. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47340. log += (index === 0 ? "\n\tMeshes:" : "");
  47341. log += "\n\t\t" + mesh.toString(fullDetails);
  47342. }
  47343. }
  47344. // Cameras
  47345. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  47346. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  47347. var parsedCamera = parsedData.cameras[index];
  47348. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  47349. log += (index === 0 ? "\n\tCameras:" : "");
  47350. log += "\n\t\t" + camera.toString(fullDetails);
  47351. }
  47352. }
  47353. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  47354. scene.setActiveCameraByID(parsedData.activeCameraID);
  47355. }
  47356. // Browsing all the graph to connect the dots
  47357. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  47358. var camera = scene.cameras[index];
  47359. if (camera._waitingParentId) {
  47360. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  47361. camera._waitingParentId = undefined;
  47362. }
  47363. }
  47364. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47365. var light = scene.lights[index];
  47366. if (light._waitingParentId) {
  47367. light.parent = scene.getLastEntryByID(light._waitingParentId);
  47368. light._waitingParentId = undefined;
  47369. }
  47370. }
  47371. // Sounds
  47372. var loadedSounds = [];
  47373. var loadedSound;
  47374. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  47375. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  47376. var parsedSound = parsedData.sounds[index];
  47377. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47378. if (!parsedSound.url)
  47379. parsedSound.url = parsedSound.name;
  47380. if (!loadedSounds[parsedSound.url]) {
  47381. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  47382. loadedSounds[parsedSound.url] = loadedSound;
  47383. }
  47384. else {
  47385. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  47386. }
  47387. }
  47388. else {
  47389. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  47390. }
  47391. }
  47392. }
  47393. loadedSounds = [];
  47394. // Connect parents & children and parse actions
  47395. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47396. var mesh = scene.meshes[index];
  47397. if (mesh._waitingParentId) {
  47398. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  47399. mesh._waitingParentId = undefined;
  47400. }
  47401. if (mesh._waitingActions) {
  47402. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  47403. mesh._waitingActions = undefined;
  47404. }
  47405. }
  47406. // freeze world matrix application
  47407. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47408. var currentMesh = scene.meshes[index];
  47409. if (currentMesh._waitingFreezeWorldMatrix) {
  47410. currentMesh.freezeWorldMatrix();
  47411. currentMesh._waitingFreezeWorldMatrix = undefined;
  47412. }
  47413. else {
  47414. currentMesh.computeWorldMatrix(true);
  47415. }
  47416. }
  47417. // Particles Systems
  47418. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  47419. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47420. var parsedParticleSystem = parsedData.particleSystems[index];
  47421. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  47422. }
  47423. }
  47424. // Lens flares
  47425. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  47426. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  47427. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  47428. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  47429. }
  47430. }
  47431. // Shadows
  47432. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  47433. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  47434. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  47435. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  47436. }
  47437. }
  47438. // Lights exclusions / inclusions
  47439. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47440. var light = scene.lights[index];
  47441. // Excluded check
  47442. if (light._excludedMeshesIds.length > 0) {
  47443. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  47444. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  47445. if (excludedMesh) {
  47446. light.excludedMeshes.push(excludedMesh);
  47447. }
  47448. }
  47449. light._excludedMeshesIds = [];
  47450. }
  47451. // Included check
  47452. if (light._includedOnlyMeshesIds.length > 0) {
  47453. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  47454. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  47455. if (includedOnlyMesh) {
  47456. light.includedOnlyMeshes.push(includedOnlyMesh);
  47457. }
  47458. }
  47459. light._includedOnlyMeshesIds = [];
  47460. }
  47461. }
  47462. // Actions (scene)
  47463. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  47464. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  47465. }
  47466. // Finish
  47467. return true;
  47468. }
  47469. catch (err) {
  47470. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  47471. log = null;
  47472. throw err;
  47473. }
  47474. finally {
  47475. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47476. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47477. }
  47478. }
  47479. }
  47480. });
  47481. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47482. })(BABYLON || (BABYLON = {}));
  47483. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  47484. var BABYLON;
  47485. (function (BABYLON) {
  47486. var FilesInput = (function () {
  47487. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  47488. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  47489. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  47490. this._engine = p_engine;
  47491. this._canvas = p_canvas;
  47492. this._currentScene = p_scene;
  47493. this._sceneLoadedCallback = p_sceneLoadedCallback;
  47494. this._progressCallback = p_progressCallback;
  47495. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  47496. this._textureLoadingCallback = p_textureLoadingCallback;
  47497. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  47498. }
  47499. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  47500. var _this = this;
  47501. if (p_elementToMonitor) {
  47502. this._elementToMonitor = p_elementToMonitor;
  47503. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  47504. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  47505. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  47506. }
  47507. };
  47508. FilesInput.prototype.renderFunction = function () {
  47509. if (this._additionnalRenderLoopLogicCallback) {
  47510. this._additionnalRenderLoopLogicCallback();
  47511. }
  47512. if (this._currentScene) {
  47513. if (this._textureLoadingCallback) {
  47514. var remaining = this._currentScene.getWaitingItemsCount();
  47515. if (remaining > 0) {
  47516. this._textureLoadingCallback(remaining);
  47517. }
  47518. }
  47519. this._currentScene.render();
  47520. }
  47521. };
  47522. FilesInput.prototype.drag = function (e) {
  47523. e.stopPropagation();
  47524. e.preventDefault();
  47525. };
  47526. FilesInput.prototype.drop = function (eventDrop) {
  47527. eventDrop.stopPropagation();
  47528. eventDrop.preventDefault();
  47529. this.loadFiles(eventDrop);
  47530. };
  47531. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  47532. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  47533. reader.readEntries(function (fileEntries) {
  47534. var remaining = fileEntries.length;
  47535. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  47536. var fileEntry = fileEntries_1[_i];
  47537. if (fileEntry.isFile) {
  47538. fileEntry.file(function (file) {
  47539. file.correctName = relativePath + file.name;
  47540. files.push(file);
  47541. remaining--;
  47542. if (remaining === 0) {
  47543. callback();
  47544. }
  47545. });
  47546. }
  47547. else {
  47548. remaining--;
  47549. if (remaining === 0) {
  47550. callback();
  47551. }
  47552. }
  47553. }
  47554. });
  47555. };
  47556. FilesInput.prototype._processFiles = function (files) {
  47557. for (var i = 0; i < files.length; i++) {
  47558. var name = files[i].correctName.toLowerCase();
  47559. var extension = name.split('.').pop();
  47560. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  47561. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  47562. this._sceneFileToLoad = files[i];
  47563. }
  47564. else {
  47565. FilesInput.FilesToLoad[name] = files[i];
  47566. }
  47567. }
  47568. this.reload();
  47569. };
  47570. FilesInput.prototype.loadFiles = function (event) {
  47571. var _this = this;
  47572. if (this._startingProcessingFilesCallback)
  47573. this._startingProcessingFilesCallback();
  47574. // Handling data transfer via drag'n'drop
  47575. if (event && event.dataTransfer && event.dataTransfer.files) {
  47576. this._filesToLoad = event.dataTransfer.files;
  47577. }
  47578. // Handling files from input files
  47579. if (event && event.target && event.target.files) {
  47580. this._filesToLoad = event.target.files;
  47581. }
  47582. if (this._filesToLoad && this._filesToLoad.length > 0) {
  47583. var files_1 = [];
  47584. var folders = [];
  47585. for (var i = 0; i < this._filesToLoad.length; i++) {
  47586. var fileToLoad = this._filesToLoad[i];
  47587. var name_1 = fileToLoad.name.toLowerCase();
  47588. var type = fileToLoad.type;
  47589. var entry = void 0;
  47590. fileToLoad.correctName = name_1;
  47591. if (event.dataTransfer && event.dataTransfer.items) {
  47592. var item = event.dataTransfer.items[i];
  47593. if (item.getAsEntry) {
  47594. entry = item.getAsEntry();
  47595. }
  47596. else if (item.webkitGetAsEntry) {
  47597. entry = item.webkitGetAsEntry();
  47598. }
  47599. }
  47600. if (!entry) {
  47601. files_1.push(fileToLoad);
  47602. }
  47603. else {
  47604. if (entry.isDirectory) {
  47605. folders.push(entry);
  47606. }
  47607. else {
  47608. files_1.push(fileToLoad);
  47609. }
  47610. }
  47611. }
  47612. if (folders.length === 0) {
  47613. this._processFiles(files_1);
  47614. }
  47615. else {
  47616. var remaining = folders.length;
  47617. // Extract folder content
  47618. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  47619. var folder = folders_1[_i];
  47620. this._handleFolderDrop(folder, files_1, function () {
  47621. remaining--;
  47622. if (remaining === 0) {
  47623. _this._processFiles(files_1);
  47624. }
  47625. });
  47626. }
  47627. }
  47628. }
  47629. };
  47630. FilesInput.prototype.reload = function () {
  47631. var _this = this;
  47632. var that = this;
  47633. // If a ".babylon" file has been provided
  47634. if (this._sceneFileToLoad) {
  47635. if (this._currentScene) {
  47636. if (BABYLON.Tools.errorsCount > 0) {
  47637. BABYLON.Tools.ClearLogCache();
  47638. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  47639. }
  47640. this._engine.stopRenderLoop();
  47641. this._currentScene.dispose();
  47642. }
  47643. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  47644. that._currentScene = newScene;
  47645. // Wait for textures and shaders to be ready
  47646. that._currentScene.executeWhenReady(function () {
  47647. if (that._sceneLoadedCallback) {
  47648. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  47649. }
  47650. that._engine.runRenderLoop(function () { that.renderFunction(); });
  47651. });
  47652. }, function (progress) {
  47653. if (_this._progressCallback) {
  47654. _this._progressCallback(progress);
  47655. }
  47656. });
  47657. }
  47658. else {
  47659. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  47660. }
  47661. };
  47662. return FilesInput;
  47663. }());
  47664. FilesInput.FilesToLoad = new Array();
  47665. BABYLON.FilesInput = FilesInput;
  47666. })(BABYLON || (BABYLON = {}));
  47667. //# sourceMappingURL=babylon.filesInput.js.map
  47668. var BABYLON;
  47669. (function (BABYLON) {
  47670. /**
  47671. * This class implement a typical dictionary using a string as key and the generic type T as value.
  47672. * The underlying implementation relies on an associative array to ensure the best performances.
  47673. * The value can be anything including 'null' but except 'undefined'
  47674. */
  47675. var StringDictionary = (function () {
  47676. function StringDictionary() {
  47677. this._count = 0;
  47678. this._data = {};
  47679. }
  47680. /**
  47681. * This will clear this dictionary and copy the content from the 'source' one.
  47682. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  47683. * @param source the dictionary to take the content from and copy to this dictionary
  47684. */
  47685. StringDictionary.prototype.copyFrom = function (source) {
  47686. var _this = this;
  47687. this.clear();
  47688. source.forEach(function (t, v) { return _this.add(t, v); });
  47689. };
  47690. /**
  47691. * Get a value based from its key
  47692. * @param key the given key to get the matching value from
  47693. * @return the value if found, otherwise undefined is returned
  47694. */
  47695. StringDictionary.prototype.get = function (key) {
  47696. var val = this._data[key];
  47697. if (val !== undefined) {
  47698. return val;
  47699. }
  47700. return undefined;
  47701. };
  47702. /**
  47703. * Get a value from its key or add it if it doesn't exist.
  47704. * This method will ensure you that a given key/data will be present in the dictionary.
  47705. * @param key the given key to get the matching value from
  47706. * @param factory the factory that will create the value if the key is not present in the dictionary.
  47707. * The factory will only be invoked if there's no data for the given key.
  47708. * @return the value corresponding to the key.
  47709. */
  47710. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  47711. var val = this.get(key);
  47712. if (val !== undefined) {
  47713. return val;
  47714. }
  47715. val = factory(key);
  47716. if (val) {
  47717. this.add(key, val);
  47718. }
  47719. return val;
  47720. };
  47721. /**
  47722. * Get a value from its key if present in the dictionary otherwise add it
  47723. * @param key the key to get the value from
  47724. * @param val if there's no such key/value pair in the dictionary add it with this value
  47725. * @return the value corresponding to the key
  47726. */
  47727. StringDictionary.prototype.getOrAdd = function (key, val) {
  47728. var curVal = this.get(key);
  47729. if (curVal !== undefined) {
  47730. return curVal;
  47731. }
  47732. this.add(key, val);
  47733. return val;
  47734. };
  47735. /**
  47736. * Check if there's a given key in the dictionary
  47737. * @param key the key to check for
  47738. * @return true if the key is present, false otherwise
  47739. */
  47740. StringDictionary.prototype.contains = function (key) {
  47741. return this._data[key] !== undefined;
  47742. };
  47743. /**
  47744. * Add a new key and its corresponding value
  47745. * @param key the key to add
  47746. * @param value the value corresponding to the key
  47747. * @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
  47748. */
  47749. StringDictionary.prototype.add = function (key, value) {
  47750. if (this._data[key] !== undefined) {
  47751. return false;
  47752. }
  47753. this._data[key] = value;
  47754. ++this._count;
  47755. return true;
  47756. };
  47757. StringDictionary.prototype.set = function (key, value) {
  47758. if (this._data[key] === undefined) {
  47759. return false;
  47760. }
  47761. this._data[key] = value;
  47762. return true;
  47763. };
  47764. /**
  47765. * Get the element of the given key and remove it from the dictionary
  47766. * @param key
  47767. */
  47768. StringDictionary.prototype.getAndRemove = function (key) {
  47769. var val = this.get(key);
  47770. if (val !== undefined) {
  47771. delete this._data[key];
  47772. --this._count;
  47773. return val;
  47774. }
  47775. return null;
  47776. };
  47777. /**
  47778. * Remove a key/value from the dictionary.
  47779. * @param key the key to remove
  47780. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  47781. */
  47782. StringDictionary.prototype.remove = function (key) {
  47783. if (this.contains(key)) {
  47784. delete this._data[key];
  47785. --this._count;
  47786. return true;
  47787. }
  47788. return false;
  47789. };
  47790. /**
  47791. * Clear the whole content of the dictionary
  47792. */
  47793. StringDictionary.prototype.clear = function () {
  47794. this._data = {};
  47795. this._count = 0;
  47796. };
  47797. Object.defineProperty(StringDictionary.prototype, "count", {
  47798. get: function () {
  47799. return this._count;
  47800. },
  47801. enumerable: true,
  47802. configurable: true
  47803. });
  47804. /**
  47805. * Execute a callback on each key/val of the dictionary.
  47806. * Note that you can remove any element in this dictionary in the callback implementation
  47807. * @param callback the callback to execute on a given key/value pair
  47808. */
  47809. StringDictionary.prototype.forEach = function (callback) {
  47810. for (var cur in this._data) {
  47811. var val = this._data[cur];
  47812. callback(cur, val);
  47813. }
  47814. };
  47815. /**
  47816. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  47817. * If the callback returns null or undefined the method will iterate to the next key/value pair
  47818. * Note that you can remove any element in this dictionary in the callback implementation
  47819. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  47820. */
  47821. StringDictionary.prototype.first = function (callback) {
  47822. for (var cur in this._data) {
  47823. var val = this._data[cur];
  47824. var res = callback(cur, val);
  47825. if (res) {
  47826. return res;
  47827. }
  47828. }
  47829. return null;
  47830. };
  47831. return StringDictionary;
  47832. }());
  47833. BABYLON.StringDictionary = StringDictionary;
  47834. })(BABYLON || (BABYLON = {}));
  47835. //# sourceMappingURL=babylon.stringDictionary.js.map
  47836. var BABYLON;
  47837. (function (BABYLON) {
  47838. var Tags = (function () {
  47839. function Tags() {
  47840. }
  47841. Tags.EnableFor = function (obj) {
  47842. obj._tags = obj._tags || {};
  47843. obj.hasTags = function () {
  47844. return Tags.HasTags(obj);
  47845. };
  47846. obj.addTags = function (tagsString) {
  47847. return Tags.AddTagsTo(obj, tagsString);
  47848. };
  47849. obj.removeTags = function (tagsString) {
  47850. return Tags.RemoveTagsFrom(obj, tagsString);
  47851. };
  47852. obj.matchesTagsQuery = function (tagsQuery) {
  47853. return Tags.MatchesQuery(obj, tagsQuery);
  47854. };
  47855. };
  47856. Tags.DisableFor = function (obj) {
  47857. delete obj._tags;
  47858. delete obj.hasTags;
  47859. delete obj.addTags;
  47860. delete obj.removeTags;
  47861. delete obj.matchesTagsQuery;
  47862. };
  47863. Tags.HasTags = function (obj) {
  47864. if (!obj._tags) {
  47865. return false;
  47866. }
  47867. return !BABYLON.Tools.IsEmpty(obj._tags);
  47868. };
  47869. Tags.GetTags = function (obj, asString) {
  47870. if (asString === void 0) { asString = true; }
  47871. if (!obj._tags) {
  47872. return null;
  47873. }
  47874. if (asString) {
  47875. var tagsArray = [];
  47876. for (var tag in obj._tags) {
  47877. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  47878. tagsArray.push(tag);
  47879. }
  47880. }
  47881. return tagsArray.join(" ");
  47882. }
  47883. else {
  47884. return obj._tags;
  47885. }
  47886. };
  47887. // the tags 'true' and 'false' are reserved and cannot be used as tags
  47888. // a tag cannot start with '||', '&&', and '!'
  47889. // it cannot contain whitespaces
  47890. Tags.AddTagsTo = function (obj, tagsString) {
  47891. if (!tagsString) {
  47892. return;
  47893. }
  47894. if (typeof tagsString !== "string") {
  47895. return;
  47896. }
  47897. var tags = tagsString.split(" ");
  47898. tags.forEach(function (tag, index, array) {
  47899. Tags._AddTagTo(obj, tag);
  47900. });
  47901. };
  47902. Tags._AddTagTo = function (obj, tag) {
  47903. tag = tag.trim();
  47904. if (tag === "" || tag === "true" || tag === "false") {
  47905. return;
  47906. }
  47907. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  47908. return;
  47909. }
  47910. Tags.EnableFor(obj);
  47911. obj._tags[tag] = true;
  47912. };
  47913. Tags.RemoveTagsFrom = function (obj, tagsString) {
  47914. if (!Tags.HasTags(obj)) {
  47915. return;
  47916. }
  47917. var tags = tagsString.split(" ");
  47918. for (var t in tags) {
  47919. Tags._RemoveTagFrom(obj, tags[t]);
  47920. }
  47921. };
  47922. Tags._RemoveTagFrom = function (obj, tag) {
  47923. delete obj._tags[tag];
  47924. };
  47925. Tags.MatchesQuery = function (obj, tagsQuery) {
  47926. if (tagsQuery === undefined) {
  47927. return true;
  47928. }
  47929. if (tagsQuery === "") {
  47930. return Tags.HasTags(obj);
  47931. }
  47932. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  47933. };
  47934. return Tags;
  47935. }());
  47936. BABYLON.Tags = Tags;
  47937. })(BABYLON || (BABYLON = {}));
  47938. //# sourceMappingURL=babylon.tags.js.map
  47939. var BABYLON;
  47940. (function (BABYLON) {
  47941. var Internals;
  47942. (function (Internals) {
  47943. var AndOrNotEvaluator = (function () {
  47944. function AndOrNotEvaluator() {
  47945. }
  47946. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  47947. if (!query.match(/\([^\(\)]*\)/g)) {
  47948. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  47949. }
  47950. else {
  47951. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  47952. // remove parenthesis
  47953. r = r.slice(1, r.length - 1);
  47954. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  47955. });
  47956. }
  47957. if (query === "true") {
  47958. return true;
  47959. }
  47960. if (query === "false") {
  47961. return false;
  47962. }
  47963. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  47964. };
  47965. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  47966. evaluateCallback = evaluateCallback || (function (r) {
  47967. return r === "true" ? true : false;
  47968. });
  47969. var result;
  47970. var or = parenthesisContent.split("||");
  47971. for (var i in or) {
  47972. if (or.hasOwnProperty(i)) {
  47973. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  47974. var and = ori.split("&&");
  47975. if (and.length > 1) {
  47976. for (var j = 0; j < and.length; ++j) {
  47977. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  47978. if (andj !== "true" && andj !== "false") {
  47979. if (andj[0] === "!") {
  47980. result = !evaluateCallback(andj.substring(1));
  47981. }
  47982. else {
  47983. result = evaluateCallback(andj);
  47984. }
  47985. }
  47986. else {
  47987. result = andj === "true" ? true : false;
  47988. }
  47989. if (!result) {
  47990. ori = "false";
  47991. break;
  47992. }
  47993. }
  47994. }
  47995. if (result || ori === "true") {
  47996. result = true;
  47997. break;
  47998. }
  47999. // result equals false (or undefined)
  48000. if (ori !== "true" && ori !== "false") {
  48001. if (ori[0] === "!") {
  48002. result = !evaluateCallback(ori.substring(1));
  48003. }
  48004. else {
  48005. result = evaluateCallback(ori);
  48006. }
  48007. }
  48008. else {
  48009. result = ori === "true" ? true : false;
  48010. }
  48011. }
  48012. }
  48013. // the whole parenthesis scope is replaced by 'true' or 'false'
  48014. return result ? "true" : "false";
  48015. };
  48016. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  48017. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  48018. // remove whitespaces
  48019. r = r.replace(/[\s]/g, function () { return ""; });
  48020. return r.length % 2 ? "!" : "";
  48021. });
  48022. booleanString = booleanString.trim();
  48023. if (booleanString === "!true") {
  48024. booleanString = "false";
  48025. }
  48026. else if (booleanString === "!false") {
  48027. booleanString = "true";
  48028. }
  48029. return booleanString;
  48030. };
  48031. return AndOrNotEvaluator;
  48032. }());
  48033. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  48034. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48035. })(BABYLON || (BABYLON = {}));
  48036. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  48037. var BABYLON;
  48038. (function (BABYLON) {
  48039. var Database = (function () {
  48040. function Database(urlToScene, callbackManifestChecked) {
  48041. // Handling various flavors of prefixed version of IndexedDB
  48042. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  48043. this.callbackManifestChecked = callbackManifestChecked;
  48044. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  48045. this.db = null;
  48046. this.enableSceneOffline = false;
  48047. this.enableTexturesOffline = false;
  48048. this.manifestVersionFound = 0;
  48049. this.mustUpdateRessources = false;
  48050. this.hasReachedQuota = false;
  48051. if (!Database.IDBStorageEnabled) {
  48052. this.callbackManifestChecked(true);
  48053. }
  48054. else {
  48055. this.checkManifestFile();
  48056. }
  48057. }
  48058. Database.prototype.checkManifestFile = function () {
  48059. var _this = this;
  48060. function noManifestFile() {
  48061. that.enableSceneOffline = false;
  48062. that.enableTexturesOffline = false;
  48063. that.callbackManifestChecked(false);
  48064. }
  48065. var that = this;
  48066. var timeStampUsed = false;
  48067. var manifestURL = this.currentSceneUrl + ".manifest";
  48068. var xhr = new XMLHttpRequest();
  48069. if (navigator.onLine) {
  48070. // Adding a timestamp to by-pass browsers' cache
  48071. timeStampUsed = true;
  48072. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  48073. }
  48074. xhr.open("GET", manifestURL, true);
  48075. xhr.addEventListener("load", function () {
  48076. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  48077. try {
  48078. var manifestFile = JSON.parse(xhr.response);
  48079. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  48080. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  48081. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  48082. _this.manifestVersionFound = manifestFile.version;
  48083. }
  48084. if (_this.callbackManifestChecked) {
  48085. _this.callbackManifestChecked(true);
  48086. }
  48087. }
  48088. catch (ex) {
  48089. noManifestFile();
  48090. }
  48091. }
  48092. else {
  48093. noManifestFile();
  48094. }
  48095. }, false);
  48096. xhr.addEventListener("error", function (event) {
  48097. if (timeStampUsed) {
  48098. timeStampUsed = false;
  48099. // Let's retry without the timeStamp
  48100. // It could fail when coupled with HTML5 Offline API
  48101. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  48102. xhr.open("GET", retryManifestURL, true);
  48103. xhr.send();
  48104. }
  48105. else {
  48106. noManifestFile();
  48107. }
  48108. }, false);
  48109. try {
  48110. xhr.send();
  48111. }
  48112. catch (ex) {
  48113. BABYLON.Tools.Error("Error on XHR send request.");
  48114. that.callbackManifestChecked(false);
  48115. }
  48116. };
  48117. Database.prototype.openAsync = function (successCallback, errorCallback) {
  48118. var _this = this;
  48119. function handleError() {
  48120. that.isSupported = false;
  48121. if (errorCallback)
  48122. errorCallback();
  48123. }
  48124. var that = this;
  48125. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  48126. // Your browser doesn't support IndexedDB
  48127. this.isSupported = false;
  48128. if (errorCallback)
  48129. errorCallback();
  48130. }
  48131. else {
  48132. // If the DB hasn't been opened or created yet
  48133. if (!this.db) {
  48134. this.hasReachedQuota = false;
  48135. this.isSupported = true;
  48136. var request = this.idbFactory.open("babylonjs", 1);
  48137. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  48138. request.onerror = function (event) {
  48139. handleError();
  48140. };
  48141. // executes when a version change transaction cannot complete due to other active transactions
  48142. request.onblocked = function (event) {
  48143. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  48144. handleError();
  48145. };
  48146. // DB has been opened successfully
  48147. request.onsuccess = function (event) {
  48148. _this.db = request.result;
  48149. successCallback();
  48150. };
  48151. // Initialization of the DB. Creating Scenes & Textures stores
  48152. request.onupgradeneeded = function (event) {
  48153. _this.db = (event.target).result;
  48154. try {
  48155. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  48156. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  48157. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  48158. }
  48159. catch (ex) {
  48160. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  48161. handleError();
  48162. }
  48163. };
  48164. }
  48165. else {
  48166. if (successCallback)
  48167. successCallback();
  48168. }
  48169. }
  48170. };
  48171. Database.prototype.loadImageFromDB = function (url, image) {
  48172. var _this = this;
  48173. var completeURL = Database.ReturnFullUrlLocation(url);
  48174. var saveAndLoadImage = function () {
  48175. if (!_this.hasReachedQuota && _this.db !== null) {
  48176. // the texture is not yet in the DB, let's try to save it
  48177. _this._saveImageIntoDBAsync(completeURL, image);
  48178. }
  48179. else {
  48180. image.src = url;
  48181. }
  48182. };
  48183. if (!this.mustUpdateRessources) {
  48184. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  48185. }
  48186. else {
  48187. saveAndLoadImage();
  48188. }
  48189. };
  48190. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  48191. if (this.isSupported && this.db !== null) {
  48192. var texture;
  48193. var transaction = this.db.transaction(["textures"]);
  48194. transaction.onabort = function (event) {
  48195. image.src = url;
  48196. };
  48197. transaction.oncomplete = function (event) {
  48198. var blobTextureURL;
  48199. if (texture) {
  48200. var URL = window.URL || window.webkitURL;
  48201. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  48202. image.onerror = function () {
  48203. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  48204. image.src = url;
  48205. };
  48206. image.src = blobTextureURL;
  48207. }
  48208. else {
  48209. notInDBCallback();
  48210. }
  48211. };
  48212. var getRequest = transaction.objectStore("textures").get(url);
  48213. getRequest.onsuccess = function (event) {
  48214. texture = (event.target).result;
  48215. };
  48216. getRequest.onerror = function (event) {
  48217. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  48218. image.src = url;
  48219. };
  48220. }
  48221. else {
  48222. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48223. image.src = url;
  48224. }
  48225. };
  48226. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  48227. var _this = this;
  48228. if (this.isSupported) {
  48229. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  48230. var generateBlobUrl = function () {
  48231. var blobTextureURL;
  48232. if (blob) {
  48233. var URL = window.URL || window.webkitURL;
  48234. try {
  48235. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  48236. }
  48237. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  48238. catch (ex) {
  48239. blobTextureURL = URL.createObjectURL(blob);
  48240. }
  48241. }
  48242. image.src = blobTextureURL;
  48243. };
  48244. if (Database.IsUASupportingBlobStorage) {
  48245. var xhr = new XMLHttpRequest(), blob;
  48246. xhr.open("GET", url, true);
  48247. xhr.responseType = "blob";
  48248. xhr.addEventListener("load", function () {
  48249. if (xhr.status === 200) {
  48250. // Blob as response (XHR2)
  48251. blob = xhr.response;
  48252. var transaction = _this.db.transaction(["textures"], "readwrite");
  48253. // the transaction could abort because of a QuotaExceededError error
  48254. transaction.onabort = function (event) {
  48255. try {
  48256. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  48257. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48258. _this.hasReachedQuota = true;
  48259. }
  48260. }
  48261. catch (ex) { }
  48262. generateBlobUrl();
  48263. };
  48264. transaction.oncomplete = function (event) {
  48265. generateBlobUrl();
  48266. };
  48267. var newTexture = { textureUrl: url, data: blob };
  48268. try {
  48269. // Put the blob into the dabase
  48270. var addRequest = transaction.objectStore("textures").put(newTexture);
  48271. addRequest.onsuccess = function (event) {
  48272. };
  48273. addRequest.onerror = function (event) {
  48274. generateBlobUrl();
  48275. };
  48276. }
  48277. catch (ex) {
  48278. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  48279. if (ex.code === 25) {
  48280. Database.IsUASupportingBlobStorage = false;
  48281. }
  48282. image.src = url;
  48283. }
  48284. }
  48285. else {
  48286. image.src = url;
  48287. }
  48288. }, false);
  48289. xhr.addEventListener("error", function (event) {
  48290. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  48291. image.src = url;
  48292. }, false);
  48293. xhr.send();
  48294. }
  48295. else {
  48296. image.src = url;
  48297. }
  48298. }
  48299. else {
  48300. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48301. image.src = url;
  48302. }
  48303. };
  48304. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  48305. var _this = this;
  48306. var updateVersion = function (event) {
  48307. // the version is not yet in the DB or we need to update it
  48308. _this._saveVersionIntoDBAsync(url, versionLoaded);
  48309. };
  48310. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  48311. };
  48312. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  48313. var _this = this;
  48314. if (this.isSupported) {
  48315. var version;
  48316. try {
  48317. var transaction = this.db.transaction(["versions"]);
  48318. transaction.oncomplete = function (event) {
  48319. if (version) {
  48320. // If the version in the JSON file is > than the version in DB
  48321. if (_this.manifestVersionFound > version.data) {
  48322. _this.mustUpdateRessources = true;
  48323. updateInDBCallback();
  48324. }
  48325. else {
  48326. callback(version.data);
  48327. }
  48328. }
  48329. else {
  48330. _this.mustUpdateRessources = true;
  48331. updateInDBCallback();
  48332. }
  48333. };
  48334. transaction.onabort = function (event) {
  48335. callback(-1);
  48336. };
  48337. var getRequest = transaction.objectStore("versions").get(url);
  48338. getRequest.onsuccess = function (event) {
  48339. version = (event.target).result;
  48340. };
  48341. getRequest.onerror = function (event) {
  48342. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  48343. callback(-1);
  48344. };
  48345. }
  48346. catch (ex) {
  48347. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  48348. callback(-1);
  48349. }
  48350. }
  48351. else {
  48352. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48353. callback(-1);
  48354. }
  48355. };
  48356. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  48357. var _this = this;
  48358. if (this.isSupported && !this.hasReachedQuota) {
  48359. try {
  48360. // Open a transaction to the database
  48361. var transaction = this.db.transaction(["versions"], "readwrite");
  48362. // the transaction could abort because of a QuotaExceededError error
  48363. transaction.onabort = function (event) {
  48364. try {
  48365. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48366. _this.hasReachedQuota = true;
  48367. }
  48368. }
  48369. catch (ex) { }
  48370. callback(-1);
  48371. };
  48372. transaction.oncomplete = function (event) {
  48373. callback(_this.manifestVersionFound);
  48374. };
  48375. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  48376. // Put the scene into the database
  48377. var addRequest = transaction.objectStore("versions").put(newVersion);
  48378. addRequest.onsuccess = function (event) {
  48379. };
  48380. addRequest.onerror = function (event) {
  48381. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  48382. };
  48383. }
  48384. catch (ex) {
  48385. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  48386. callback(-1);
  48387. }
  48388. }
  48389. else {
  48390. callback(-1);
  48391. }
  48392. };
  48393. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  48394. var _this = this;
  48395. var completeUrl = Database.ReturnFullUrlLocation(url);
  48396. var saveAndLoadFile = function (event) {
  48397. // the scene is not yet in the DB, let's try to save it
  48398. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  48399. };
  48400. this._checkVersionFromDB(completeUrl, function (version) {
  48401. if (version !== -1) {
  48402. if (!_this.mustUpdateRessources) {
  48403. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  48404. }
  48405. else {
  48406. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  48407. }
  48408. }
  48409. else {
  48410. errorCallback();
  48411. }
  48412. });
  48413. };
  48414. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  48415. if (this.isSupported) {
  48416. var targetStore;
  48417. if (url.indexOf(".babylon") !== -1) {
  48418. targetStore = "scenes";
  48419. }
  48420. else {
  48421. targetStore = "textures";
  48422. }
  48423. var file;
  48424. var transaction = this.db.transaction([targetStore]);
  48425. transaction.oncomplete = function (event) {
  48426. if (file) {
  48427. callback(file.data);
  48428. }
  48429. else {
  48430. notInDBCallback();
  48431. }
  48432. };
  48433. transaction.onabort = function (event) {
  48434. notInDBCallback();
  48435. };
  48436. var getRequest = transaction.objectStore(targetStore).get(url);
  48437. getRequest.onsuccess = function (event) {
  48438. file = (event.target).result;
  48439. };
  48440. getRequest.onerror = function (event) {
  48441. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  48442. notInDBCallback();
  48443. };
  48444. }
  48445. else {
  48446. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48447. callback();
  48448. }
  48449. };
  48450. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  48451. var _this = this;
  48452. if (this.isSupported) {
  48453. var targetStore;
  48454. if (url.indexOf(".babylon") !== -1) {
  48455. targetStore = "scenes";
  48456. }
  48457. else {
  48458. targetStore = "textures";
  48459. }
  48460. // Create XHR
  48461. var xhr = new XMLHttpRequest(), fileData;
  48462. xhr.open("GET", url, true);
  48463. if (useArrayBuffer) {
  48464. xhr.responseType = "arraybuffer";
  48465. }
  48466. xhr.onprogress = progressCallback;
  48467. xhr.addEventListener("load", function () {
  48468. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  48469. // Blob as response (XHR2)
  48470. //fileData = xhr.responseText;
  48471. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  48472. if (!_this.hasReachedQuota) {
  48473. // Open a transaction to the database
  48474. var transaction = _this.db.transaction([targetStore], "readwrite");
  48475. // the transaction could abort because of a QuotaExceededError error
  48476. transaction.onabort = function (event) {
  48477. try {
  48478. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  48479. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48480. _this.hasReachedQuota = true;
  48481. }
  48482. }
  48483. catch (ex) { }
  48484. callback(fileData);
  48485. };
  48486. transaction.oncomplete = function (event) {
  48487. callback(fileData);
  48488. };
  48489. var newFile;
  48490. if (targetStore === "scenes") {
  48491. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  48492. }
  48493. else {
  48494. newFile = { textureUrl: url, data: fileData };
  48495. }
  48496. try {
  48497. // Put the scene into the database
  48498. var addRequest = transaction.objectStore(targetStore).put(newFile);
  48499. addRequest.onsuccess = function (event) {
  48500. };
  48501. addRequest.onerror = function (event) {
  48502. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  48503. };
  48504. }
  48505. catch (ex) {
  48506. callback(fileData);
  48507. }
  48508. }
  48509. else {
  48510. callback(fileData);
  48511. }
  48512. }
  48513. else {
  48514. callback();
  48515. }
  48516. }, false);
  48517. xhr.addEventListener("error", function (event) {
  48518. BABYLON.Tools.Error("error on XHR request.");
  48519. callback();
  48520. }, false);
  48521. xhr.send();
  48522. }
  48523. else {
  48524. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48525. callback();
  48526. }
  48527. };
  48528. return Database;
  48529. }());
  48530. Database.IsUASupportingBlobStorage = true;
  48531. Database.IDBStorageEnabled = true;
  48532. Database.parseURL = function (url) {
  48533. var a = document.createElement('a');
  48534. a.href = url;
  48535. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  48536. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  48537. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  48538. return absLocation;
  48539. };
  48540. Database.ReturnFullUrlLocation = function (url) {
  48541. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  48542. return (Database.parseURL(window.location.href) + url);
  48543. }
  48544. else {
  48545. return url;
  48546. }
  48547. };
  48548. BABYLON.Database = Database;
  48549. })(BABYLON || (BABYLON = {}));
  48550. //# sourceMappingURL=babylon.database.js.map
  48551. var BABYLON;
  48552. (function (BABYLON) {
  48553. var FresnelParameters = (function () {
  48554. function FresnelParameters() {
  48555. this._isEnabled = true;
  48556. this.leftColor = BABYLON.Color3.White();
  48557. this.rightColor = BABYLON.Color3.Black();
  48558. this.bias = 0;
  48559. this.power = 1;
  48560. }
  48561. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  48562. get: function () {
  48563. return this._isEnabled;
  48564. },
  48565. set: function (value) {
  48566. if (this._isEnabled === value) {
  48567. return;
  48568. }
  48569. this._isEnabled = value;
  48570. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  48571. },
  48572. enumerable: true,
  48573. configurable: true
  48574. });
  48575. FresnelParameters.prototype.clone = function () {
  48576. var newFresnelParameters = new FresnelParameters();
  48577. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  48578. return newFresnelParameters;
  48579. };
  48580. FresnelParameters.prototype.serialize = function () {
  48581. var serializationObject = {};
  48582. serializationObject.isEnabled = this.isEnabled;
  48583. serializationObject.leftColor = this.leftColor;
  48584. serializationObject.rightColor = this.rightColor;
  48585. serializationObject.bias = this.bias;
  48586. serializationObject.power = this.power;
  48587. return serializationObject;
  48588. };
  48589. FresnelParameters.Parse = function (parsedFresnelParameters) {
  48590. var fresnelParameters = new FresnelParameters();
  48591. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  48592. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  48593. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  48594. fresnelParameters.bias = parsedFresnelParameters.bias;
  48595. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  48596. return fresnelParameters;
  48597. };
  48598. return FresnelParameters;
  48599. }());
  48600. BABYLON.FresnelParameters = FresnelParameters;
  48601. })(BABYLON || (BABYLON = {}));
  48602. //# sourceMappingURL=babylon.fresnelParameters.js.map
  48603. var BABYLON;
  48604. (function (BABYLON) {
  48605. var MultiMaterial = (function (_super) {
  48606. __extends(MultiMaterial, _super);
  48607. function MultiMaterial(name, scene) {
  48608. var _this = _super.call(this, name, scene, true) || this;
  48609. scene.multiMaterials.push(_this);
  48610. _this.subMaterials = new Array();
  48611. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  48612. return _this;
  48613. }
  48614. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  48615. get: function () {
  48616. return this._subMaterials;
  48617. },
  48618. set: function (value) {
  48619. this._subMaterials = value;
  48620. this._hookArray(value);
  48621. },
  48622. enumerable: true,
  48623. configurable: true
  48624. });
  48625. MultiMaterial.prototype._hookArray = function (array) {
  48626. var _this = this;
  48627. var oldPush = array.push;
  48628. array.push = function () {
  48629. var items = [];
  48630. for (var _i = 0; _i < arguments.length; _i++) {
  48631. items[_i] = arguments[_i];
  48632. }
  48633. var result = oldPush.apply(array, items);
  48634. _this._markAllSubMeshesAsTexturesDirty();
  48635. return result;
  48636. };
  48637. var oldSplice = array.splice;
  48638. array.splice = function (index, deleteCount) {
  48639. var deleted = oldSplice.apply(array, [index, deleteCount]);
  48640. _this._markAllSubMeshesAsTexturesDirty();
  48641. return deleted;
  48642. };
  48643. };
  48644. // Properties
  48645. MultiMaterial.prototype.getSubMaterial = function (index) {
  48646. if (index < 0 || index >= this.subMaterials.length) {
  48647. return this.getScene().defaultMaterial;
  48648. }
  48649. return this.subMaterials[index];
  48650. };
  48651. MultiMaterial.prototype.getActiveTextures = function () {
  48652. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  48653. var _a;
  48654. };
  48655. // Methods
  48656. MultiMaterial.prototype.getClassName = function () {
  48657. return "MultiMaterial";
  48658. };
  48659. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  48660. for (var index = 0; index < this.subMaterials.length; index++) {
  48661. var subMaterial = this.subMaterials[index];
  48662. if (subMaterial) {
  48663. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  48664. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  48665. return false;
  48666. }
  48667. continue;
  48668. }
  48669. if (!this.subMaterials[index].isReady(mesh)) {
  48670. return false;
  48671. }
  48672. }
  48673. }
  48674. return true;
  48675. };
  48676. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  48677. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  48678. for (var index = 0; index < this.subMaterials.length; index++) {
  48679. var subMaterial = null;
  48680. if (cloneChildren) {
  48681. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  48682. }
  48683. else {
  48684. subMaterial = this.subMaterials[index];
  48685. }
  48686. newMultiMaterial.subMaterials.push(subMaterial);
  48687. }
  48688. return newMultiMaterial;
  48689. };
  48690. MultiMaterial.prototype.serialize = function () {
  48691. var serializationObject = {};
  48692. serializationObject.name = this.name;
  48693. serializationObject.id = this.id;
  48694. serializationObject.tags = BABYLON.Tags.GetTags(this);
  48695. serializationObject.materials = [];
  48696. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  48697. var subMat = this.subMaterials[matIndex];
  48698. if (subMat) {
  48699. serializationObject.materials.push(subMat.id);
  48700. }
  48701. else {
  48702. serializationObject.materials.push(null);
  48703. }
  48704. }
  48705. return serializationObject;
  48706. };
  48707. return MultiMaterial;
  48708. }(BABYLON.Material));
  48709. BABYLON.MultiMaterial = MultiMaterial;
  48710. })(BABYLON || (BABYLON = {}));
  48711. //# sourceMappingURL=babylon.multiMaterial.js.map
  48712. var BABYLON;
  48713. (function (BABYLON) {
  48714. var FreeCameraTouchInput = (function () {
  48715. function FreeCameraTouchInput() {
  48716. this._offsetX = null;
  48717. this._offsetY = null;
  48718. this._pointerCount = 0;
  48719. this._pointerPressed = [];
  48720. this.touchAngularSensibility = 200000.0;
  48721. this.touchMoveSensibility = 250.0;
  48722. }
  48723. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  48724. var _this = this;
  48725. var previousPosition;
  48726. if (this._pointerInput === undefined) {
  48727. this._onLostFocus = function (evt) {
  48728. _this._offsetX = null;
  48729. _this._offsetY = null;
  48730. };
  48731. this._pointerInput = function (p, s) {
  48732. var evt = p.event;
  48733. if (evt.pointerType === "mouse") {
  48734. return;
  48735. }
  48736. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  48737. if (!noPreventDefault) {
  48738. evt.preventDefault();
  48739. }
  48740. _this._pointerPressed.push(evt.pointerId);
  48741. if (_this._pointerPressed.length !== 1) {
  48742. return;
  48743. }
  48744. previousPosition = {
  48745. x: evt.clientX,
  48746. y: evt.clientY
  48747. };
  48748. }
  48749. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  48750. if (!noPreventDefault) {
  48751. evt.preventDefault();
  48752. }
  48753. var index = _this._pointerPressed.indexOf(evt.pointerId);
  48754. if (index === -1) {
  48755. return;
  48756. }
  48757. _this._pointerPressed.splice(index, 1);
  48758. if (index != 0) {
  48759. return;
  48760. }
  48761. previousPosition = null;
  48762. _this._offsetX = null;
  48763. _this._offsetY = null;
  48764. }
  48765. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48766. if (!noPreventDefault) {
  48767. evt.preventDefault();
  48768. }
  48769. if (!previousPosition) {
  48770. return;
  48771. }
  48772. var index = _this._pointerPressed.indexOf(evt.pointerId);
  48773. if (index != 0) {
  48774. return;
  48775. }
  48776. _this._offsetX = evt.clientX - previousPosition.x;
  48777. _this._offsetY = -(evt.clientY - previousPosition.y);
  48778. }
  48779. };
  48780. }
  48781. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48782. element.addEventListener("blur", this._onLostFocus);
  48783. };
  48784. FreeCameraTouchInput.prototype.detachControl = function (element) {
  48785. if (this._pointerInput && element) {
  48786. this.camera.getScene().onPointerObservable.remove(this._observer);
  48787. this._observer = null;
  48788. element.removeEventListener("blur", this._onLostFocus);
  48789. this._onLostFocus = null;
  48790. this._pointerPressed = [];
  48791. this._offsetX = null;
  48792. this._offsetY = null;
  48793. this._pointerCount = 0;
  48794. }
  48795. };
  48796. FreeCameraTouchInput.prototype.checkInputs = function () {
  48797. if (this._offsetX) {
  48798. var camera = this.camera;
  48799. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  48800. if (this._pointerPressed.length > 1) {
  48801. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  48802. }
  48803. else {
  48804. var speed = camera._computeLocalCameraSpeed();
  48805. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  48806. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  48807. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  48808. }
  48809. }
  48810. };
  48811. FreeCameraTouchInput.prototype.getClassName = function () {
  48812. return "FreeCameraTouchInput";
  48813. };
  48814. FreeCameraTouchInput.prototype.getSimpleName = function () {
  48815. return "touch";
  48816. };
  48817. return FreeCameraTouchInput;
  48818. }());
  48819. __decorate([
  48820. BABYLON.serialize()
  48821. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  48822. __decorate([
  48823. BABYLON.serialize()
  48824. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  48825. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  48826. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  48827. })(BABYLON || (BABYLON = {}));
  48828. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  48829. /// <reference path="babylon.freeCamera.ts" />
  48830. var BABYLON;
  48831. (function (BABYLON) {
  48832. // We're mainly based on the logic defined into the FreeCamera code
  48833. var TouchCamera = (function (_super) {
  48834. __extends(TouchCamera, _super);
  48835. //-- end properties for backward compatibility for inputs
  48836. function TouchCamera(name, position, scene) {
  48837. var _this = _super.call(this, name, position, scene) || this;
  48838. _this.inputs.addTouch();
  48839. _this._setupInputs();
  48840. return _this;
  48841. }
  48842. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  48843. //-- Begin properties for backward compatibility for inputs
  48844. get: function () {
  48845. var touch = this.inputs.attached["touch"];
  48846. if (touch)
  48847. return touch.touchAngularSensibility;
  48848. },
  48849. set: function (value) {
  48850. var touch = this.inputs.attached["touch"];
  48851. if (touch)
  48852. touch.touchAngularSensibility = value;
  48853. },
  48854. enumerable: true,
  48855. configurable: true
  48856. });
  48857. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  48858. get: function () {
  48859. var touch = this.inputs.attached["touch"];
  48860. if (touch)
  48861. return touch.touchMoveSensibility;
  48862. },
  48863. set: function (value) {
  48864. var touch = this.inputs.attached["touch"];
  48865. if (touch)
  48866. touch.touchMoveSensibility = value;
  48867. },
  48868. enumerable: true,
  48869. configurable: true
  48870. });
  48871. TouchCamera.prototype.getClassName = function () {
  48872. return "TouchCamera";
  48873. };
  48874. TouchCamera.prototype._setupInputs = function () {
  48875. var mouse = this.inputs.attached["mouse"];
  48876. if (mouse) {
  48877. mouse.touchEnabled = false;
  48878. }
  48879. };
  48880. return TouchCamera;
  48881. }(BABYLON.FreeCamera));
  48882. BABYLON.TouchCamera = TouchCamera;
  48883. })(BABYLON || (BABYLON = {}));
  48884. //# sourceMappingURL=babylon.touchCamera.js.map
  48885. var BABYLON;
  48886. (function (BABYLON) {
  48887. var ProceduralTexture = (function (_super) {
  48888. __extends(ProceduralTexture, _super);
  48889. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  48890. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48891. if (isCube === void 0) { isCube = false; }
  48892. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  48893. _this.isCube = isCube;
  48894. _this.isEnabled = true;
  48895. _this._currentRefreshId = -1;
  48896. _this._refreshRate = 1;
  48897. _this._vertexBuffers = {};
  48898. _this._uniforms = new Array();
  48899. _this._samplers = new Array();
  48900. _this._textures = new Array();
  48901. _this._floats = new Array();
  48902. _this._floatsArrays = {};
  48903. _this._colors3 = new Array();
  48904. _this._colors4 = new Array();
  48905. _this._vectors2 = new Array();
  48906. _this._vectors3 = new Array();
  48907. _this._matrices = new Array();
  48908. _this._fallbackTextureUsed = false;
  48909. scene._proceduralTextures.push(_this);
  48910. _this.name = name;
  48911. _this.isRenderTarget = true;
  48912. _this._size = size;
  48913. _this._generateMipMaps = generateMipMaps;
  48914. _this.setFragment(fragment);
  48915. _this._fallbackTexture = fallbackTexture;
  48916. var engine = scene.getEngine();
  48917. if (isCube) {
  48918. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  48919. _this.setFloat("face", 0);
  48920. }
  48921. else {
  48922. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  48923. }
  48924. // VBO
  48925. var vertices = [];
  48926. vertices.push(1, 1);
  48927. vertices.push(-1, 1);
  48928. vertices.push(-1, -1);
  48929. vertices.push(1, -1);
  48930. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  48931. // Indices
  48932. var indices = [];
  48933. indices.push(0);
  48934. indices.push(1);
  48935. indices.push(2);
  48936. indices.push(0);
  48937. indices.push(2);
  48938. indices.push(3);
  48939. _this._indexBuffer = engine.createIndexBuffer(indices);
  48940. return _this;
  48941. }
  48942. ProceduralTexture.prototype.reset = function () {
  48943. if (this._effect === undefined) {
  48944. return;
  48945. }
  48946. var engine = this.getScene().getEngine();
  48947. engine._releaseEffect(this._effect);
  48948. };
  48949. ProceduralTexture.prototype.isReady = function () {
  48950. var _this = this;
  48951. var engine = this.getScene().getEngine();
  48952. var shaders;
  48953. if (!this._fragment) {
  48954. return false;
  48955. }
  48956. if (this._fallbackTextureUsed) {
  48957. return true;
  48958. }
  48959. if (this._fragment.fragmentElement !== undefined) {
  48960. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  48961. }
  48962. else {
  48963. shaders = { vertex: "procedural", fragment: this._fragment };
  48964. }
  48965. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  48966. _this.releaseInternalTexture();
  48967. if (_this._fallbackTexture) {
  48968. _this._texture = _this._fallbackTexture._texture;
  48969. _this._texture.references++;
  48970. }
  48971. _this._fallbackTextureUsed = true;
  48972. });
  48973. return this._effect.isReady();
  48974. };
  48975. ProceduralTexture.prototype.resetRefreshCounter = function () {
  48976. this._currentRefreshId = -1;
  48977. };
  48978. ProceduralTexture.prototype.setFragment = function (fragment) {
  48979. this._fragment = fragment;
  48980. };
  48981. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  48982. get: function () {
  48983. return this._refreshRate;
  48984. },
  48985. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  48986. set: function (value) {
  48987. this._refreshRate = value;
  48988. this.resetRefreshCounter();
  48989. },
  48990. enumerable: true,
  48991. configurable: true
  48992. });
  48993. ProceduralTexture.prototype._shouldRender = function () {
  48994. if (!this.isEnabled || !this.isReady() || !this._texture) {
  48995. return false;
  48996. }
  48997. if (this._fallbackTextureUsed) {
  48998. return false;
  48999. }
  49000. if (this._currentRefreshId === -1) {
  49001. this._currentRefreshId = 1;
  49002. return true;
  49003. }
  49004. if (this.refreshRate === this._currentRefreshId) {
  49005. this._currentRefreshId = 1;
  49006. return true;
  49007. }
  49008. this._currentRefreshId++;
  49009. return false;
  49010. };
  49011. ProceduralTexture.prototype.getRenderSize = function () {
  49012. return this._size;
  49013. };
  49014. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  49015. if (this._fallbackTextureUsed) {
  49016. return;
  49017. }
  49018. this.releaseInternalTexture();
  49019. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  49020. };
  49021. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  49022. if (this._uniforms.indexOf(uniformName) === -1) {
  49023. this._uniforms.push(uniformName);
  49024. }
  49025. };
  49026. ProceduralTexture.prototype.setTexture = function (name, texture) {
  49027. if (this._samplers.indexOf(name) === -1) {
  49028. this._samplers.push(name);
  49029. }
  49030. this._textures[name] = texture;
  49031. return this;
  49032. };
  49033. ProceduralTexture.prototype.setFloat = function (name, value) {
  49034. this._checkUniform(name);
  49035. this._floats[name] = value;
  49036. return this;
  49037. };
  49038. ProceduralTexture.prototype.setFloats = function (name, value) {
  49039. this._checkUniform(name);
  49040. this._floatsArrays[name] = value;
  49041. return this;
  49042. };
  49043. ProceduralTexture.prototype.setColor3 = function (name, value) {
  49044. this._checkUniform(name);
  49045. this._colors3[name] = value;
  49046. return this;
  49047. };
  49048. ProceduralTexture.prototype.setColor4 = function (name, value) {
  49049. this._checkUniform(name);
  49050. this._colors4[name] = value;
  49051. return this;
  49052. };
  49053. ProceduralTexture.prototype.setVector2 = function (name, value) {
  49054. this._checkUniform(name);
  49055. this._vectors2[name] = value;
  49056. return this;
  49057. };
  49058. ProceduralTexture.prototype.setVector3 = function (name, value) {
  49059. this._checkUniform(name);
  49060. this._vectors3[name] = value;
  49061. return this;
  49062. };
  49063. ProceduralTexture.prototype.setMatrix = function (name, value) {
  49064. this._checkUniform(name);
  49065. this._matrices[name] = value;
  49066. return this;
  49067. };
  49068. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  49069. var scene = this.getScene();
  49070. var engine = scene.getEngine();
  49071. // Render
  49072. engine.enableEffect(this._effect);
  49073. engine.setState(false);
  49074. // Texture
  49075. for (var name in this._textures) {
  49076. this._effect.setTexture(name, this._textures[name]);
  49077. }
  49078. // Float
  49079. for (name in this._floats) {
  49080. this._effect.setFloat(name, this._floats[name]);
  49081. }
  49082. // Floats
  49083. for (name in this._floatsArrays) {
  49084. this._effect.setArray(name, this._floatsArrays[name]);
  49085. }
  49086. // Color3
  49087. for (name in this._colors3) {
  49088. this._effect.setColor3(name, this._colors3[name]);
  49089. }
  49090. // Color4
  49091. for (name in this._colors4) {
  49092. var color = this._colors4[name];
  49093. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49094. }
  49095. // Vector2
  49096. for (name in this._vectors2) {
  49097. this._effect.setVector2(name, this._vectors2[name]);
  49098. }
  49099. // Vector3
  49100. for (name in this._vectors3) {
  49101. this._effect.setVector3(name, this._vectors3[name]);
  49102. }
  49103. // Matrix
  49104. for (name in this._matrices) {
  49105. this._effect.setMatrix(name, this._matrices[name]);
  49106. }
  49107. if (this.isCube) {
  49108. for (var face = 0; face < 6; face++) {
  49109. engine.bindFramebuffer(this._texture, face);
  49110. // VBOs
  49111. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49112. this._effect.setFloat("face", face);
  49113. // Clear
  49114. engine.clear(scene.clearColor, true, true, true);
  49115. // Draw order
  49116. engine.draw(true, 0, 6);
  49117. // Mipmaps
  49118. if (face === 5) {
  49119. engine.generateMipMapsForCubemap(this._texture);
  49120. }
  49121. }
  49122. }
  49123. else {
  49124. engine.bindFramebuffer(this._texture);
  49125. // VBOs
  49126. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49127. // Clear
  49128. engine.clear(scene.clearColor, true, true, true);
  49129. // Draw order
  49130. engine.draw(true, 0, 6);
  49131. }
  49132. // Unbind
  49133. engine.unBindFramebuffer(this._texture, this.isCube);
  49134. if (this.onGenerated) {
  49135. this.onGenerated();
  49136. }
  49137. };
  49138. ProceduralTexture.prototype.clone = function () {
  49139. var textureSize = this.getSize();
  49140. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  49141. // Base texture
  49142. newTexture.hasAlpha = this.hasAlpha;
  49143. newTexture.level = this.level;
  49144. // RenderTarget Texture
  49145. newTexture.coordinatesMode = this.coordinatesMode;
  49146. return newTexture;
  49147. };
  49148. ProceduralTexture.prototype.dispose = function () {
  49149. var index = this.getScene()._proceduralTextures.indexOf(this);
  49150. if (index >= 0) {
  49151. this.getScene()._proceduralTextures.splice(index, 1);
  49152. }
  49153. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  49154. if (vertexBuffer) {
  49155. vertexBuffer.dispose();
  49156. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  49157. }
  49158. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  49159. this._indexBuffer = null;
  49160. }
  49161. _super.prototype.dispose.call(this);
  49162. };
  49163. return ProceduralTexture;
  49164. }(BABYLON.Texture));
  49165. BABYLON.ProceduralTexture = ProceduralTexture;
  49166. })(BABYLON || (BABYLON = {}));
  49167. //# sourceMappingURL=babylon.proceduralTexture.js.map
  49168. /// <reference path="babylon.proceduralTexture.ts" />
  49169. var BABYLON;
  49170. (function (BABYLON) {
  49171. var CustomProceduralTexture = (function (_super) {
  49172. __extends(CustomProceduralTexture, _super);
  49173. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  49174. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  49175. _this._animate = true;
  49176. _this._time = 0;
  49177. _this._texturePath = texturePath;
  49178. //Try to load json
  49179. _this.loadJson(texturePath);
  49180. _this.refreshRate = 1;
  49181. return _this;
  49182. }
  49183. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  49184. var _this = this;
  49185. var that = this;
  49186. function noConfigFile() {
  49187. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  49188. try {
  49189. that.setFragment(that._texturePath);
  49190. }
  49191. catch (ex) {
  49192. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  49193. }
  49194. }
  49195. var configFileUrl = jsonUrl + "/config.json";
  49196. var xhr = new XMLHttpRequest();
  49197. xhr.open("GET", configFileUrl, true);
  49198. xhr.addEventListener("load", function () {
  49199. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49200. try {
  49201. _this._config = JSON.parse(xhr.response);
  49202. _this.updateShaderUniforms();
  49203. _this.updateTextures();
  49204. _this.setFragment(_this._texturePath + "/custom");
  49205. _this._animate = _this._config.animate;
  49206. _this.refreshRate = _this._config.refreshrate;
  49207. }
  49208. catch (ex) {
  49209. noConfigFile();
  49210. }
  49211. }
  49212. else {
  49213. noConfigFile();
  49214. }
  49215. }, false);
  49216. xhr.addEventListener("error", function () {
  49217. noConfigFile();
  49218. }, false);
  49219. try {
  49220. xhr.send();
  49221. }
  49222. catch (ex) {
  49223. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  49224. }
  49225. };
  49226. CustomProceduralTexture.prototype.isReady = function () {
  49227. if (!_super.prototype.isReady.call(this)) {
  49228. return false;
  49229. }
  49230. for (var name in this._textures) {
  49231. var texture = this._textures[name];
  49232. if (!texture.isReady()) {
  49233. return false;
  49234. }
  49235. }
  49236. return true;
  49237. };
  49238. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  49239. if (this._animate) {
  49240. this._time += this.getScene().getAnimationRatio() * 0.03;
  49241. this.updateShaderUniforms();
  49242. }
  49243. _super.prototype.render.call(this, useCameraPostProcess);
  49244. };
  49245. CustomProceduralTexture.prototype.updateTextures = function () {
  49246. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  49247. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  49248. }
  49249. };
  49250. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  49251. if (this._config) {
  49252. for (var j = 0; j < this._config.uniforms.length; j++) {
  49253. var uniform = this._config.uniforms[j];
  49254. switch (uniform.type) {
  49255. case "float":
  49256. this.setFloat(uniform.name, uniform.value);
  49257. break;
  49258. case "color3":
  49259. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  49260. break;
  49261. case "color4":
  49262. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  49263. break;
  49264. case "vector2":
  49265. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  49266. break;
  49267. case "vector3":
  49268. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  49269. break;
  49270. }
  49271. }
  49272. }
  49273. this.setFloat("time", this._time);
  49274. };
  49275. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  49276. get: function () {
  49277. return this._animate;
  49278. },
  49279. set: function (value) {
  49280. this._animate = value;
  49281. },
  49282. enumerable: true,
  49283. configurable: true
  49284. });
  49285. return CustomProceduralTexture;
  49286. }(BABYLON.ProceduralTexture));
  49287. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  49288. })(BABYLON || (BABYLON = {}));
  49289. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  49290. var BABYLON;
  49291. (function (BABYLON) {
  49292. var FreeCameraGamepadInput = (function () {
  49293. function FreeCameraGamepadInput() {
  49294. this.gamepadAngularSensibility = 200;
  49295. this.gamepadMoveSensibility = 40;
  49296. // private members
  49297. this._cameraTransform = BABYLON.Matrix.Identity();
  49298. this._deltaTransform = BABYLON.Vector3.Zero();
  49299. this._vector3 = BABYLON.Vector3.Zero();
  49300. this._vector2 = BABYLON.Vector2.Zero();
  49301. }
  49302. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  49303. var _this = this;
  49304. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  49305. };
  49306. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  49307. if (this._gamepads) {
  49308. this._gamepads.dispose();
  49309. }
  49310. this.gamepad = null;
  49311. };
  49312. FreeCameraGamepadInput.prototype.checkInputs = function () {
  49313. if (this.gamepad && this.gamepad.leftStick) {
  49314. var camera = this.camera;
  49315. var LSValues = this.gamepad.leftStick;
  49316. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  49317. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  49318. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  49319. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  49320. var RSValues = this.gamepad.rightStick;
  49321. if (RSValues) {
  49322. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  49323. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  49324. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  49325. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  49326. }
  49327. else {
  49328. RSValues = { x: 0, y: 0 };
  49329. }
  49330. if (!camera.rotationQuaternion) {
  49331. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  49332. }
  49333. else {
  49334. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  49335. }
  49336. var speed = camera._computeLocalCameraSpeed() * 50.0;
  49337. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  49338. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  49339. camera.cameraDirection.addInPlace(this._deltaTransform);
  49340. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  49341. camera.cameraRotation.addInPlace(this._vector2);
  49342. }
  49343. };
  49344. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  49345. // Only the first gamepad found can control the camera
  49346. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  49347. // prioritize XBOX gamepads.
  49348. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  49349. this.gamepad = gamepad;
  49350. }
  49351. }
  49352. };
  49353. FreeCameraGamepadInput.prototype.getClassName = function () {
  49354. return "FreeCameraGamepadInput";
  49355. };
  49356. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  49357. return "gamepad";
  49358. };
  49359. return FreeCameraGamepadInput;
  49360. }());
  49361. __decorate([
  49362. BABYLON.serialize()
  49363. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  49364. __decorate([
  49365. BABYLON.serialize()
  49366. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  49367. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  49368. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  49369. })(BABYLON || (BABYLON = {}));
  49370. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  49371. var BABYLON;
  49372. (function (BABYLON) {
  49373. var ArcRotateCameraGamepadInput = (function () {
  49374. function ArcRotateCameraGamepadInput() {
  49375. this.gamepadRotationSensibility = 80;
  49376. this.gamepadMoveSensibility = 40;
  49377. }
  49378. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  49379. var _this = this;
  49380. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  49381. };
  49382. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  49383. if (this._gamepads) {
  49384. this._gamepads.dispose();
  49385. }
  49386. this.gamepad = null;
  49387. };
  49388. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  49389. if (this.gamepad) {
  49390. var camera = this.camera;
  49391. var RSValues = this.gamepad.rightStick;
  49392. if (RSValues) {
  49393. if (RSValues.x != 0) {
  49394. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  49395. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  49396. camera.inertialAlphaOffset += normalizedRX;
  49397. }
  49398. }
  49399. if (RSValues.y != 0) {
  49400. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  49401. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  49402. camera.inertialBetaOffset += normalizedRY;
  49403. }
  49404. }
  49405. }
  49406. var LSValues = this.gamepad.leftStick;
  49407. if (LSValues && LSValues.y != 0) {
  49408. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  49409. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  49410. this.camera.inertialRadiusOffset -= normalizedLY;
  49411. }
  49412. }
  49413. }
  49414. };
  49415. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  49416. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  49417. // prioritize XBOX gamepads.
  49418. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  49419. this.gamepad = gamepad;
  49420. }
  49421. }
  49422. };
  49423. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  49424. return "ArcRotateCameraGamepadInput";
  49425. };
  49426. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  49427. return "gamepad";
  49428. };
  49429. return ArcRotateCameraGamepadInput;
  49430. }());
  49431. __decorate([
  49432. BABYLON.serialize()
  49433. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  49434. __decorate([
  49435. BABYLON.serialize()
  49436. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  49437. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  49438. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  49439. })(BABYLON || (BABYLON = {}));
  49440. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  49441. var BABYLON;
  49442. (function (BABYLON) {
  49443. var Gamepads = (function () {
  49444. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  49445. var _this = this;
  49446. this.babylonGamepads = [];
  49447. this.oneGamepadConnected = false;
  49448. this.isMonitoring = false;
  49449. this.gamepadEventSupported = 'GamepadEvent' in window;
  49450. this.gamepadSupport = (navigator.getGamepads ||
  49451. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  49452. this._callbackGamepadConnected = ongamedpadconnected;
  49453. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  49454. if (this.gamepadSupport) {
  49455. //first add already-connected gamepads
  49456. this._updateGamepadObjects();
  49457. if (this.babylonGamepads.length) {
  49458. this._startMonitoringGamepads();
  49459. }
  49460. // Checking if the gamepad connected event is supported (like in Firefox)
  49461. if (this.gamepadEventSupported) {
  49462. this._onGamepadConnectedEvent = function (evt) {
  49463. _this._onGamepadConnected(evt.gamepad);
  49464. };
  49465. this._onGamepadDisonnectedEvent = function (evt) {
  49466. _this._onGamepadDisconnected(evt.gamepad);
  49467. };
  49468. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49469. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49470. }
  49471. else {
  49472. this._startMonitoringGamepads();
  49473. }
  49474. }
  49475. }
  49476. Gamepads.prototype.dispose = function () {
  49477. if (this._onGamepadConnectedEvent) {
  49478. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49479. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49480. this._onGamepadConnectedEvent = null;
  49481. this._onGamepadDisonnectedEvent = null;
  49482. }
  49483. this.oneGamepadConnected = false;
  49484. this._stopMonitoringGamepads();
  49485. this.babylonGamepads = [];
  49486. };
  49487. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  49488. // Protection code for Chrome which has a very buggy gamepad implementation...
  49489. // And raises a connected event on disconnection for instance
  49490. if (gamepad.index in this.babylonGamepads) {
  49491. return;
  49492. }
  49493. var newGamepad = this._addNewGamepad(gamepad);
  49494. if (this._callbackGamepadConnected)
  49495. this._callbackGamepadConnected(newGamepad);
  49496. this._startMonitoringGamepads();
  49497. };
  49498. Gamepads.prototype._addNewGamepad = function (gamepad) {
  49499. if (!this.oneGamepadConnected) {
  49500. this.oneGamepadConnected = true;
  49501. }
  49502. var newGamepad;
  49503. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  49504. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  49505. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  49506. }
  49507. else if (gamepad.pose) {
  49508. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  49509. }
  49510. else {
  49511. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  49512. }
  49513. this.babylonGamepads.push(newGamepad);
  49514. return newGamepad;
  49515. };
  49516. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  49517. // Remove the gamepad from the list of gamepads to monitor.
  49518. for (var i in this.babylonGamepads) {
  49519. if (this.babylonGamepads[i].index == gamepad.index) {
  49520. this.babylonGamepads.splice(+i, 1);
  49521. break;
  49522. }
  49523. }
  49524. // If no gamepads are left, stop the polling loop.
  49525. if (this.babylonGamepads.length == 0) {
  49526. this._stopMonitoringGamepads();
  49527. this.oneGamepadConnected = false;
  49528. }
  49529. if (this._callbackGamepadDisconnected)
  49530. this._callbackGamepadDisconnected(gamepad);
  49531. };
  49532. Gamepads.prototype._startMonitoringGamepads = function () {
  49533. if (!this.isMonitoring) {
  49534. this.isMonitoring = true;
  49535. this._checkGamepadsStatus();
  49536. }
  49537. };
  49538. Gamepads.prototype._stopMonitoringGamepads = function () {
  49539. this.isMonitoring = false;
  49540. };
  49541. Gamepads.prototype._checkGamepadsStatus = function () {
  49542. var _this = this;
  49543. // Hack to be compatible Chrome
  49544. this._updateGamepadObjects();
  49545. for (var i in this.babylonGamepads) {
  49546. this.babylonGamepads[i].update();
  49547. }
  49548. if (this.isMonitoring) {
  49549. if (window.requestAnimationFrame) {
  49550. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49551. }
  49552. else if (window.mozRequestAnimationFrame) {
  49553. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49554. }
  49555. else if (window.webkitRequestAnimationFrame) {
  49556. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49557. }
  49558. }
  49559. };
  49560. // This function is called only on Chrome, which does not properly support
  49561. // connection/disconnection events and forces you to recopy again the gamepad object
  49562. Gamepads.prototype._updateGamepadObjects = function () {
  49563. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  49564. for (var i = 0; i < gamepads.length; i++) {
  49565. if (gamepads[i]) {
  49566. if (!(gamepads[i].index in this.babylonGamepads)) {
  49567. var newGamepad = this._addNewGamepad(gamepads[i]);
  49568. if (this._callbackGamepadConnected) {
  49569. this._callbackGamepadConnected(newGamepad);
  49570. }
  49571. }
  49572. else {
  49573. // Forced to copy again this object for Chrome for unknown reason
  49574. this.babylonGamepads[i].browserGamepad = gamepads[i];
  49575. }
  49576. }
  49577. }
  49578. };
  49579. return Gamepads;
  49580. }());
  49581. BABYLON.Gamepads = Gamepads;
  49582. var StickValues = (function () {
  49583. function StickValues(x, y) {
  49584. this.x = x;
  49585. this.y = y;
  49586. }
  49587. return StickValues;
  49588. }());
  49589. BABYLON.StickValues = StickValues;
  49590. var Gamepad = (function () {
  49591. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  49592. if (leftStickX === void 0) { leftStickX = 0; }
  49593. if (leftStickY === void 0) { leftStickY = 1; }
  49594. if (rightStickX === void 0) { rightStickX = 2; }
  49595. if (rightStickY === void 0) { rightStickY = 3; }
  49596. this.id = id;
  49597. this.index = index;
  49598. this.browserGamepad = browserGamepad;
  49599. this.type = Gamepad.GAMEPAD;
  49600. this._leftStickAxisX = leftStickX;
  49601. this._leftStickAxisY = leftStickY;
  49602. this._rightStickAxisX = rightStickX;
  49603. this._rightStickAxisY = rightStickY;
  49604. if (this.browserGamepad.axes.length >= 2) {
  49605. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49606. }
  49607. if (this.browserGamepad.axes.length >= 4) {
  49608. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49609. }
  49610. }
  49611. Gamepad.prototype.onleftstickchanged = function (callback) {
  49612. this._onleftstickchanged = callback;
  49613. };
  49614. Gamepad.prototype.onrightstickchanged = function (callback) {
  49615. this._onrightstickchanged = callback;
  49616. };
  49617. Object.defineProperty(Gamepad.prototype, "leftStick", {
  49618. get: function () {
  49619. return this._leftStick;
  49620. },
  49621. set: function (newValues) {
  49622. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  49623. this._onleftstickchanged(newValues);
  49624. }
  49625. this._leftStick = newValues;
  49626. },
  49627. enumerable: true,
  49628. configurable: true
  49629. });
  49630. Object.defineProperty(Gamepad.prototype, "rightStick", {
  49631. get: function () {
  49632. return this._rightStick;
  49633. },
  49634. set: function (newValues) {
  49635. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  49636. this._onrightstickchanged(newValues);
  49637. }
  49638. this._rightStick = newValues;
  49639. },
  49640. enumerable: true,
  49641. configurable: true
  49642. });
  49643. Gamepad.prototype.update = function () {
  49644. if (this._leftStick) {
  49645. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49646. }
  49647. if (this._rightStick) {
  49648. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49649. }
  49650. };
  49651. return Gamepad;
  49652. }());
  49653. Gamepad.GAMEPAD = 0;
  49654. Gamepad.GENERIC = 1;
  49655. Gamepad.XBOX = 2;
  49656. Gamepad.POSE_ENABLED = 3;
  49657. BABYLON.Gamepad = Gamepad;
  49658. var GenericPad = (function (_super) {
  49659. __extends(GenericPad, _super);
  49660. function GenericPad(id, index, browserGamepad) {
  49661. var _this = _super.call(this, id, index, browserGamepad) || this;
  49662. _this.type = Gamepad.GENERIC;
  49663. _this._buttons = new Array(browserGamepad.buttons.length);
  49664. return _this;
  49665. }
  49666. GenericPad.prototype.onbuttondown = function (callback) {
  49667. this._onbuttondown = callback;
  49668. };
  49669. GenericPad.prototype.onbuttonup = function (callback) {
  49670. this._onbuttonup = callback;
  49671. };
  49672. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  49673. if (newValue !== currentValue) {
  49674. if (this._onbuttondown && newValue === 1) {
  49675. this._onbuttondown(buttonIndex);
  49676. }
  49677. if (this._onbuttonup && newValue === 0) {
  49678. this._onbuttonup(buttonIndex);
  49679. }
  49680. }
  49681. return newValue;
  49682. };
  49683. GenericPad.prototype.update = function () {
  49684. _super.prototype.update.call(this);
  49685. for (var index = 0; index < this._buttons.length; index++) {
  49686. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  49687. }
  49688. };
  49689. return GenericPad;
  49690. }(Gamepad));
  49691. BABYLON.GenericPad = GenericPad;
  49692. var Xbox360Button;
  49693. (function (Xbox360Button) {
  49694. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  49695. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  49696. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  49697. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  49698. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  49699. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  49700. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  49701. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  49702. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  49703. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  49704. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  49705. var Xbox360Dpad;
  49706. (function (Xbox360Dpad) {
  49707. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  49708. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  49709. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  49710. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  49711. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  49712. var Xbox360Pad = (function (_super) {
  49713. __extends(Xbox360Pad, _super);
  49714. function Xbox360Pad(id, index, gamepad, xboxOne) {
  49715. if (xboxOne === void 0) { xboxOne = false; }
  49716. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  49717. _this._leftTrigger = 0;
  49718. _this._rightTrigger = 0;
  49719. _this._buttonA = 0;
  49720. _this._buttonB = 0;
  49721. _this._buttonX = 0;
  49722. _this._buttonY = 0;
  49723. _this._buttonBack = 0;
  49724. _this._buttonStart = 0;
  49725. _this._buttonLB = 0;
  49726. _this._buttonRB = 0;
  49727. _this._buttonLeftStick = 0;
  49728. _this._buttonRightStick = 0;
  49729. _this._dPadUp = 0;
  49730. _this._dPadDown = 0;
  49731. _this._dPadLeft = 0;
  49732. _this._dPadRight = 0;
  49733. _this._isXboxOnePad = false;
  49734. _this.type = Gamepad.XBOX;
  49735. _this._isXboxOnePad = xboxOne;
  49736. return _this;
  49737. }
  49738. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  49739. this._onlefttriggerchanged = callback;
  49740. };
  49741. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  49742. this._onrighttriggerchanged = callback;
  49743. };
  49744. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  49745. get: function () {
  49746. return this._leftTrigger;
  49747. },
  49748. set: function (newValue) {
  49749. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  49750. this._onlefttriggerchanged(newValue);
  49751. }
  49752. this._leftTrigger = newValue;
  49753. },
  49754. enumerable: true,
  49755. configurable: true
  49756. });
  49757. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  49758. get: function () {
  49759. return this._rightTrigger;
  49760. },
  49761. set: function (newValue) {
  49762. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  49763. this._onrighttriggerchanged(newValue);
  49764. }
  49765. this._rightTrigger = newValue;
  49766. },
  49767. enumerable: true,
  49768. configurable: true
  49769. });
  49770. Xbox360Pad.prototype.onbuttondown = function (callback) {
  49771. this._onbuttondown = callback;
  49772. };
  49773. Xbox360Pad.prototype.onbuttonup = function (callback) {
  49774. this._onbuttonup = callback;
  49775. };
  49776. Xbox360Pad.prototype.ondpaddown = function (callback) {
  49777. this._ondpaddown = callback;
  49778. };
  49779. Xbox360Pad.prototype.ondpadup = function (callback) {
  49780. this._ondpadup = callback;
  49781. };
  49782. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  49783. if (newValue !== currentValue) {
  49784. if (this._onbuttondown && newValue === 1) {
  49785. this._onbuttondown(buttonType);
  49786. }
  49787. if (this._onbuttonup && newValue === 0) {
  49788. this._onbuttonup(buttonType);
  49789. }
  49790. }
  49791. return newValue;
  49792. };
  49793. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  49794. if (newValue !== currentValue) {
  49795. if (this._ondpaddown && newValue === 1) {
  49796. this._ondpaddown(buttonType);
  49797. }
  49798. if (this._ondpadup && newValue === 0) {
  49799. this._ondpadup(buttonType);
  49800. }
  49801. }
  49802. return newValue;
  49803. };
  49804. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  49805. get: function () {
  49806. return this._buttonA;
  49807. },
  49808. set: function (value) {
  49809. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  49810. },
  49811. enumerable: true,
  49812. configurable: true
  49813. });
  49814. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  49815. get: function () {
  49816. return this._buttonB;
  49817. },
  49818. set: function (value) {
  49819. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  49820. },
  49821. enumerable: true,
  49822. configurable: true
  49823. });
  49824. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  49825. get: function () {
  49826. return this._buttonX;
  49827. },
  49828. set: function (value) {
  49829. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  49830. },
  49831. enumerable: true,
  49832. configurable: true
  49833. });
  49834. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  49835. get: function () {
  49836. return this._buttonY;
  49837. },
  49838. set: function (value) {
  49839. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  49840. },
  49841. enumerable: true,
  49842. configurable: true
  49843. });
  49844. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  49845. get: function () {
  49846. return this._buttonStart;
  49847. },
  49848. set: function (value) {
  49849. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  49850. },
  49851. enumerable: true,
  49852. configurable: true
  49853. });
  49854. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  49855. get: function () {
  49856. return this._buttonBack;
  49857. },
  49858. set: function (value) {
  49859. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  49860. },
  49861. enumerable: true,
  49862. configurable: true
  49863. });
  49864. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  49865. get: function () {
  49866. return this._buttonLB;
  49867. },
  49868. set: function (value) {
  49869. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  49870. },
  49871. enumerable: true,
  49872. configurable: true
  49873. });
  49874. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  49875. get: function () {
  49876. return this._buttonRB;
  49877. },
  49878. set: function (value) {
  49879. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  49880. },
  49881. enumerable: true,
  49882. configurable: true
  49883. });
  49884. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  49885. get: function () {
  49886. return this._buttonLeftStick;
  49887. },
  49888. set: function (value) {
  49889. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  49890. },
  49891. enumerable: true,
  49892. configurable: true
  49893. });
  49894. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  49895. get: function () {
  49896. return this._buttonRightStick;
  49897. },
  49898. set: function (value) {
  49899. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  49900. },
  49901. enumerable: true,
  49902. configurable: true
  49903. });
  49904. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  49905. get: function () {
  49906. return this._dPadUp;
  49907. },
  49908. set: function (value) {
  49909. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  49910. },
  49911. enumerable: true,
  49912. configurable: true
  49913. });
  49914. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  49915. get: function () {
  49916. return this._dPadDown;
  49917. },
  49918. set: function (value) {
  49919. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  49920. },
  49921. enumerable: true,
  49922. configurable: true
  49923. });
  49924. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  49925. get: function () {
  49926. return this._dPadLeft;
  49927. },
  49928. set: function (value) {
  49929. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  49930. },
  49931. enumerable: true,
  49932. configurable: true
  49933. });
  49934. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  49935. get: function () {
  49936. return this._dPadRight;
  49937. },
  49938. set: function (value) {
  49939. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  49940. },
  49941. enumerable: true,
  49942. configurable: true
  49943. });
  49944. Xbox360Pad.prototype.update = function () {
  49945. _super.prototype.update.call(this);
  49946. if (this._isXboxOnePad) {
  49947. this.buttonA = this.browserGamepad.buttons[0].value;
  49948. this.buttonB = this.browserGamepad.buttons[1].value;
  49949. this.buttonX = this.browserGamepad.buttons[2].value;
  49950. this.buttonY = this.browserGamepad.buttons[3].value;
  49951. this.buttonLB = this.browserGamepad.buttons[4].value;
  49952. this.buttonRB = this.browserGamepad.buttons[5].value;
  49953. this.leftTrigger = this.browserGamepad.axes[2];
  49954. this.rightTrigger = this.browserGamepad.axes[5];
  49955. this.buttonBack = this.browserGamepad.buttons[9].value;
  49956. this.buttonStart = this.browserGamepad.buttons[8].value;
  49957. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  49958. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  49959. this.dPadUp = this.browserGamepad.buttons[11].value;
  49960. this.dPadDown = this.browserGamepad.buttons[12].value;
  49961. this.dPadLeft = this.browserGamepad.buttons[13].value;
  49962. this.dPadRight = this.browserGamepad.buttons[14].value;
  49963. }
  49964. else {
  49965. this.buttonA = this.browserGamepad.buttons[0].value;
  49966. this.buttonB = this.browserGamepad.buttons[1].value;
  49967. this.buttonX = this.browserGamepad.buttons[2].value;
  49968. this.buttonY = this.browserGamepad.buttons[3].value;
  49969. this.buttonLB = this.browserGamepad.buttons[4].value;
  49970. this.buttonRB = this.browserGamepad.buttons[5].value;
  49971. this.leftTrigger = this.browserGamepad.buttons[6].value;
  49972. this.rightTrigger = this.browserGamepad.buttons[7].value;
  49973. this.buttonBack = this.browserGamepad.buttons[8].value;
  49974. this.buttonStart = this.browserGamepad.buttons[9].value;
  49975. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  49976. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  49977. this.dPadUp = this.browserGamepad.buttons[12].value;
  49978. this.dPadDown = this.browserGamepad.buttons[13].value;
  49979. this.dPadLeft = this.browserGamepad.buttons[14].value;
  49980. this.dPadRight = this.browserGamepad.buttons[15].value;
  49981. }
  49982. };
  49983. return Xbox360Pad;
  49984. }(Gamepad));
  49985. BABYLON.Xbox360Pad = Xbox360Pad;
  49986. })(BABYLON || (BABYLON = {}));
  49987. //# sourceMappingURL=babylon.gamepads.js.map
  49988. var BABYLON;
  49989. (function (BABYLON) {
  49990. var PoseEnabledControllerType;
  49991. (function (PoseEnabledControllerType) {
  49992. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  49993. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  49994. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  49995. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  49996. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  49997. var PoseEnabledControllerHelper = (function () {
  49998. function PoseEnabledControllerHelper() {
  49999. }
  50000. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  50001. // Oculus Touch
  50002. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  50003. return new OculusTouchController(vrGamepad);
  50004. }
  50005. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  50006. return new ViveController(vrGamepad);
  50007. }
  50008. else {
  50009. return new GenericController(vrGamepad);
  50010. }
  50011. };
  50012. return PoseEnabledControllerHelper;
  50013. }());
  50014. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  50015. var PoseEnabledController = (function (_super) {
  50016. __extends(PoseEnabledController, _super);
  50017. function PoseEnabledController(vrGamepad) {
  50018. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  50019. _this.vrGamepad = vrGamepad;
  50020. _this.deviceScaleFactor = 1;
  50021. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  50022. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  50023. _this.controllerType = PoseEnabledControllerType.GENERIC;
  50024. _this.position = BABYLON.Vector3.Zero();
  50025. _this.rotationQuaternion = new BABYLON.Quaternion();
  50026. _this.devicePosition = BABYLON.Vector3.Zero();
  50027. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50028. _this._calculatedPosition = BABYLON.Vector3.Zero();
  50029. _this._calculatedRotation = new BABYLON.Quaternion();
  50030. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  50031. return _this;
  50032. }
  50033. PoseEnabledController.prototype.update = function () {
  50034. _super.prototype.update.call(this);
  50035. var pose = this.vrGamepad.pose;
  50036. this.updateFromDevice(pose);
  50037. if (this._mesh) {
  50038. this._mesh.position.copyFrom(this._calculatedPosition);
  50039. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  50040. }
  50041. };
  50042. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  50043. if (poseData) {
  50044. this.rawPose = poseData;
  50045. if (poseData.position) {
  50046. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  50047. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  50048. this.devicePosition.z *= -1;
  50049. }
  50050. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  50051. this._calculatedPosition.addInPlace(this.position);
  50052. }
  50053. if (poseData.orientation) {
  50054. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50055. if (this._mesh) {
  50056. if (this._mesh.getScene().useRightHandedSystem) {
  50057. this.deviceRotationQuaternion.z *= -1;
  50058. this.deviceRotationQuaternion.w *= -1;
  50059. }
  50060. else {
  50061. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  50062. }
  50063. }
  50064. // if the camera is set, rotate to the camera's rotation
  50065. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  50066. }
  50067. }
  50068. };
  50069. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  50070. if (this._mesh) {
  50071. this._mesh.parent = undefined;
  50072. }
  50073. this._mesh = mesh;
  50074. if (this._poseControlledCamera) {
  50075. this._mesh.parent = this._poseControlledCamera;
  50076. }
  50077. if (!this._mesh.rotationQuaternion) {
  50078. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  50079. }
  50080. };
  50081. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  50082. this._poseControlledCamera = camera;
  50083. if (this._mesh) {
  50084. this._mesh.parent = this._poseControlledCamera;
  50085. }
  50086. };
  50087. PoseEnabledController.prototype.detachMesh = function () {
  50088. this._mesh = undefined;
  50089. };
  50090. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  50091. get: function () {
  50092. return this._mesh;
  50093. },
  50094. enumerable: true,
  50095. configurable: true
  50096. });
  50097. PoseEnabledController.prototype.getForwardRay = function (length) {
  50098. if (length === void 0) { length = 100; }
  50099. if (!this.mesh) {
  50100. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  50101. }
  50102. var m = this.mesh.getWorldMatrix();
  50103. var origin = m.getTranslation();
  50104. var forward = new BABYLON.Vector3(0, 0, -1);
  50105. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  50106. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  50107. return new BABYLON.Ray(origin, direction, length);
  50108. };
  50109. return PoseEnabledController;
  50110. }(BABYLON.Gamepad));
  50111. BABYLON.PoseEnabledController = PoseEnabledController;
  50112. var WebVRController = (function (_super) {
  50113. __extends(WebVRController, _super);
  50114. function WebVRController(vrGamepad) {
  50115. var _this = _super.call(this, vrGamepad) || this;
  50116. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  50117. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  50118. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  50119. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  50120. _this.onPadStateChangedObservable = new BABYLON.Observable();
  50121. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  50122. _this.pad = { x: 0, y: 0 };
  50123. // avoid GC, store state in a tmp object
  50124. _this._changes = {
  50125. pressChanged: false,
  50126. touchChanged: false,
  50127. valueChanged: false,
  50128. changed: false
  50129. };
  50130. _this._buttons = new Array(vrGamepad.buttons.length);
  50131. _this.hand = vrGamepad.hand;
  50132. return _this;
  50133. }
  50134. WebVRController.prototype.onButtonStateChange = function (callback) {
  50135. this._onButtonStateChange = callback;
  50136. };
  50137. WebVRController.prototype.update = function () {
  50138. _super.prototype.update.call(this);
  50139. for (var index = 0; index < this._buttons.length; index++) {
  50140. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  50141. }
  50142. ;
  50143. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  50144. this.pad.x = this.leftStick.x;
  50145. this.pad.y = this.leftStick.y;
  50146. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  50147. }
  50148. };
  50149. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  50150. if (!newState) {
  50151. newState = {
  50152. pressed: false,
  50153. touched: false,
  50154. value: 0
  50155. };
  50156. }
  50157. if (!currentState) {
  50158. this._buttons[buttonIndex] = {
  50159. pressed: newState.pressed,
  50160. touched: newState.touched,
  50161. value: newState.value
  50162. };
  50163. return;
  50164. }
  50165. this._checkChanges(newState, currentState);
  50166. if (this._changes.changed) {
  50167. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  50168. this.handleButtonChange(buttonIndex, newState, this._changes);
  50169. }
  50170. this._buttons[buttonIndex].pressed = newState.pressed;
  50171. this._buttons[buttonIndex].touched = newState.touched;
  50172. // oculus triggers are never 0, thou not touched.
  50173. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  50174. };
  50175. WebVRController.prototype._checkChanges = function (newState, currentState) {
  50176. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  50177. this._changes.touchChanged = newState.touched !== currentState.touched;
  50178. this._changes.valueChanged = newState.value !== currentState.value;
  50179. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  50180. return this._changes;
  50181. };
  50182. return WebVRController;
  50183. }(PoseEnabledController));
  50184. BABYLON.WebVRController = WebVRController;
  50185. var OculusTouchController = (function (_super) {
  50186. __extends(OculusTouchController, _super);
  50187. function OculusTouchController(vrGamepad) {
  50188. var _this = _super.call(this, vrGamepad) || this;
  50189. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  50190. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  50191. _this.controllerType = PoseEnabledControllerType.OCULUS;
  50192. return _this;
  50193. }
  50194. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50195. var _this = this;
  50196. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  50197. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  50198. /*
  50199. Parent Mesh name: oculus_touch_left
  50200. - body
  50201. - trigger
  50202. - thumbstick
  50203. - grip
  50204. - button_y
  50205. - button_x
  50206. - button_enter
  50207. */
  50208. _this._defaultModel = newMeshes[1];
  50209. if (meshLoaded) {
  50210. meshLoaded(_this._defaultModel);
  50211. }
  50212. _this.attachToMesh(_this._defaultModel);
  50213. });
  50214. };
  50215. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  50216. // helper getters for left and right hand.
  50217. get: function () {
  50218. if (this.hand === 'right') {
  50219. return this.onMainButtonStateChangedObservable;
  50220. }
  50221. else {
  50222. throw new Error('No A button on left hand');
  50223. }
  50224. },
  50225. enumerable: true,
  50226. configurable: true
  50227. });
  50228. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  50229. get: function () {
  50230. if (this.hand === 'right') {
  50231. return this.onSecondaryButtonStateChangedObservable;
  50232. }
  50233. else {
  50234. throw new Error('No B button on left hand');
  50235. }
  50236. },
  50237. enumerable: true,
  50238. configurable: true
  50239. });
  50240. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  50241. get: function () {
  50242. if (this.hand === 'left') {
  50243. return this.onMainButtonStateChangedObservable;
  50244. }
  50245. else {
  50246. throw new Error('No X button on right hand');
  50247. }
  50248. },
  50249. enumerable: true,
  50250. configurable: true
  50251. });
  50252. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  50253. get: function () {
  50254. if (this.hand === 'left') {
  50255. return this.onSecondaryButtonStateChangedObservable;
  50256. }
  50257. else {
  50258. throw new Error('No Y button on right hand');
  50259. }
  50260. },
  50261. enumerable: true,
  50262. configurable: true
  50263. });
  50264. /*
  50265. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  50266. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  50267. 2) secondary trigger (same)
  50268. 3) A (right) X (left), touch, pressed = value
  50269. 4) B / Y
  50270. 5) thumb rest
  50271. */
  50272. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50273. var notifyObject = state; //{ state: state, changes: changes };
  50274. var triggerDirection = this.hand === 'right' ? -1 : 1;
  50275. switch (buttonIdx) {
  50276. case 0:
  50277. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  50278. return;
  50279. case 1:
  50280. if (this._defaultModel) {
  50281. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  50282. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  50283. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  50284. }
  50285. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  50286. return;
  50287. case 2:
  50288. if (this._defaultModel) {
  50289. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  50290. }
  50291. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  50292. return;
  50293. case 3:
  50294. if (this._defaultModel) {
  50295. if (notifyObject.pressed) {
  50296. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  50297. }
  50298. else {
  50299. (this._defaultModel.getChildren()[1]).position.y = 0;
  50300. }
  50301. }
  50302. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  50303. return;
  50304. case 4:
  50305. if (this._defaultModel) {
  50306. if (notifyObject.pressed) {
  50307. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  50308. }
  50309. else {
  50310. (this._defaultModel.getChildren()[2]).position.y = 0;
  50311. }
  50312. }
  50313. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  50314. return;
  50315. case 5:
  50316. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  50317. return;
  50318. }
  50319. };
  50320. return OculusTouchController;
  50321. }(WebVRController));
  50322. BABYLON.OculusTouchController = OculusTouchController;
  50323. var ViveController = (function (_super) {
  50324. __extends(ViveController, _super);
  50325. function ViveController(vrGamepad) {
  50326. var _this = _super.call(this, vrGamepad) || this;
  50327. _this.controllerType = PoseEnabledControllerType.VIVE;
  50328. return _this;
  50329. }
  50330. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50331. var _this = this;
  50332. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  50333. /*
  50334. Parent Mesh name: ViveWand
  50335. - body
  50336. - r_gripper
  50337. - l_gripper
  50338. - menu_button
  50339. - system_button
  50340. - trackpad
  50341. - trigger
  50342. - LED
  50343. */
  50344. _this._defaultModel = newMeshes[1];
  50345. if (meshLoaded) {
  50346. meshLoaded(_this._defaultModel);
  50347. }
  50348. _this.attachToMesh(_this._defaultModel);
  50349. });
  50350. };
  50351. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  50352. get: function () {
  50353. return this.onMainButtonStateChangedObservable;
  50354. },
  50355. enumerable: true,
  50356. configurable: true
  50357. });
  50358. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  50359. get: function () {
  50360. return this.onMainButtonStateChangedObservable;
  50361. },
  50362. enumerable: true,
  50363. configurable: true
  50364. });
  50365. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  50366. get: function () {
  50367. return this.onSecondaryButtonStateChangedObservable;
  50368. },
  50369. enumerable: true,
  50370. configurable: true
  50371. });
  50372. /**
  50373. * Vive mapping:
  50374. * 0: touchpad
  50375. * 1: trigger
  50376. * 2: left AND right buttons
  50377. * 3: menu button
  50378. */
  50379. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50380. var notifyObject = state; //{ state: state, changes: changes };
  50381. switch (buttonIdx) {
  50382. case 0:
  50383. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  50384. return;
  50385. case 1:
  50386. if (this._defaultModel) {
  50387. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  50388. }
  50389. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  50390. return;
  50391. case 2:
  50392. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  50393. return;
  50394. case 3:
  50395. if (this._defaultModel) {
  50396. if (notifyObject.pressed) {
  50397. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  50398. }
  50399. else {
  50400. (this._defaultModel.getChildren()[2]).position.y = 0;
  50401. }
  50402. }
  50403. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  50404. return;
  50405. }
  50406. };
  50407. return ViveController;
  50408. }(WebVRController));
  50409. BABYLON.ViveController = ViveController;
  50410. var GenericController = (function (_super) {
  50411. __extends(GenericController, _super);
  50412. function GenericController(vrGamepad) {
  50413. return _super.call(this, vrGamepad) || this;
  50414. }
  50415. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50416. var _this = this;
  50417. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "genericvrcontroller.babylon", scene, function (newMeshes) {
  50418. _this._defaultModel = newMeshes[1];
  50419. if (meshLoaded) {
  50420. meshLoaded(_this._defaultModel);
  50421. }
  50422. _this.attachToMesh(_this._defaultModel);
  50423. });
  50424. };
  50425. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50426. console.log("Button id: " + buttonIdx + "state: ");
  50427. console.dir(state);
  50428. };
  50429. return GenericController;
  50430. }(WebVRController));
  50431. BABYLON.GenericController = GenericController;
  50432. })(BABYLON || (BABYLON = {}));
  50433. //# sourceMappingURL=babylon.extendedGamepad.js.map
  50434. /// <reference path="babylon.targetCamera.ts" />
  50435. var BABYLON;
  50436. (function (BABYLON) {
  50437. var FollowCamera = (function (_super) {
  50438. __extends(FollowCamera, _super);
  50439. function FollowCamera(name, position, scene, lockedTarget) {
  50440. var _this = _super.call(this, name, position, scene) || this;
  50441. _this.radius = 12;
  50442. _this.rotationOffset = 0;
  50443. _this.heightOffset = 4;
  50444. _this.cameraAcceleration = 0.05;
  50445. _this.maxCameraSpeed = 20;
  50446. _this.lockedTarget = lockedTarget;
  50447. return _this;
  50448. }
  50449. FollowCamera.prototype.getRadians = function (degrees) {
  50450. return degrees * Math.PI / 180;
  50451. };
  50452. FollowCamera.prototype.follow = function (cameraTarget) {
  50453. if (!cameraTarget)
  50454. return;
  50455. var yRotation;
  50456. if (cameraTarget.rotationQuaternion) {
  50457. var rotMatrix = new BABYLON.Matrix();
  50458. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  50459. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  50460. }
  50461. else {
  50462. yRotation = cameraTarget.rotation.y;
  50463. }
  50464. var radians = this.getRadians(this.rotationOffset) + yRotation;
  50465. var targetPosition = cameraTarget.getAbsolutePosition();
  50466. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  50467. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  50468. var dx = targetX - this.position.x;
  50469. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  50470. var dz = (targetZ) - this.position.z;
  50471. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  50472. var vy = dy * this.cameraAcceleration;
  50473. var vz = dz * this.cameraAcceleration * 2;
  50474. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  50475. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50476. }
  50477. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  50478. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50479. }
  50480. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  50481. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50482. }
  50483. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  50484. this.setTarget(targetPosition);
  50485. };
  50486. FollowCamera.prototype._checkInputs = function () {
  50487. _super.prototype._checkInputs.call(this);
  50488. this.follow(this.lockedTarget);
  50489. };
  50490. FollowCamera.prototype.getClassName = function () {
  50491. return "FollowCamera";
  50492. };
  50493. return FollowCamera;
  50494. }(BABYLON.TargetCamera));
  50495. __decorate([
  50496. BABYLON.serialize()
  50497. ], FollowCamera.prototype, "radius", void 0);
  50498. __decorate([
  50499. BABYLON.serialize()
  50500. ], FollowCamera.prototype, "rotationOffset", void 0);
  50501. __decorate([
  50502. BABYLON.serialize()
  50503. ], FollowCamera.prototype, "heightOffset", void 0);
  50504. __decorate([
  50505. BABYLON.serialize()
  50506. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  50507. __decorate([
  50508. BABYLON.serialize()
  50509. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  50510. __decorate([
  50511. BABYLON.serializeAsMeshReference("lockedTargetId")
  50512. ], FollowCamera.prototype, "lockedTarget", void 0);
  50513. BABYLON.FollowCamera = FollowCamera;
  50514. var ArcFollowCamera = (function (_super) {
  50515. __extends(ArcFollowCamera, _super);
  50516. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  50517. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  50518. _this.alpha = alpha;
  50519. _this.beta = beta;
  50520. _this.radius = radius;
  50521. _this.target = target;
  50522. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  50523. _this.follow();
  50524. return _this;
  50525. }
  50526. ArcFollowCamera.prototype.follow = function () {
  50527. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  50528. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  50529. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  50530. var targetPosition = this.target.getAbsolutePosition();
  50531. this.position = targetPosition.add(this._cartesianCoordinates);
  50532. this.setTarget(targetPosition);
  50533. };
  50534. ArcFollowCamera.prototype._checkInputs = function () {
  50535. _super.prototype._checkInputs.call(this);
  50536. this.follow();
  50537. };
  50538. ArcFollowCamera.prototype.getClassName = function () {
  50539. return "ArcFollowCamera";
  50540. };
  50541. return ArcFollowCamera;
  50542. }(BABYLON.TargetCamera));
  50543. BABYLON.ArcFollowCamera = ArcFollowCamera;
  50544. })(BABYLON || (BABYLON = {}));
  50545. //# sourceMappingURL=babylon.followCamera.js.map
  50546. /// <reference path="babylon.touchCamera.ts" />
  50547. var BABYLON;
  50548. (function (BABYLON) {
  50549. // We're mainly based on the logic defined into the FreeCamera code
  50550. var UniversalCamera = (function (_super) {
  50551. __extends(UniversalCamera, _super);
  50552. //-- end properties for backward compatibility for inputs
  50553. function UniversalCamera(name, position, scene) {
  50554. var _this = _super.call(this, name, position, scene) || this;
  50555. _this.inputs.addGamepad();
  50556. return _this;
  50557. }
  50558. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50559. //-- Begin properties for backward compatibility for inputs
  50560. get: function () {
  50561. var gamepad = this.inputs.attached["gamepad"];
  50562. if (gamepad)
  50563. return gamepad.gamepadAngularSensibility;
  50564. },
  50565. set: function (value) {
  50566. var gamepad = this.inputs.attached["gamepad"];
  50567. if (gamepad)
  50568. gamepad.gamepadAngularSensibility = value;
  50569. },
  50570. enumerable: true,
  50571. configurable: true
  50572. });
  50573. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50574. get: function () {
  50575. var gamepad = this.inputs.attached["gamepad"];
  50576. if (gamepad)
  50577. return gamepad.gamepadMoveSensibility;
  50578. },
  50579. set: function (value) {
  50580. var gamepad = this.inputs.attached["gamepad"];
  50581. if (gamepad)
  50582. gamepad.gamepadMoveSensibility = value;
  50583. },
  50584. enumerable: true,
  50585. configurable: true
  50586. });
  50587. UniversalCamera.prototype.getClassName = function () {
  50588. return "UniversalCamera";
  50589. };
  50590. return UniversalCamera;
  50591. }(BABYLON.TouchCamera));
  50592. BABYLON.UniversalCamera = UniversalCamera;
  50593. })(BABYLON || (BABYLON = {}));
  50594. //# sourceMappingURL=babylon.universalCamera.js.map
  50595. /// <reference path="babylon.universalCamera.ts" />
  50596. var BABYLON;
  50597. (function (BABYLON) {
  50598. // We're mainly based on the logic defined into the FreeCamera code
  50599. var GamepadCamera = (function (_super) {
  50600. __extends(GamepadCamera, _super);
  50601. //-- end properties for backward compatibility for inputs
  50602. function GamepadCamera(name, position, scene) {
  50603. return _super.call(this, name, position, scene) || this;
  50604. }
  50605. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  50606. //-- Begin properties for backward compatibility for inputs
  50607. get: function () {
  50608. var gamepad = this.inputs.attached["gamepad"];
  50609. if (gamepad)
  50610. return gamepad.gamepadAngularSensibility;
  50611. },
  50612. set: function (value) {
  50613. var gamepad = this.inputs.attached["gamepad"];
  50614. if (gamepad)
  50615. gamepad.gamepadAngularSensibility = value;
  50616. },
  50617. enumerable: true,
  50618. configurable: true
  50619. });
  50620. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  50621. get: function () {
  50622. var gamepad = this.inputs.attached["gamepad"];
  50623. if (gamepad)
  50624. return gamepad.gamepadMoveSensibility;
  50625. },
  50626. set: function (value) {
  50627. var gamepad = this.inputs.attached["gamepad"];
  50628. if (gamepad)
  50629. gamepad.gamepadMoveSensibility = value;
  50630. },
  50631. enumerable: true,
  50632. configurable: true
  50633. });
  50634. GamepadCamera.prototype.getClassName = function () {
  50635. return "GamepadCamera";
  50636. };
  50637. return GamepadCamera;
  50638. }(BABYLON.UniversalCamera));
  50639. BABYLON.GamepadCamera = GamepadCamera;
  50640. })(BABYLON || (BABYLON = {}));
  50641. //# sourceMappingURL=babylon.gamepadCamera.js.map
  50642. var BABYLON;
  50643. (function (BABYLON) {
  50644. var PostProcessRenderPipelineManager = (function () {
  50645. function PostProcessRenderPipelineManager() {
  50646. this._renderPipelines = {};
  50647. }
  50648. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  50649. this._renderPipelines[renderPipeline._name] = renderPipeline;
  50650. };
  50651. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  50652. var renderPipeline = this._renderPipelines[renderPipelineName];
  50653. if (!renderPipeline) {
  50654. return;
  50655. }
  50656. renderPipeline._attachCameras(cameras, unique);
  50657. };
  50658. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  50659. var renderPipeline = this._renderPipelines[renderPipelineName];
  50660. if (!renderPipeline) {
  50661. return;
  50662. }
  50663. renderPipeline._detachCameras(cameras);
  50664. };
  50665. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  50666. var renderPipeline = this._renderPipelines[renderPipelineName];
  50667. if (!renderPipeline) {
  50668. return;
  50669. }
  50670. renderPipeline._enableEffect(renderEffectName, cameras);
  50671. };
  50672. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  50673. var renderPipeline = this._renderPipelines[renderPipelineName];
  50674. if (!renderPipeline) {
  50675. return;
  50676. }
  50677. renderPipeline._disableEffect(renderEffectName, cameras);
  50678. };
  50679. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  50680. var renderPipeline = this._renderPipelines[renderPipelineName];
  50681. if (!renderPipeline) {
  50682. return;
  50683. }
  50684. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  50685. };
  50686. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  50687. var renderPipeline = this._renderPipelines[renderPipelineName];
  50688. if (!renderPipeline) {
  50689. return;
  50690. }
  50691. renderPipeline._disableDisplayOnlyPass(cameras);
  50692. };
  50693. PostProcessRenderPipelineManager.prototype.update = function () {
  50694. for (var renderPipelineName in this._renderPipelines) {
  50695. var pipeline = this._renderPipelines[renderPipelineName];
  50696. if (!pipeline.isSupported) {
  50697. pipeline.dispose();
  50698. delete this._renderPipelines[renderPipelineName];
  50699. }
  50700. else {
  50701. pipeline._update();
  50702. }
  50703. }
  50704. };
  50705. return PostProcessRenderPipelineManager;
  50706. }());
  50707. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  50708. })(BABYLON || (BABYLON = {}));
  50709. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  50710. var BABYLON;
  50711. (function (BABYLON) {
  50712. var PostProcessRenderPass = (function () {
  50713. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  50714. this._enabled = true;
  50715. this._refCount = 0;
  50716. this._name = name;
  50717. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  50718. this.setRenderList(renderList);
  50719. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  50720. this._renderTexture.onAfterRenderObservable.add(afterRender);
  50721. this._scene = scene;
  50722. this._renderList = renderList;
  50723. }
  50724. // private
  50725. PostProcessRenderPass.prototype._incRefCount = function () {
  50726. if (this._refCount === 0) {
  50727. this._scene.customRenderTargets.push(this._renderTexture);
  50728. }
  50729. return ++this._refCount;
  50730. };
  50731. PostProcessRenderPass.prototype._decRefCount = function () {
  50732. this._refCount--;
  50733. if (this._refCount <= 0) {
  50734. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  50735. }
  50736. return this._refCount;
  50737. };
  50738. PostProcessRenderPass.prototype._update = function () {
  50739. this.setRenderList(this._renderList);
  50740. };
  50741. // public
  50742. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  50743. this._renderTexture.renderList = renderList;
  50744. };
  50745. PostProcessRenderPass.prototype.getRenderTexture = function () {
  50746. return this._renderTexture;
  50747. };
  50748. return PostProcessRenderPass;
  50749. }());
  50750. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  50751. })(BABYLON || (BABYLON = {}));
  50752. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  50753. var BABYLON;
  50754. (function (BABYLON) {
  50755. var PostProcessRenderEffect = (function () {
  50756. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  50757. this._engine = engine;
  50758. this._name = name;
  50759. this._singleInstance = singleInstance || true;
  50760. this._getPostProcess = getPostProcess;
  50761. this._cameras = [];
  50762. this._indicesForCamera = [];
  50763. this._postProcesses = {};
  50764. this._renderPasses = {};
  50765. this._renderEffectAsPasses = {};
  50766. }
  50767. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  50768. get: function () {
  50769. for (var index in this._postProcesses) {
  50770. if (!this._postProcesses[index].isSupported) {
  50771. return false;
  50772. }
  50773. }
  50774. return true;
  50775. },
  50776. enumerable: true,
  50777. configurable: true
  50778. });
  50779. PostProcessRenderEffect.prototype._update = function () {
  50780. for (var renderPassName in this._renderPasses) {
  50781. this._renderPasses[renderPassName]._update();
  50782. }
  50783. };
  50784. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  50785. this._renderPasses[renderPass._name] = renderPass;
  50786. this._linkParameters();
  50787. };
  50788. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  50789. delete this._renderPasses[renderPass._name];
  50790. this._linkParameters();
  50791. };
  50792. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  50793. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  50794. this._linkParameters();
  50795. };
  50796. PostProcessRenderEffect.prototype.getPass = function (passName) {
  50797. for (var renderPassName in this._renderPasses) {
  50798. if (renderPassName === passName) {
  50799. return this._renderPasses[passName];
  50800. }
  50801. }
  50802. };
  50803. PostProcessRenderEffect.prototype.emptyPasses = function () {
  50804. this._renderPasses = {};
  50805. this._linkParameters();
  50806. };
  50807. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  50808. var cameraKey;
  50809. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50810. for (var i = 0; i < _cam.length; i++) {
  50811. var camera = _cam[i];
  50812. var cameraName = camera.name;
  50813. if (this._singleInstance) {
  50814. cameraKey = 0;
  50815. }
  50816. else {
  50817. cameraKey = cameraName;
  50818. }
  50819. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  50820. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  50821. if (!this._indicesForCamera[cameraName]) {
  50822. this._indicesForCamera[cameraName] = [];
  50823. }
  50824. this._indicesForCamera[cameraName].push(index);
  50825. if (this._cameras.indexOf(camera) === -1) {
  50826. this._cameras[cameraName] = camera;
  50827. }
  50828. for (var passName in this._renderPasses) {
  50829. this._renderPasses[passName]._incRefCount();
  50830. }
  50831. }
  50832. this._linkParameters();
  50833. };
  50834. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  50835. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50836. for (var i = 0; i < _cam.length; i++) {
  50837. var camera = _cam[i];
  50838. var cameraName = camera.name;
  50839. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  50840. var index = this._cameras.indexOf(cameraName);
  50841. this._indicesForCamera.splice(index, 1);
  50842. this._cameras.splice(index, 1);
  50843. for (var passName in this._renderPasses) {
  50844. this._renderPasses[passName]._decRefCount();
  50845. }
  50846. }
  50847. };
  50848. PostProcessRenderEffect.prototype._enable = function (cameras) {
  50849. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50850. for (var i = 0; i < _cam.length; i++) {
  50851. var camera = _cam[i];
  50852. var cameraName = camera.name;
  50853. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  50854. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  50855. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  50856. }
  50857. }
  50858. for (var passName in this._renderPasses) {
  50859. this._renderPasses[passName]._incRefCount();
  50860. }
  50861. }
  50862. };
  50863. PostProcessRenderEffect.prototype._disable = function (cameras) {
  50864. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50865. for (var i = 0; i < _cam.length; i++) {
  50866. var camera = _cam[i];
  50867. var cameraName = camera.Name;
  50868. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  50869. for (var passName in this._renderPasses) {
  50870. this._renderPasses[passName]._decRefCount();
  50871. }
  50872. }
  50873. };
  50874. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  50875. if (this._singleInstance) {
  50876. return this._postProcesses[0];
  50877. }
  50878. else {
  50879. return this._postProcesses[camera.name];
  50880. }
  50881. };
  50882. PostProcessRenderEffect.prototype._linkParameters = function () {
  50883. var _this = this;
  50884. for (var index in this._postProcesses) {
  50885. if (this.applyParameters) {
  50886. this.applyParameters(this._postProcesses[index]);
  50887. }
  50888. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  50889. _this._linkTextures(effect);
  50890. });
  50891. }
  50892. };
  50893. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  50894. for (var renderPassName in this._renderPasses) {
  50895. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  50896. }
  50897. for (var renderEffectName in this._renderEffectAsPasses) {
  50898. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  50899. }
  50900. };
  50901. return PostProcessRenderEffect;
  50902. }());
  50903. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  50904. })(BABYLON || (BABYLON = {}));
  50905. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  50906. var BABYLON;
  50907. (function (BABYLON) {
  50908. var PostProcessRenderPipeline = (function () {
  50909. function PostProcessRenderPipeline(engine, name) {
  50910. this._engine = engine;
  50911. this._name = name;
  50912. this._renderEffects = new Array();
  50913. this._renderEffectsForIsolatedPass = new Array();
  50914. this._cameras = [];
  50915. }
  50916. PostProcessRenderPipeline.prototype.getClassName = function () {
  50917. return "PostProcessRenderPipeline";
  50918. };
  50919. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  50920. get: function () {
  50921. for (var renderEffectName in this._renderEffects) {
  50922. if (!this._renderEffects[renderEffectName].isSupported) {
  50923. return false;
  50924. }
  50925. }
  50926. return true;
  50927. },
  50928. enumerable: true,
  50929. configurable: true
  50930. });
  50931. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  50932. this._renderEffects[renderEffect._name] = renderEffect;
  50933. };
  50934. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  50935. var renderEffects = this._renderEffects[renderEffectName];
  50936. if (!renderEffects) {
  50937. return;
  50938. }
  50939. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  50940. };
  50941. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  50942. var renderEffects = this._renderEffects[renderEffectName];
  50943. if (!renderEffects) {
  50944. return;
  50945. }
  50946. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  50947. };
  50948. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  50949. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50950. var indicesToDelete = [];
  50951. var i;
  50952. for (i = 0; i < _cam.length; i++) {
  50953. var camera = _cam[i];
  50954. var cameraName = camera.name;
  50955. if (this._cameras.indexOf(camera) === -1) {
  50956. this._cameras[cameraName] = camera;
  50957. }
  50958. else if (unique) {
  50959. indicesToDelete.push(i);
  50960. }
  50961. }
  50962. for (i = 0; i < indicesToDelete.length; i++) {
  50963. cameras.splice(indicesToDelete[i], 1);
  50964. }
  50965. for (var renderEffectName in this._renderEffects) {
  50966. this._renderEffects[renderEffectName]._attachCameras(_cam);
  50967. }
  50968. };
  50969. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  50970. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50971. for (var renderEffectName in this._renderEffects) {
  50972. this._renderEffects[renderEffectName]._detachCameras(_cam);
  50973. }
  50974. for (var i = 0; i < _cam.length; i++) {
  50975. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  50976. }
  50977. };
  50978. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  50979. var _this = this;
  50980. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  50981. var pass = null;
  50982. var renderEffectName;
  50983. for (renderEffectName in this._renderEffects) {
  50984. pass = this._renderEffects[renderEffectName].getPass(passName);
  50985. if (pass != null) {
  50986. break;
  50987. }
  50988. }
  50989. if (pass === null) {
  50990. return;
  50991. }
  50992. for (renderEffectName in this._renderEffects) {
  50993. this._renderEffects[renderEffectName]._disable(_cam);
  50994. }
  50995. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  50996. for (var i = 0; i < _cam.length; i++) {
  50997. var camera = _cam[i];
  50998. var cameraName = camera.name;
  50999. 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); });
  51000. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  51001. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  51002. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  51003. }
  51004. };
  51005. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  51006. var _this = this;
  51007. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51008. for (var i = 0; i < _cam.length; i++) {
  51009. var camera = _cam[i];
  51010. var cameraName = camera.name;
  51011. 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); });
  51012. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  51013. }
  51014. for (var renderEffectName in this._renderEffects) {
  51015. this._renderEffects[renderEffectName]._enable(_cam);
  51016. }
  51017. };
  51018. PostProcessRenderPipeline.prototype._update = function () {
  51019. for (var renderEffectName in this._renderEffects) {
  51020. this._renderEffects[renderEffectName]._update();
  51021. }
  51022. for (var i = 0; i < this._cameras.length; i++) {
  51023. var cameraName = this._cameras[i].name;
  51024. if (this._renderEffectsForIsolatedPass[cameraName]) {
  51025. this._renderEffectsForIsolatedPass[cameraName]._update();
  51026. }
  51027. }
  51028. };
  51029. PostProcessRenderPipeline.prototype._reset = function () {
  51030. this._renderEffects = new Array();
  51031. this._renderEffectsForIsolatedPass = new Array();
  51032. };
  51033. PostProcessRenderPipeline.prototype.dispose = function () {
  51034. // Must be implemented by children
  51035. };
  51036. return PostProcessRenderPipeline;
  51037. }());
  51038. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  51039. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  51040. __decorate([
  51041. BABYLON.serialize()
  51042. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  51043. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  51044. })(BABYLON || (BABYLON = {}));
  51045. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  51046. var BABYLON;
  51047. (function (BABYLON) {
  51048. var DepthRenderer = (function () {
  51049. function DepthRenderer(scene, type) {
  51050. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51051. var _this = this;
  51052. this._viewMatrix = BABYLON.Matrix.Zero();
  51053. this._projectionMatrix = BABYLON.Matrix.Zero();
  51054. this._transformMatrix = BABYLON.Matrix.Zero();
  51055. this._worldViewProjection = BABYLON.Matrix.Zero();
  51056. this._scene = scene;
  51057. var engine = scene.getEngine();
  51058. // Render target
  51059. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51060. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51061. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51062. this._depthMap.refreshRate = 1;
  51063. this._depthMap.renderParticles = false;
  51064. this._depthMap.renderList = null;
  51065. // set default depth value to 1.0 (far away)
  51066. this._depthMap.onClearObservable.add(function (engine) {
  51067. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51068. });
  51069. // Custom render function
  51070. var renderSubMesh = function (subMesh) {
  51071. var mesh = subMesh.getRenderingMesh();
  51072. var scene = _this._scene;
  51073. var engine = scene.getEngine();
  51074. // Culling
  51075. engine.setState(subMesh.getMaterial().backFaceCulling);
  51076. // Managing instances
  51077. var batch = mesh._getInstancesRenderList(subMesh._id);
  51078. if (batch.mustReturn) {
  51079. return;
  51080. }
  51081. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  51082. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51083. engine.enableEffect(_this._effect);
  51084. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51085. var material = subMesh.getMaterial();
  51086. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51087. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  51088. // Alpha test
  51089. if (material && material.needAlphaTesting()) {
  51090. var alphaTexture = material.getAlphaTestTexture();
  51091. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51092. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51093. }
  51094. // Bones
  51095. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51096. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51097. }
  51098. // Draw
  51099. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51100. }
  51101. };
  51102. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51103. var index;
  51104. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51105. renderSubMesh(opaqueSubMeshes.data[index]);
  51106. }
  51107. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51108. renderSubMesh(alphaTestSubMeshes.data[index]);
  51109. }
  51110. };
  51111. }
  51112. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  51113. var material = subMesh.getMaterial();
  51114. if (material.disableDepthWrite) {
  51115. return false;
  51116. }
  51117. var defines = [];
  51118. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51119. var mesh = subMesh.getMesh();
  51120. var scene = mesh.getScene();
  51121. // Alpha test
  51122. if (material && material.needAlphaTesting()) {
  51123. defines.push("#define ALPHATEST");
  51124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51125. attribs.push(BABYLON.VertexBuffer.UVKind);
  51126. defines.push("#define UV1");
  51127. }
  51128. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51129. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51130. defines.push("#define UV2");
  51131. }
  51132. }
  51133. // Bones
  51134. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51135. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51136. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51137. if (mesh.numBoneInfluencers > 4) {
  51138. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51139. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51140. }
  51141. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51142. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51143. }
  51144. else {
  51145. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51146. }
  51147. // Instances
  51148. if (useInstances) {
  51149. defines.push("#define INSTANCES");
  51150. attribs.push("world0");
  51151. attribs.push("world1");
  51152. attribs.push("world2");
  51153. attribs.push("world3");
  51154. }
  51155. // Get correct effect
  51156. var join = defines.join("\n");
  51157. if (this._cachedDefines !== join) {
  51158. this._cachedDefines = join;
  51159. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  51160. }
  51161. return this._effect.isReady();
  51162. };
  51163. DepthRenderer.prototype.getDepthMap = function () {
  51164. return this._depthMap;
  51165. };
  51166. // Methods
  51167. DepthRenderer.prototype.dispose = function () {
  51168. this._depthMap.dispose();
  51169. };
  51170. return DepthRenderer;
  51171. }());
  51172. BABYLON.DepthRenderer = DepthRenderer;
  51173. })(BABYLON || (BABYLON = {}));
  51174. //# sourceMappingURL=babylon.depthRenderer.js.map
  51175. var BABYLON;
  51176. (function (BABYLON) {
  51177. var SSAORenderingPipeline = (function (_super) {
  51178. __extends(SSAORenderingPipeline, _super);
  51179. /**
  51180. * @constructor
  51181. * @param {string} name - The rendering pipeline name
  51182. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51183. * @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 }
  51184. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51185. */
  51186. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  51187. var _this = _super.call(this, scene.getEngine(), name) || this;
  51188. // Members
  51189. /**
  51190. * The PassPostProcess id in the pipeline that contains the original scene color
  51191. * @type {string}
  51192. */
  51193. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  51194. /**
  51195. * The SSAO PostProcess id in the pipeline
  51196. * @type {string}
  51197. */
  51198. _this.SSAORenderEffect = "SSAORenderEffect";
  51199. /**
  51200. * The horizontal blur PostProcess id in the pipeline
  51201. * @type {string}
  51202. */
  51203. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  51204. /**
  51205. * The vertical blur PostProcess id in the pipeline
  51206. * @type {string}
  51207. */
  51208. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  51209. /**
  51210. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  51211. * @type {string}
  51212. */
  51213. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  51214. /**
  51215. * The output strength of the SSAO post-process. Default value is 1.0.
  51216. * @type {number}
  51217. */
  51218. _this.totalStrength = 1.0;
  51219. /**
  51220. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  51221. * @type {number}
  51222. */
  51223. _this.radius = 0.0001;
  51224. /**
  51225. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  51226. * Must not be equal to fallOff and superior to fallOff.
  51227. * Default value is 0.975
  51228. * @type {number}
  51229. */
  51230. _this.area = 0.0075;
  51231. /**
  51232. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  51233. * Must not be equal to area and inferior to area.
  51234. * Default value is 0.0
  51235. * @type {number}
  51236. */
  51237. _this.fallOff = 0.000001;
  51238. /**
  51239. * The base color of the SSAO post-process
  51240. * The final result is "base + ssao" between [0, 1]
  51241. * @type {number}
  51242. */
  51243. _this.base = 0.5;
  51244. _this._firstUpdate = true;
  51245. _this._scene = scene;
  51246. // Set up assets
  51247. _this._createRandomTexture();
  51248. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51249. var ssaoRatio = ratio.ssaoRatio || ratio;
  51250. var combineRatio = ratio.combineRatio || ratio;
  51251. _this._ratio = {
  51252. ssaoRatio: ssaoRatio,
  51253. combineRatio: combineRatio
  51254. };
  51255. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51256. _this._createSSAOPostProcess(ssaoRatio);
  51257. _this._createBlurPostProcess(ssaoRatio);
  51258. _this._createSSAOCombinePostProcess(combineRatio);
  51259. // Set up pipeline
  51260. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  51261. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  51262. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  51263. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  51264. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  51265. // Finish
  51266. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51267. if (cameras)
  51268. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51269. return _this;
  51270. }
  51271. // Public Methods
  51272. /**
  51273. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  51274. */
  51275. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51276. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51277. for (var i = 0; i < this._scene.cameras.length; i++) {
  51278. var camera = this._scene.cameras[i];
  51279. this._originalColorPostProcess.dispose(camera);
  51280. this._ssaoPostProcess.dispose(camera);
  51281. this._blurHPostProcess.dispose(camera);
  51282. this._blurVPostProcess.dispose(camera);
  51283. this._ssaoCombinePostProcess.dispose(camera);
  51284. }
  51285. this._randomTexture.dispose();
  51286. if (disableDepthRender)
  51287. this._scene.disableDepthRenderer();
  51288. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51289. _super.prototype.dispose.call(this);
  51290. };
  51291. // Private Methods
  51292. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  51293. var _this = this;
  51294. /*
  51295. var samplerOffsets = [
  51296. -8.0, -6.0, -4.0, -2.0,
  51297. 0.0,
  51298. 2.0, 4.0, 6.0, 8.0
  51299. ];
  51300. */
  51301. var samples = 16;
  51302. var samplerOffsets = [];
  51303. for (var i = -8; i < 8; i++) {
  51304. samplerOffsets.push(i * 2);
  51305. }
  51306. 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");
  51307. this._blurHPostProcess.onApply = function (effect) {
  51308. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  51309. effect.setTexture("depthSampler", _this._depthTexture);
  51310. if (_this._firstUpdate) {
  51311. effect.setArray("samplerOffsets", samplerOffsets);
  51312. }
  51313. };
  51314. 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");
  51315. this._blurVPostProcess.onApply = function (effect) {
  51316. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  51317. effect.setTexture("depthSampler", _this._depthTexture);
  51318. if (_this._firstUpdate) {
  51319. effect.setArray("samplerOffsets", samplerOffsets);
  51320. _this._firstUpdate = false;
  51321. }
  51322. };
  51323. };
  51324. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  51325. var _this = this;
  51326. var numSamples = 16;
  51327. var sampleSphere = [
  51328. 0.5381, 0.1856, -0.4319,
  51329. 0.1379, 0.2486, 0.4430,
  51330. 0.3371, 0.5679, -0.0057,
  51331. -0.6999, -0.0451, -0.0019,
  51332. 0.0689, -0.1598, -0.8547,
  51333. 0.0560, 0.0069, -0.1843,
  51334. -0.0146, 0.1402, 0.0762,
  51335. 0.0100, -0.1924, -0.0344,
  51336. -0.3577, -0.5301, -0.4358,
  51337. -0.3169, 0.1063, 0.0158,
  51338. 0.0103, -0.5869, 0.0046,
  51339. -0.0897, -0.4940, 0.3287,
  51340. 0.7119, -0.0154, -0.0918,
  51341. -0.0533, 0.0596, -0.5411,
  51342. 0.0352, -0.0631, 0.5460,
  51343. -0.4776, 0.2847, -0.0271
  51344. ];
  51345. var samplesFactor = 1.0 / numSamples;
  51346. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  51347. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  51348. "area", "fallOff", "base", "range", "viewport"
  51349. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  51350. var viewport = new BABYLON.Vector2(0, 0);
  51351. this._ssaoPostProcess.onApply = function (effect) {
  51352. if (_this._firstUpdate) {
  51353. effect.setArray3("sampleSphere", sampleSphere);
  51354. effect.setFloat("samplesFactor", samplesFactor);
  51355. effect.setFloat("randTextureTiles", 4.0);
  51356. }
  51357. effect.setFloat("totalStrength", _this.totalStrength);
  51358. effect.setFloat("radius", _this.radius);
  51359. effect.setFloat("area", _this.area);
  51360. effect.setFloat("fallOff", _this.fallOff);
  51361. effect.setFloat("base", _this.base);
  51362. effect.setTexture("textureSampler", _this._depthTexture);
  51363. effect.setTexture("randomSampler", _this._randomTexture);
  51364. };
  51365. };
  51366. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  51367. var _this = this;
  51368. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51369. this._ssaoCombinePostProcess.onApply = function (effect) {
  51370. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  51371. };
  51372. };
  51373. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  51374. var size = 512;
  51375. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51376. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51377. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51378. var context = this._randomTexture.getContext();
  51379. var rand = function (min, max) {
  51380. return Math.random() * (max - min) + min;
  51381. };
  51382. var randVector = BABYLON.Vector3.Zero();
  51383. for (var x = 0; x < size; x++) {
  51384. for (var y = 0; y < size; y++) {
  51385. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  51386. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  51387. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  51388. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  51389. context.fillRect(x, y, 1, 1);
  51390. }
  51391. }
  51392. this._randomTexture.update(false);
  51393. };
  51394. return SSAORenderingPipeline;
  51395. }(BABYLON.PostProcessRenderPipeline));
  51396. __decorate([
  51397. BABYLON.serialize()
  51398. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  51399. __decorate([
  51400. BABYLON.serialize()
  51401. ], SSAORenderingPipeline.prototype, "radius", void 0);
  51402. __decorate([
  51403. BABYLON.serialize()
  51404. ], SSAORenderingPipeline.prototype, "area", void 0);
  51405. __decorate([
  51406. BABYLON.serialize()
  51407. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  51408. __decorate([
  51409. BABYLON.serialize()
  51410. ], SSAORenderingPipeline.prototype, "base", void 0);
  51411. __decorate([
  51412. BABYLON.serialize()
  51413. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  51414. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  51415. })(BABYLON || (BABYLON = {}));
  51416. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  51417. var BABYLON;
  51418. (function (BABYLON) {
  51419. var SSAO2RenderingPipeline = (function (_super) {
  51420. __extends(SSAO2RenderingPipeline, _super);
  51421. /**
  51422. * @constructor
  51423. * @param {string} name - The rendering pipeline name
  51424. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51425. * @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 }
  51426. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51427. */
  51428. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  51429. var _this = _super.call(this, scene.getEngine(), name) || this;
  51430. // Members
  51431. /**
  51432. * The PassPostProcess id in the pipeline that contains the original scene color
  51433. * @type {string}
  51434. */
  51435. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  51436. /**
  51437. * The SSAO PostProcess id in the pipeline
  51438. * @type {string}
  51439. */
  51440. _this.SSAORenderEffect = "SSAORenderEffect";
  51441. /**
  51442. * The horizontal blur PostProcess id in the pipeline
  51443. * @type {string}
  51444. */
  51445. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  51446. /**
  51447. * The vertical blur PostProcess id in the pipeline
  51448. * @type {string}
  51449. */
  51450. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  51451. /**
  51452. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  51453. * @type {string}
  51454. */
  51455. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  51456. /**
  51457. * The output strength of the SSAO post-process. Default value is 1.0.
  51458. * @type {number}
  51459. */
  51460. _this.totalStrength = 1.0;
  51461. /**
  51462. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  51463. * @type {number}
  51464. */
  51465. _this.maxZ = 100.0;
  51466. /**
  51467. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  51468. * @type {number}
  51469. */
  51470. _this.minZAspect = 0.2;
  51471. /**
  51472. * Number of samples used for the SSAO calculations. Default value is 8
  51473. * @type {number}
  51474. */
  51475. _this._samples = 8;
  51476. /**
  51477. * Are we using bilateral blur ?
  51478. * @type {boolean}
  51479. */
  51480. _this._expensiveBlur = true;
  51481. /**
  51482. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  51483. * @type {number}
  51484. */
  51485. _this.radius = 2.0;
  51486. /**
  51487. * The base color of the SSAO post-process
  51488. * The final result is "base + ssao" between [0, 1]
  51489. * @type {number}
  51490. */
  51491. _this.base = 0.1;
  51492. _this._firstUpdate = true;
  51493. _this._scene = scene;
  51494. if (!_this.isSupported) {
  51495. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  51496. return _this;
  51497. }
  51498. var ssaoRatio = ratio.ssaoRatio || ratio;
  51499. var blurRatio = ratio.blurRatio || ratio;
  51500. _this._ratio = {
  51501. ssaoRatio: ssaoRatio,
  51502. blurRatio: blurRatio
  51503. };
  51504. // Set up assets
  51505. _this._createRandomTexture();
  51506. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  51507. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  51508. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51509. _this._createSSAOPostProcess(1.0);
  51510. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  51511. _this._createSSAOCombinePostProcess(blurRatio);
  51512. // Set up pipeline
  51513. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  51514. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  51515. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  51516. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  51517. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  51518. // Finish
  51519. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51520. if (cameras)
  51521. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51522. return _this;
  51523. }
  51524. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  51525. get: function () {
  51526. return this._samples;
  51527. },
  51528. set: function (n) {
  51529. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  51530. this._samples = n;
  51531. this._sampleSphere = this._generateHemisphere();
  51532. this._firstUpdate = true;
  51533. },
  51534. enumerable: true,
  51535. configurable: true
  51536. });
  51537. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  51538. get: function () {
  51539. return this._expensiveBlur;
  51540. },
  51541. set: function (b) {
  51542. 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"]);
  51543. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  51544. this._expensiveBlur = b;
  51545. this._firstUpdate = true;
  51546. },
  51547. enumerable: true,
  51548. configurable: true
  51549. });
  51550. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  51551. /**
  51552. * Support test.
  51553. * @type {boolean}
  51554. */
  51555. get: function () {
  51556. var engine = BABYLON.Engine.LastCreatedEngine;
  51557. return engine.webGLVersion > 1;
  51558. },
  51559. enumerable: true,
  51560. configurable: true
  51561. });
  51562. // Public Methods
  51563. /**
  51564. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  51565. */
  51566. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  51567. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  51568. for (var i = 0; i < this._scene.cameras.length; i++) {
  51569. var camera = this._scene.cameras[i];
  51570. this._originalColorPostProcess.dispose(camera);
  51571. this._ssaoPostProcess.dispose(camera);
  51572. this._blurHPostProcess.dispose(camera);
  51573. this._blurVPostProcess.dispose(camera);
  51574. this._ssaoCombinePostProcess.dispose(camera);
  51575. }
  51576. this._randomTexture.dispose();
  51577. if (disableGeometryBufferRenderer)
  51578. this._scene.disableGeometryBufferRenderer();
  51579. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51580. _super.prototype.dispose.call(this);
  51581. };
  51582. // Private Methods
  51583. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  51584. var _this = this;
  51585. var samples = 16;
  51586. this._samplerOffsets = [];
  51587. var expensive = this.expensiveBlur;
  51588. for (var i = -8; i < 8; i++) {
  51589. this._samplerOffsets.push(i * 2 + 0.5);
  51590. }
  51591. 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");
  51592. this._blurHPostProcess.onApply = function (effect) {
  51593. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  51594. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51595. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51596. effect.setFloat("radius", _this.radius);
  51597. effect.setTexture("depthSampler", _this._depthTexture);
  51598. if (_this._firstUpdate) {
  51599. effect.setArray("samplerOffsets", _this._samplerOffsets);
  51600. }
  51601. };
  51602. 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");
  51603. this._blurVPostProcess.onApply = function (effect) {
  51604. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  51605. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51606. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51607. effect.setFloat("radius", _this.radius);
  51608. effect.setTexture("depthSampler", _this._depthTexture);
  51609. if (_this._firstUpdate) {
  51610. effect.setArray("samplerOffsets", _this._samplerOffsets);
  51611. _this._firstUpdate = false;
  51612. }
  51613. };
  51614. };
  51615. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  51616. var numSamples = this.samples;
  51617. var result = [];
  51618. var vector, scale;
  51619. var rand = function (min, max) {
  51620. return Math.random() * (max - min) + min;
  51621. };
  51622. var lerp = function (start, end, percent) {
  51623. return (start + percent * (end - start));
  51624. };
  51625. var i = 0;
  51626. var normal = new BABYLON.Vector3(0, 0, 1);
  51627. while (i < numSamples) {
  51628. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  51629. vector.normalize();
  51630. scale = i / numSamples;
  51631. scale = lerp(0.1, 1.0, scale * scale);
  51632. vector.scaleInPlace(scale);
  51633. result.push(vector.x, vector.y, vector.z);
  51634. i++;
  51635. }
  51636. return result;
  51637. };
  51638. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  51639. var _this = this;
  51640. var numSamples = this.samples;
  51641. this._sampleSphere = this._generateHemisphere();
  51642. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  51643. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  51644. "base", "range", "projection", "near", "far", "texelSize",
  51645. "xViewport", "yViewport", "maxZ", "minZAspect"
  51646. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  51647. this._ssaoPostProcess.onApply = function (effect) {
  51648. if (_this._firstUpdate) {
  51649. effect.setArray3("sampleSphere", _this._sampleSphere);
  51650. effect.setFloat("randTextureTiles", 4.0);
  51651. }
  51652. effect.setFloat("samplesFactor", 1 / _this.samples);
  51653. effect.setFloat("totalStrength", _this.totalStrength);
  51654. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  51655. effect.setFloat("radius", _this.radius);
  51656. effect.setFloat("maxZ", _this.maxZ);
  51657. effect.setFloat("minZAspect", _this.minZAspect);
  51658. effect.setFloat("base", _this.base);
  51659. effect.setFloat("near", _this._scene.activeCamera.minZ);
  51660. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  51661. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  51662. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  51663. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  51664. effect.setTexture("textureSampler", _this._depthTexture);
  51665. effect.setTexture("normalSampler", _this._normalTexture);
  51666. effect.setTexture("randomSampler", _this._randomTexture);
  51667. };
  51668. };
  51669. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  51670. var _this = this;
  51671. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51672. this._ssaoCombinePostProcess.onApply = function (effect) {
  51673. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  51674. };
  51675. };
  51676. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  51677. var size = 512;
  51678. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51679. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51680. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51681. var context = this._randomTexture.getContext();
  51682. var rand = function (min, max) {
  51683. return Math.random() * (max - min) + min;
  51684. };
  51685. var randVector = BABYLON.Vector3.Zero();
  51686. for (var x = 0; x < size; x++) {
  51687. for (var y = 0; y < size; y++) {
  51688. randVector.x = rand(0.0, 1.0);
  51689. randVector.y = rand(0.0, 1.0);
  51690. randVector.z = 0.0;
  51691. randVector.normalize();
  51692. randVector.scaleInPlace(255);
  51693. randVector.x = Math.floor(randVector.x);
  51694. randVector.y = Math.floor(randVector.y);
  51695. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  51696. context.fillRect(x, y, 1, 1);
  51697. }
  51698. }
  51699. this._randomTexture.update(false);
  51700. };
  51701. return SSAO2RenderingPipeline;
  51702. }(BABYLON.PostProcessRenderPipeline));
  51703. __decorate([
  51704. BABYLON.serialize()
  51705. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  51706. __decorate([
  51707. BABYLON.serialize()
  51708. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  51709. __decorate([
  51710. BABYLON.serialize()
  51711. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  51712. __decorate([
  51713. BABYLON.serialize("samples")
  51714. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  51715. __decorate([
  51716. BABYLON.serialize("expensiveBlur")
  51717. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  51718. __decorate([
  51719. BABYLON.serialize()
  51720. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  51721. __decorate([
  51722. BABYLON.serialize()
  51723. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  51724. __decorate([
  51725. BABYLON.serialize()
  51726. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  51727. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  51728. })(BABYLON || (BABYLON = {}));
  51729. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  51730. // BABYLON.JS Chromatic Aberration GLSL Shader
  51731. // Author: Olivier Guyot
  51732. // Separates very slightly R, G and B colors on the edges of the screen
  51733. // Inspired by Francois Tarlier & Martins Upitis
  51734. var BABYLON;
  51735. (function (BABYLON) {
  51736. var LensRenderingPipeline = (function (_super) {
  51737. __extends(LensRenderingPipeline, _super);
  51738. /**
  51739. * @constructor
  51740. *
  51741. * Effect parameters are as follow:
  51742. * {
  51743. * chromatic_aberration: number; // from 0 to x (1 for realism)
  51744. * edge_blur: number; // from 0 to x (1 for realism)
  51745. * distortion: number; // from 0 to x (1 for realism)
  51746. * grain_amount: number; // from 0 to 1
  51747. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  51748. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  51749. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  51750. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  51751. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  51752. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  51753. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  51754. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  51755. * }
  51756. * Note: if an effect parameter is unset, effect is disabled
  51757. *
  51758. * @param {string} name - The rendering pipeline name
  51759. * @param {object} parameters - An object containing all parameters (see above)
  51760. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51761. * @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)
  51762. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51763. */
  51764. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  51765. if (ratio === void 0) { ratio = 1.0; }
  51766. var _this = _super.call(this, scene.getEngine(), name) || this;
  51767. // Lens effects can be of the following:
  51768. // - chromatic aberration (slight shift of RGB colors)
  51769. // - blur on the edge of the lens
  51770. // - lens distortion
  51771. // - depth-of-field blur & highlights enhancing
  51772. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  51773. // - grain effect (noise or custom texture)
  51774. // Two additional texture samplers are needed:
  51775. // - depth map (for depth-of-field)
  51776. // - grain texture
  51777. /**
  51778. * The chromatic aberration PostProcess id in the pipeline
  51779. * @type {string}
  51780. */
  51781. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  51782. /**
  51783. * The highlights enhancing PostProcess id in the pipeline
  51784. * @type {string}
  51785. */
  51786. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  51787. /**
  51788. * The depth-of-field PostProcess id in the pipeline
  51789. * @type {string}
  51790. */
  51791. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  51792. _this._scene = scene;
  51793. // Fetch texture samplers
  51794. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51795. if (parameters.grain_texture) {
  51796. _this._grainTexture = parameters.grain_texture;
  51797. }
  51798. else {
  51799. _this._createGrainTexture();
  51800. }
  51801. // save parameters
  51802. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  51803. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  51804. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  51805. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  51806. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  51807. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  51808. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  51809. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  51810. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  51811. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  51812. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  51813. // Create effects
  51814. _this._createChromaticAberrationPostProcess(ratio);
  51815. _this._createHighlightsPostProcess(ratio);
  51816. _this._createDepthOfFieldPostProcess(ratio / 4);
  51817. // Set up pipeline
  51818. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  51819. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  51820. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  51821. if (_this._highlightsGain === -1) {
  51822. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  51823. }
  51824. // Finish
  51825. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51826. if (cameras) {
  51827. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51828. }
  51829. return _this;
  51830. }
  51831. // public methods (self explanatory)
  51832. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  51833. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  51834. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  51835. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  51836. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  51837. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  51838. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  51839. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  51840. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  51841. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  51842. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  51843. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  51844. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  51845. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  51846. };
  51847. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  51848. this._highlightsPostProcess.updateEffect();
  51849. };
  51850. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  51851. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  51852. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  51853. this._highlightsGain = amount;
  51854. };
  51855. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  51856. if (this._highlightsGain === -1) {
  51857. this._highlightsGain = 1.0;
  51858. }
  51859. this._highlightsThreshold = amount;
  51860. };
  51861. LensRenderingPipeline.prototype.disableHighlights = function () {
  51862. this._highlightsGain = -1;
  51863. };
  51864. /**
  51865. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  51866. */
  51867. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51868. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51869. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51870. this._chromaticAberrationPostProcess = undefined;
  51871. this._highlightsPostProcess = undefined;
  51872. this._depthOfFieldPostProcess = undefined;
  51873. this._grainTexture.dispose();
  51874. if (disableDepthRender)
  51875. this._scene.disableDepthRenderer();
  51876. };
  51877. // colors shifting and distortion
  51878. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  51879. var _this = this;
  51880. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  51881. [], // samplers
  51882. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51883. this._chromaticAberrationPostProcess.onApply = function (effect) {
  51884. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  51885. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51886. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51887. };
  51888. };
  51889. // highlights enhancing
  51890. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  51891. var _this = this;
  51892. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  51893. [], // samplers
  51894. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  51895. this._highlightsPostProcess.onApply = function (effect) {
  51896. effect.setFloat('gain', _this._highlightsGain);
  51897. effect.setFloat('threshold', _this._highlightsThreshold);
  51898. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  51899. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51900. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51901. };
  51902. };
  51903. // colors shifting and distortion
  51904. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  51905. var _this = this;
  51906. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  51907. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  51908. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  51909. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51910. this._depthOfFieldPostProcess.onApply = function (effect) {
  51911. effect.setTexture("depthSampler", _this._depthTexture);
  51912. effect.setTexture("grainSampler", _this._grainTexture);
  51913. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  51914. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  51915. effect.setFloat('grain_amount', _this._grainAmount);
  51916. effect.setBool('blur_noise', _this._blurNoise);
  51917. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51918. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51919. effect.setFloat('distortion', _this._distortion);
  51920. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  51921. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  51922. effect.setFloat('aperture', _this._dofAperture);
  51923. effect.setFloat('darken', _this._dofDarken);
  51924. effect.setFloat('edge_blur', _this._edgeBlur);
  51925. effect.setBool('highlights', (_this._highlightsGain !== -1));
  51926. effect.setFloat('near', _this._scene.activeCamera.minZ);
  51927. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  51928. };
  51929. };
  51930. // creates a black and white random noise texture, 512x512
  51931. LensRenderingPipeline.prototype._createGrainTexture = function () {
  51932. var size = 512;
  51933. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51934. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51935. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51936. var context = this._grainTexture.getContext();
  51937. var rand = function (min, max) {
  51938. return Math.random() * (max - min) + min;
  51939. };
  51940. var value;
  51941. for (var x = 0; x < size; x++) {
  51942. for (var y = 0; y < size; y++) {
  51943. value = Math.floor(rand(0.42, 0.58) * 255);
  51944. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  51945. context.fillRect(x, y, 1, 1);
  51946. }
  51947. }
  51948. this._grainTexture.update(false);
  51949. };
  51950. return LensRenderingPipeline;
  51951. }(BABYLON.PostProcessRenderPipeline));
  51952. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  51953. })(BABYLON || (BABYLON = {}));
  51954. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  51955. var BABYLON;
  51956. (function (BABYLON) {
  51957. var StandardRenderingPipeline = (function (_super) {
  51958. __extends(StandardRenderingPipeline, _super);
  51959. /**
  51960. * @constructor
  51961. * @param {string} name - The rendering pipeline name
  51962. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51963. * @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)
  51964. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  51965. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51966. */
  51967. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  51968. if (originalPostProcess === void 0) { originalPostProcess = null; }
  51969. var _this = _super.call(this, scene.getEngine(), name) || this;
  51970. _this.downSampleX4PostProcess = null;
  51971. _this.brightPassPostProcess = null;
  51972. _this.blurHPostProcesses = [];
  51973. _this.blurVPostProcesses = [];
  51974. _this.textureAdderPostProcess = null;
  51975. _this.volumetricLightPostProcess = null;
  51976. _this.volumetricLightSmoothXPostProcess = null;
  51977. _this.volumetricLightSmoothYPostProcess = null;
  51978. _this.volumetricLightMergePostProces = null;
  51979. _this.volumetricLightFinalPostProcess = null;
  51980. _this.luminancePostProcess = null;
  51981. _this.luminanceDownSamplePostProcesses = [];
  51982. _this.hdrPostProcess = null;
  51983. _this.textureAdderFinalPostProcess = null;
  51984. _this.lensFlareFinalPostProcess = null;
  51985. _this.hdrFinalPostProcess = null;
  51986. _this.lensFlarePostProcess = null;
  51987. _this.lensFlareComposePostProcess = null;
  51988. _this.motionBlurPostProcess = null;
  51989. _this.depthOfFieldPostProcess = null;
  51990. // Values
  51991. _this.brightThreshold = 1.0;
  51992. _this.blurWidth = 512.0;
  51993. _this.horizontalBlur = false;
  51994. _this.exposure = 1.0;
  51995. _this.lensTexture = null;
  51996. _this.volumetricLightCoefficient = 0.2;
  51997. _this.volumetricLightPower = 4.0;
  51998. _this.volumetricLightBlurScale = 64.0;
  51999. _this.sourceLight = null;
  52000. _this.hdrMinimumLuminance = 1.0;
  52001. _this.hdrDecreaseRate = 0.5;
  52002. _this.hdrIncreaseRate = 0.5;
  52003. _this.lensColorTexture = null;
  52004. _this.lensFlareStrength = 20.0;
  52005. _this.lensFlareGhostDispersal = 1.4;
  52006. _this.lensFlareHaloWidth = 0.7;
  52007. _this.lensFlareDistortionStrength = 16.0;
  52008. _this.lensStarTexture = null;
  52009. _this.lensFlareDirtTexture = null;
  52010. _this.depthOfFieldDistance = 10.0;
  52011. _this.depthOfFieldBlurWidth = 64.0;
  52012. _this.motionStrength = 1.0;
  52013. // IAnimatable
  52014. _this.animations = [];
  52015. _this._currentDepthOfFieldSource = null;
  52016. _this._hdrCurrentLuminance = 1.0;
  52017. // Getters and setters
  52018. _this._bloomEnabled = true;
  52019. _this._depthOfFieldEnabled = false;
  52020. _this._vlsEnabled = false;
  52021. _this._lensFlareEnabled = false;
  52022. _this._hdrEnabled = false;
  52023. _this._motionBlurEnabled = false;
  52024. _this._motionBlurSamples = 64.0;
  52025. _this._volumetricLightStepsCount = 50.0;
  52026. _this._cameras = cameras || [];
  52027. // Initialize
  52028. _this._scene = scene;
  52029. _this._basePostProcess = originalPostProcess;
  52030. _this._ratio = ratio;
  52031. // Misc
  52032. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52033. // Finish
  52034. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52035. _this._buildPipeline();
  52036. return _this;
  52037. }
  52038. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  52039. get: function () {
  52040. return this._bloomEnabled;
  52041. },
  52042. set: function (enabled) {
  52043. if (this._bloomEnabled === enabled) {
  52044. return;
  52045. }
  52046. this._bloomEnabled = enabled;
  52047. this._buildPipeline();
  52048. },
  52049. enumerable: true,
  52050. configurable: true
  52051. });
  52052. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  52053. get: function () {
  52054. return this._depthOfFieldEnabled;
  52055. },
  52056. set: function (enabled) {
  52057. if (this._depthOfFieldEnabled === enabled) {
  52058. return;
  52059. }
  52060. this._depthOfFieldEnabled = enabled;
  52061. this._buildPipeline();
  52062. },
  52063. enumerable: true,
  52064. configurable: true
  52065. });
  52066. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  52067. get: function () {
  52068. return this._lensFlareEnabled;
  52069. },
  52070. set: function (enabled) {
  52071. if (this._lensFlareEnabled === enabled) {
  52072. return;
  52073. }
  52074. this._lensFlareEnabled = enabled;
  52075. this._buildPipeline();
  52076. },
  52077. enumerable: true,
  52078. configurable: true
  52079. });
  52080. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  52081. get: function () {
  52082. return this._hdrEnabled;
  52083. },
  52084. set: function (enabled) {
  52085. if (this._hdrEnabled === enabled) {
  52086. return;
  52087. }
  52088. this._hdrEnabled = enabled;
  52089. this._buildPipeline();
  52090. },
  52091. enumerable: true,
  52092. configurable: true
  52093. });
  52094. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  52095. get: function () {
  52096. return this._vlsEnabled;
  52097. },
  52098. set: function (enabled) {
  52099. if (this._vlsEnabled === enabled) {
  52100. return;
  52101. }
  52102. if (enabled) {
  52103. var geometry = this._scene.enableGeometryBufferRenderer();
  52104. if (!geometry) {
  52105. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  52106. return;
  52107. }
  52108. }
  52109. this._vlsEnabled = enabled;
  52110. this._buildPipeline();
  52111. },
  52112. enumerable: true,
  52113. configurable: true
  52114. });
  52115. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  52116. get: function () {
  52117. return this._motionBlurEnabled;
  52118. },
  52119. set: function (enabled) {
  52120. if (this._motionBlurEnabled === enabled) {
  52121. return;
  52122. }
  52123. this._motionBlurEnabled = enabled;
  52124. this._buildPipeline();
  52125. },
  52126. enumerable: true,
  52127. configurable: true
  52128. });
  52129. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  52130. get: function () {
  52131. return this._volumetricLightStepsCount;
  52132. },
  52133. set: function (count) {
  52134. if (this.volumetricLightPostProcess) {
  52135. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  52136. }
  52137. this._volumetricLightStepsCount = count;
  52138. },
  52139. enumerable: true,
  52140. configurable: true
  52141. });
  52142. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  52143. get: function () {
  52144. return this._motionBlurSamples;
  52145. },
  52146. set: function (samples) {
  52147. if (this.motionBlurPostProcess) {
  52148. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  52149. }
  52150. this._motionBlurSamples = samples;
  52151. },
  52152. enumerable: true,
  52153. configurable: true
  52154. });
  52155. StandardRenderingPipeline.prototype._buildPipeline = function () {
  52156. var _this = this;
  52157. var ratio = this._ratio;
  52158. var scene = this._scene;
  52159. this._disposePostProcesses();
  52160. this._reset();
  52161. // Create pass post-process
  52162. if (!this._basePostProcess) {
  52163. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  52164. this.originalPostProcess.onApply = function (effect) {
  52165. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  52166. };
  52167. }
  52168. else {
  52169. this.originalPostProcess = this._basePostProcess;
  52170. }
  52171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  52172. this._currentDepthOfFieldSource = this.originalPostProcess;
  52173. if (this._vlsEnabled) {
  52174. // Create volumetric light
  52175. this._createVolumetricLightPostProcess(scene, ratio);
  52176. // Create volumetric light final post-process
  52177. 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);
  52178. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  52179. }
  52180. if (this._bloomEnabled) {
  52181. // Create down sample X4 post-process
  52182. this._createDownSampleX4PostProcess(scene, ratio / 2);
  52183. // Create bright pass post-process
  52184. this._createBrightPassPostProcess(scene, ratio / 2);
  52185. // Create gaussian blur post-processes (down sampling blurs)
  52186. this._createBlurPostProcesses(scene, ratio / 4, 1);
  52187. // Create texture adder post-process
  52188. this._createTextureAdderPostProcess(scene, ratio);
  52189. // Create depth-of-field source post-process
  52190. 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);
  52191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  52192. }
  52193. if (this._lensFlareEnabled) {
  52194. // Create lens flare post-process
  52195. this._createLensFlarePostProcess(scene, ratio);
  52196. // Create depth-of-field source post-process post lens-flare and disable it now
  52197. 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);
  52198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  52199. }
  52200. if (this._hdrEnabled) {
  52201. // Create luminance
  52202. this._createLuminancePostProcesses(scene, this._floatTextureType);
  52203. // Create HDR
  52204. this._createHdrPostProcess(scene, ratio);
  52205. // Create depth-of-field source post-process post hdr and disable it now
  52206. 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);
  52207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  52208. }
  52209. if (this._depthOfFieldEnabled) {
  52210. // Create gaussian blur used by depth-of-field
  52211. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  52212. // Create depth-of-field post-process
  52213. this._createDepthOfFieldPostProcess(scene, ratio);
  52214. }
  52215. if (this._motionBlurEnabled) {
  52216. // Create motion blur post-process
  52217. this._createMotionBlurPostProcess(scene, ratio);
  52218. }
  52219. if (this._cameras !== null) {
  52220. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  52221. }
  52222. };
  52223. // Down Sample X4 Post-Processs
  52224. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  52225. var _this = this;
  52226. var downSampleX4Offsets = new Array(32);
  52227. 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);
  52228. this.downSampleX4PostProcess.onApply = function (effect) {
  52229. var id = 0;
  52230. for (var i = -2; i < 2; i++) {
  52231. for (var j = -2; j < 2; j++) {
  52232. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  52233. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  52234. id += 2;
  52235. }
  52236. }
  52237. effect.setArray2("dsOffsets", downSampleX4Offsets);
  52238. };
  52239. // Add to pipeline
  52240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  52241. };
  52242. // Brightpass Post-Process
  52243. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  52244. var _this = this;
  52245. var brightOffsets = new Array(8);
  52246. 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);
  52247. this.brightPassPostProcess.onApply = function (effect) {
  52248. var sU = (1.0 / _this.brightPassPostProcess.width);
  52249. var sV = (1.0 / _this.brightPassPostProcess.height);
  52250. brightOffsets[0] = -0.5 * sU;
  52251. brightOffsets[1] = 0.5 * sV;
  52252. brightOffsets[2] = 0.5 * sU;
  52253. brightOffsets[3] = 0.5 * sV;
  52254. brightOffsets[4] = -0.5 * sU;
  52255. brightOffsets[5] = -0.5 * sV;
  52256. brightOffsets[6] = 0.5 * sU;
  52257. brightOffsets[7] = -0.5 * sV;
  52258. effect.setArray2("dsOffsets", brightOffsets);
  52259. effect.setFloat("brightThreshold", _this.brightThreshold);
  52260. };
  52261. // Add to pipeline
  52262. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  52263. };
  52264. // Create blur H&V post-processes
  52265. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  52266. var _this = this;
  52267. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  52268. var engine = scene.getEngine();
  52269. 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);
  52270. 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);
  52271. blurX.onActivateObservable.add(function () {
  52272. var dw = blurX.width / engine.getRenderingCanvas().width;
  52273. blurX.kernel = _this[blurWidthKey] * dw;
  52274. });
  52275. blurY.onActivateObservable.add(function () {
  52276. var dw = blurY.height / engine.getRenderingCanvas().height;
  52277. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  52278. });
  52279. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  52280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  52281. this.blurHPostProcesses.push(blurX);
  52282. this.blurVPostProcesses.push(blurY);
  52283. };
  52284. // Create texture adder post-process
  52285. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  52286. var _this = this;
  52287. 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);
  52288. this.textureAdderPostProcess.onApply = function (effect) {
  52289. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  52290. effect.setTexture("lensSampler", _this.lensTexture);
  52291. effect.setFloat("exposure", _this.exposure);
  52292. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  52293. };
  52294. // Add to pipeline
  52295. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  52296. };
  52297. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  52298. var _this = this;
  52299. var geometryRenderer = scene.enableGeometryBufferRenderer();
  52300. geometryRenderer.enablePosition = true;
  52301. var geometry = geometryRenderer.getGBuffer();
  52302. // Base post-process
  52303. 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));
  52304. var depthValues = BABYLON.Vector2.Zero();
  52305. this.volumetricLightPostProcess.onApply = function (effect) {
  52306. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  52307. var generator = _this.sourceLight.getShadowGenerator();
  52308. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  52309. effect.setTexture("positionSampler", geometry.textures[2]);
  52310. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  52311. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  52312. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  52313. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  52314. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  52315. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  52316. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  52317. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  52318. effect.setVector2("depthValues", depthValues);
  52319. }
  52320. };
  52321. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  52322. // Smooth
  52323. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  52324. // Merge
  52325. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  52326. this.volumetricLightMergePostProces.onApply = function (effect) {
  52327. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  52328. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  52329. };
  52330. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  52331. };
  52332. // Create luminance
  52333. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  52334. var _this = this;
  52335. // Create luminance
  52336. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  52337. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  52338. var offsets = [];
  52339. this.luminancePostProcess.onApply = function (effect) {
  52340. var sU = (1.0 / _this.luminancePostProcess.width);
  52341. var sV = (1.0 / _this.luminancePostProcess.height);
  52342. offsets[0] = -0.5 * sU;
  52343. offsets[1] = 0.5 * sV;
  52344. offsets[2] = 0.5 * sU;
  52345. offsets[3] = 0.5 * sV;
  52346. offsets[4] = -0.5 * sU;
  52347. offsets[5] = -0.5 * sV;
  52348. offsets[6] = 0.5 * sU;
  52349. offsets[7] = -0.5 * sV;
  52350. effect.setArray2("lumOffsets", offsets);
  52351. };
  52352. // Add to pipeline
  52353. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  52354. // Create down sample luminance
  52355. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  52356. var size = Math.pow(3, i);
  52357. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  52358. if (i === 0) {
  52359. defines += "#define FINAL_DOWN_SAMPLER";
  52360. }
  52361. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  52362. this.luminanceDownSamplePostProcesses.push(postProcess);
  52363. }
  52364. // Create callbacks and add effects
  52365. var lastLuminance = this.luminancePostProcess;
  52366. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  52367. var downSampleOffsets = new Array(18);
  52368. pp.onApply = function (effect) {
  52369. var id = 0;
  52370. for (var x = -1; x < 2; x++) {
  52371. for (var y = -1; y < 2; y++) {
  52372. downSampleOffsets[id] = x / lastLuminance.width;
  52373. downSampleOffsets[id + 1] = y / lastLuminance.height;
  52374. id += 2;
  52375. }
  52376. }
  52377. effect.setArray2("dsOffsets", downSampleOffsets);
  52378. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  52379. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  52380. lastLuminance = _this.luminancePostProcess;
  52381. }
  52382. else {
  52383. lastLuminance = pp;
  52384. }
  52385. };
  52386. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  52387. pp.onAfterRender = function (effect) {
  52388. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  52389. 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);
  52390. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  52391. };
  52392. }
  52393. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  52394. });
  52395. };
  52396. // Create HDR post-process
  52397. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  52398. var _this = this;
  52399. 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);
  52400. var outputLiminance = 1;
  52401. var time = 0;
  52402. var lastTime = 0;
  52403. this.hdrPostProcess.onApply = function (effect) {
  52404. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  52405. time += scene.getEngine().getDeltaTime();
  52406. if (outputLiminance < 0) {
  52407. outputLiminance = _this._hdrCurrentLuminance;
  52408. }
  52409. else {
  52410. var dt = (lastTime - time) / 1000.0;
  52411. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  52412. outputLiminance += _this.hdrDecreaseRate * dt;
  52413. }
  52414. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  52415. outputLiminance -= _this.hdrIncreaseRate * dt;
  52416. }
  52417. else {
  52418. outputLiminance = _this._hdrCurrentLuminance;
  52419. }
  52420. }
  52421. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  52422. effect.setFloat("averageLuminance", outputLiminance);
  52423. lastTime = time;
  52424. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  52425. };
  52426. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  52427. };
  52428. // Create lens flare post-process
  52429. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  52430. var _this = this;
  52431. 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);
  52432. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  52433. this._createBlurPostProcesses(scene, ratio / 4, 2);
  52434. 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);
  52435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  52436. var resolution = new BABYLON.Vector2(0, 0);
  52437. // Lens flare
  52438. this.lensFlarePostProcess.onApply = function (effect) {
  52439. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  52440. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  52441. effect.setFloat("strength", _this.lensFlareStrength);
  52442. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  52443. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  52444. // Shift
  52445. resolution.x = _this.lensFlarePostProcess.width;
  52446. resolution.y = _this.lensFlarePostProcess.height;
  52447. effect.setVector2("resolution", resolution);
  52448. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  52449. };
  52450. // Compose
  52451. 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);
  52452. 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);
  52453. this.lensFlareComposePostProcess.onApply = function (effect) {
  52454. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  52455. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  52456. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  52457. // Lens start rotation matrix
  52458. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  52459. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  52460. 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));
  52461. camRot *= 4.0;
  52462. 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);
  52463. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  52464. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  52465. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  52466. };
  52467. };
  52468. // Create depth-of-field post-process
  52469. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  52470. var _this = this;
  52471. 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);
  52472. this.depthOfFieldPostProcess.onApply = function (effect) {
  52473. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  52474. effect.setTexture("depthSampler", _this._getDepthTexture());
  52475. effect.setFloat("distance", _this.depthOfFieldDistance);
  52476. };
  52477. // Add to pipeline
  52478. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  52479. };
  52480. // Create motion blur post-process
  52481. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  52482. var _this = this;
  52483. 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);
  52484. var motionScale = 0;
  52485. var prevViewProjection = BABYLON.Matrix.Identity();
  52486. var invViewProjection = BABYLON.Matrix.Identity();
  52487. var viewProjection = BABYLON.Matrix.Identity();
  52488. var screenSize = BABYLON.Vector2.Zero();
  52489. this.motionBlurPostProcess.onApply = function (effect) {
  52490. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  52491. viewProjection.invertToRef(invViewProjection);
  52492. effect.setMatrix("inverseViewProjection", invViewProjection);
  52493. effect.setMatrix("prevViewProjection", prevViewProjection);
  52494. prevViewProjection = viewProjection;
  52495. screenSize.x = _this.motionBlurPostProcess.width;
  52496. screenSize.y = _this.motionBlurPostProcess.height;
  52497. effect.setVector2("screenSize", screenSize);
  52498. motionScale = scene.getEngine().getFps() / 60.0;
  52499. effect.setFloat("motionScale", motionScale);
  52500. effect.setFloat("motionStrength", _this.motionStrength);
  52501. effect.setTexture("depthSampler", _this._getDepthTexture());
  52502. };
  52503. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  52504. };
  52505. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  52506. var geometry = this._scene.enableGeometryBufferRenderer();
  52507. if (geometry) {
  52508. return geometry.getGBuffer().textures[0];
  52509. }
  52510. return this._scene.enableDepthRenderer().getDepthMap();
  52511. };
  52512. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  52513. for (var i = 0; i < this._cameras.length; i++) {
  52514. var camera = this._cameras[i];
  52515. if (this.originalPostProcess) {
  52516. this.originalPostProcess.dispose(camera);
  52517. }
  52518. if (this.downSampleX4PostProcess) {
  52519. this.downSampleX4PostProcess.dispose(camera);
  52520. }
  52521. if (this.brightPassPostProcess) {
  52522. this.brightPassPostProcess.dispose(camera);
  52523. }
  52524. if (this.textureAdderPostProcess) {
  52525. this.textureAdderPostProcess.dispose(camera);
  52526. }
  52527. if (this.textureAdderFinalPostProcess) {
  52528. this.textureAdderFinalPostProcess.dispose(camera);
  52529. }
  52530. if (this.volumetricLightPostProcess) {
  52531. this.volumetricLightPostProcess.dispose(camera);
  52532. }
  52533. if (this.volumetricLightSmoothXPostProcess) {
  52534. this.volumetricLightSmoothXPostProcess.dispose(camera);
  52535. }
  52536. if (this.volumetricLightSmoothYPostProcess) {
  52537. this.volumetricLightSmoothYPostProcess.dispose(camera);
  52538. }
  52539. if (this.volumetricLightMergePostProces) {
  52540. this.volumetricLightMergePostProces.dispose(camera);
  52541. }
  52542. if (this.volumetricLightFinalPostProcess) {
  52543. this.volumetricLightFinalPostProcess.dispose(camera);
  52544. }
  52545. if (this.lensFlarePostProcess) {
  52546. this.lensFlarePostProcess.dispose(camera);
  52547. }
  52548. if (this.lensFlareComposePostProcess) {
  52549. this.lensFlareComposePostProcess.dispose(camera);
  52550. }
  52551. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  52552. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  52553. }
  52554. if (this.luminancePostProcess) {
  52555. this.luminancePostProcess.dispose(camera);
  52556. }
  52557. if (this.hdrPostProcess) {
  52558. this.hdrPostProcess.dispose(camera);
  52559. }
  52560. if (this.hdrFinalPostProcess) {
  52561. this.hdrFinalPostProcess.dispose(camera);
  52562. }
  52563. if (this.depthOfFieldPostProcess) {
  52564. this.depthOfFieldPostProcess.dispose(camera);
  52565. }
  52566. if (this.motionBlurPostProcess) {
  52567. this.motionBlurPostProcess.dispose(camera);
  52568. }
  52569. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  52570. this.blurHPostProcesses[j].dispose(camera);
  52571. }
  52572. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  52573. this.blurVPostProcesses[j].dispose(camera);
  52574. }
  52575. }
  52576. this.originalPostProcess = null;
  52577. this.downSampleX4PostProcess = null;
  52578. this.brightPassPostProcess = null;
  52579. this.textureAdderPostProcess = null;
  52580. this.textureAdderFinalPostProcess = null;
  52581. this.volumetricLightPostProcess = null;
  52582. this.volumetricLightSmoothXPostProcess = null;
  52583. this.volumetricLightSmoothYPostProcess = null;
  52584. this.volumetricLightMergePostProces = null;
  52585. this.volumetricLightFinalPostProcess = null;
  52586. this.lensFlarePostProcess = null;
  52587. this.lensFlareComposePostProcess = null;
  52588. this.luminancePostProcess = null;
  52589. this.hdrPostProcess = null;
  52590. this.hdrFinalPostProcess = null;
  52591. this.depthOfFieldPostProcess = null;
  52592. this.motionBlurPostProcess = null;
  52593. this.luminanceDownSamplePostProcesses = [];
  52594. this.blurHPostProcesses = [];
  52595. this.blurVPostProcesses = [];
  52596. };
  52597. // Dispose
  52598. StandardRenderingPipeline.prototype.dispose = function () {
  52599. this._disposePostProcesses();
  52600. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  52601. _super.prototype.dispose.call(this);
  52602. };
  52603. // Serialize rendering pipeline
  52604. StandardRenderingPipeline.prototype.serialize = function () {
  52605. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52606. serializationObject.customType = "StandardRenderingPipeline";
  52607. return serializationObject;
  52608. };
  52609. /**
  52610. * Static members
  52611. */
  52612. // Parse serialized pipeline
  52613. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  52614. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  52615. };
  52616. return StandardRenderingPipeline;
  52617. }(BABYLON.PostProcessRenderPipeline));
  52618. // Luminance steps
  52619. StandardRenderingPipeline.LuminanceSteps = 6;
  52620. __decorate([
  52621. BABYLON.serialize()
  52622. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  52623. __decorate([
  52624. BABYLON.serialize()
  52625. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  52626. __decorate([
  52627. BABYLON.serialize()
  52628. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  52629. __decorate([
  52630. BABYLON.serialize()
  52631. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  52632. __decorate([
  52633. BABYLON.serializeAsTexture("lensTexture")
  52634. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  52635. __decorate([
  52636. BABYLON.serialize()
  52637. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  52638. __decorate([
  52639. BABYLON.serialize()
  52640. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  52641. __decorate([
  52642. BABYLON.serialize()
  52643. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  52644. __decorate([
  52645. BABYLON.serialize()
  52646. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  52647. __decorate([
  52648. BABYLON.serialize()
  52649. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  52650. __decorate([
  52651. BABYLON.serialize()
  52652. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  52653. __decorate([
  52654. BABYLON.serializeAsTexture("lensColorTexture")
  52655. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  52656. __decorate([
  52657. BABYLON.serialize()
  52658. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  52659. __decorate([
  52660. BABYLON.serialize()
  52661. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  52662. __decorate([
  52663. BABYLON.serialize()
  52664. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  52665. __decorate([
  52666. BABYLON.serialize()
  52667. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  52668. __decorate([
  52669. BABYLON.serializeAsTexture("lensStarTexture")
  52670. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  52671. __decorate([
  52672. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  52673. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  52674. __decorate([
  52675. BABYLON.serialize()
  52676. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  52677. __decorate([
  52678. BABYLON.serialize()
  52679. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  52680. __decorate([
  52681. BABYLON.serialize()
  52682. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  52683. __decorate([
  52684. BABYLON.serialize()
  52685. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  52686. __decorate([
  52687. BABYLON.serialize()
  52688. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  52689. __decorate([
  52690. BABYLON.serialize()
  52691. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  52692. __decorate([
  52693. BABYLON.serialize()
  52694. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  52695. __decorate([
  52696. BABYLON.serialize()
  52697. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  52698. __decorate([
  52699. BABYLON.serialize()
  52700. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  52701. __decorate([
  52702. BABYLON.serialize()
  52703. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  52704. __decorate([
  52705. BABYLON.serialize()
  52706. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  52707. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  52708. })(BABYLON || (BABYLON = {}));
  52709. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  52710. var BABYLON;
  52711. (function (BABYLON) {
  52712. var FxaaPostProcess = (function (_super) {
  52713. __extends(FxaaPostProcess, _super);
  52714. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52715. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52716. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  52717. _this.onApplyObservable.add(function (effect) {
  52718. var texelSize = _this.texelSize;
  52719. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  52720. });
  52721. return _this;
  52722. }
  52723. return FxaaPostProcess;
  52724. }(BABYLON.PostProcess));
  52725. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52726. })(BABYLON || (BABYLON = {}));
  52727. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  52728. var BABYLON;
  52729. (function (BABYLON) {
  52730. var DefaultRenderingPipeline = (function (_super) {
  52731. __extends(DefaultRenderingPipeline, _super);
  52732. /**
  52733. * @constructor
  52734. * @param {string} name - The rendering pipeline name
  52735. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52736. * @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)
  52737. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52738. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  52739. */
  52740. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  52741. if (automaticBuild === void 0) { automaticBuild = true; }
  52742. var _this = _super.call(this, scene.getEngine(), name) || this;
  52743. _this.PassPostProcessId = "PassPostProcessEffect";
  52744. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  52745. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  52746. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  52747. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  52748. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  52749. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  52750. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  52751. // IAnimatable
  52752. _this.animations = [];
  52753. // Values
  52754. _this._bloomEnabled = false;
  52755. _this._fxaaEnabled = false;
  52756. _this._imageProcessingEnabled = true;
  52757. _this._bloomScale = 0.6;
  52758. _this._buildAllowed = true;
  52759. /**
  52760. * Specifies the size of the bloom blur kernel, relative to the final output size
  52761. */
  52762. _this.bloomKernel = 64;
  52763. /**
  52764. * Specifies the weight of the bloom in the final rendering
  52765. */
  52766. _this._bloomWeight = 0.15;
  52767. _this._cameras = cameras || [];
  52768. _this._buildAllowed = automaticBuild;
  52769. // Initialize
  52770. _this._scene = scene;
  52771. var caps = _this._scene.getEngine().getCaps();
  52772. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  52773. // Misc
  52774. if (_this._hdr) {
  52775. if (caps.textureHalfFloatRender) {
  52776. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52777. }
  52778. else if (caps.textureFloatRender) {
  52779. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52780. }
  52781. }
  52782. else {
  52783. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52784. }
  52785. // Attach
  52786. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52787. _this._buildPipeline();
  52788. return _this;
  52789. }
  52790. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  52791. get: function () {
  52792. return this._bloomWeight;
  52793. },
  52794. set: function (value) {
  52795. if (this._bloomWeight === value) {
  52796. return;
  52797. }
  52798. this._bloomWeight = value;
  52799. if (this._hdr && this.copyBack) {
  52800. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  52801. }
  52802. },
  52803. enumerable: true,
  52804. configurable: true
  52805. });
  52806. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  52807. get: function () {
  52808. return this._bloomScale;
  52809. },
  52810. set: function (value) {
  52811. if (this._bloomScale === value) {
  52812. return;
  52813. }
  52814. this._bloomScale = value;
  52815. this._buildPipeline();
  52816. },
  52817. enumerable: true,
  52818. configurable: true
  52819. });
  52820. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  52821. get: function () {
  52822. return this._bloomEnabled;
  52823. },
  52824. set: function (enabled) {
  52825. if (this._bloomEnabled === enabled) {
  52826. return;
  52827. }
  52828. this._bloomEnabled = enabled;
  52829. this._buildPipeline();
  52830. },
  52831. enumerable: true,
  52832. configurable: true
  52833. });
  52834. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  52835. get: function () {
  52836. return this._fxaaEnabled;
  52837. },
  52838. set: function (enabled) {
  52839. if (this._fxaaEnabled === enabled) {
  52840. return;
  52841. }
  52842. this._fxaaEnabled = enabled;
  52843. this._buildPipeline();
  52844. },
  52845. enumerable: true,
  52846. configurable: true
  52847. });
  52848. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  52849. get: function () {
  52850. return this._imageProcessingEnabled;
  52851. },
  52852. set: function (enabled) {
  52853. if (this._imageProcessingEnabled === enabled) {
  52854. return;
  52855. }
  52856. this._imageProcessingEnabled = enabled;
  52857. this._buildPipeline();
  52858. },
  52859. enumerable: true,
  52860. configurable: true
  52861. });
  52862. /**
  52863. * Force the compilation of the entire pipeline.
  52864. */
  52865. DefaultRenderingPipeline.prototype.prepare = function () {
  52866. var previousState = this._buildAllowed;
  52867. this._buildAllowed = true;
  52868. this._buildPipeline();
  52869. this._buildAllowed = previousState;
  52870. };
  52871. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  52872. var _this = this;
  52873. if (!this._buildAllowed) {
  52874. return;
  52875. }
  52876. var engine = this._scene.getEngine();
  52877. this._disposePostProcesses();
  52878. this._reset();
  52879. if (this.bloomEnabled) {
  52880. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52881. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  52882. if (!this._hdr) {
  52883. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52884. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  52885. this.highlights.autoClear = false;
  52886. this.highlights.alwaysForcePOT = true;
  52887. }
  52888. 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);
  52889. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  52890. this.blurX.alwaysForcePOT = true;
  52891. this.blurX.autoClear = false;
  52892. this.blurX.onActivateObservable.add(function () {
  52893. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  52894. _this.blurX.kernel = _this.bloomKernel * dw;
  52895. });
  52896. 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);
  52897. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  52898. this.blurY.alwaysForcePOT = true;
  52899. this.blurY.autoClear = false;
  52900. this.blurY.onActivateObservable.add(function () {
  52901. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  52902. _this.blurY.kernel = _this.bloomKernel * dh;
  52903. });
  52904. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52905. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  52906. this.copyBack.alwaysForcePOT = true;
  52907. if (this._hdr) {
  52908. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  52909. var w = this.bloomWeight;
  52910. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  52911. }
  52912. else {
  52913. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  52914. }
  52915. this.copyBack.autoClear = false;
  52916. }
  52917. if (this._imageProcessingEnabled) {
  52918. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52919. if (this._hdr) {
  52920. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  52921. }
  52922. }
  52923. if (this.fxaaEnabled) {
  52924. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52925. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  52926. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  52927. }
  52928. else {
  52929. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  52930. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  52931. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  52932. }
  52933. if (this.bloomEnabled) {
  52934. if (this._hdr) {
  52935. this.copyBack.shareOutputWith(this.blurX);
  52936. if (this.imageProcessing) {
  52937. this.imageProcessing.shareOutputWith(this.pass);
  52938. this.imageProcessing.autoClear = false;
  52939. }
  52940. else if (this.fxaa) {
  52941. this.fxaa.shareOutputWith(this.pass);
  52942. }
  52943. else {
  52944. this.finalMerge.shareOutputWith(this.pass);
  52945. }
  52946. }
  52947. else {
  52948. if (this.fxaa) {
  52949. this.fxaa.shareOutputWith(this.pass);
  52950. }
  52951. else {
  52952. this.finalMerge.shareOutputWith(this.pass);
  52953. }
  52954. }
  52955. }
  52956. if (this._cameras !== null) {
  52957. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  52958. }
  52959. };
  52960. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  52961. for (var i = 0; i < this._cameras.length; i++) {
  52962. var camera = this._cameras[i];
  52963. if (this.pass) {
  52964. this.pass.dispose(camera);
  52965. }
  52966. if (this.highlights) {
  52967. this.highlights.dispose(camera);
  52968. }
  52969. if (this.blurX) {
  52970. this.blurX.dispose(camera);
  52971. }
  52972. if (this.blurY) {
  52973. this.blurY.dispose(camera);
  52974. }
  52975. if (this.copyBack) {
  52976. this.copyBack.dispose(camera);
  52977. }
  52978. if (this.imageProcessing) {
  52979. this.imageProcessing.dispose(camera);
  52980. }
  52981. if (this.fxaa) {
  52982. this.fxaa.dispose(camera);
  52983. }
  52984. if (this.finalMerge) {
  52985. this.finalMerge.dispose(camera);
  52986. }
  52987. }
  52988. this.pass = null;
  52989. this.highlights = null;
  52990. this.blurX = null;
  52991. this.blurY = null;
  52992. this.copyBack = null;
  52993. this.imageProcessing = null;
  52994. this.fxaa = null;
  52995. this.finalMerge = null;
  52996. };
  52997. // Dispose
  52998. DefaultRenderingPipeline.prototype.dispose = function () {
  52999. this._disposePostProcesses();
  53000. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53001. _super.prototype.dispose.call(this);
  53002. };
  53003. // Serialize rendering pipeline
  53004. DefaultRenderingPipeline.prototype.serialize = function () {
  53005. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53006. serializationObject.customType = "DefaultRenderingPipeline";
  53007. return serializationObject;
  53008. };
  53009. // Parse serialized pipeline
  53010. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53011. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  53012. };
  53013. return DefaultRenderingPipeline;
  53014. }(BABYLON.PostProcessRenderPipeline));
  53015. __decorate([
  53016. BABYLON.serialize()
  53017. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  53018. __decorate([
  53019. BABYLON.serialize()
  53020. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  53021. __decorate([
  53022. BABYLON.serialize()
  53023. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  53024. __decorate([
  53025. BABYLON.serialize()
  53026. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  53027. __decorate([
  53028. BABYLON.serialize()
  53029. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  53030. __decorate([
  53031. BABYLON.serialize()
  53032. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  53033. __decorate([
  53034. BABYLON.serialize()
  53035. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  53036. __decorate([
  53037. BABYLON.serialize()
  53038. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  53039. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  53040. })(BABYLON || (BABYLON = {}));
  53041. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  53042. var BABYLON;
  53043. (function (BABYLON) {
  53044. var GeometryBufferRenderer = (function () {
  53045. function GeometryBufferRenderer(scene, ratio) {
  53046. if (ratio === void 0) { ratio = 1; }
  53047. this._viewMatrix = BABYLON.Matrix.Zero();
  53048. this._projectionMatrix = BABYLON.Matrix.Zero();
  53049. this._transformMatrix = BABYLON.Matrix.Zero();
  53050. this._worldViewProjection = BABYLON.Matrix.Zero();
  53051. this._enablePosition = false;
  53052. this._scene = scene;
  53053. this._ratio = ratio;
  53054. // Render target
  53055. this._createRenderTargets();
  53056. }
  53057. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  53058. set: function (meshes) {
  53059. this._multiRenderTarget.renderList = meshes;
  53060. },
  53061. enumerable: true,
  53062. configurable: true
  53063. });
  53064. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  53065. get: function () {
  53066. return this._multiRenderTarget.isSupported;
  53067. },
  53068. enumerable: true,
  53069. configurable: true
  53070. });
  53071. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  53072. get: function () {
  53073. return this._enablePosition;
  53074. },
  53075. set: function (enable) {
  53076. this._enablePosition = enable;
  53077. this.dispose();
  53078. this._createRenderTargets();
  53079. },
  53080. enumerable: true,
  53081. configurable: true
  53082. });
  53083. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  53084. var material = subMesh.getMaterial();
  53085. if (material && material.disableDepthWrite) {
  53086. return false;
  53087. }
  53088. var defines = [];
  53089. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  53090. var mesh = subMesh.getMesh();
  53091. var scene = mesh.getScene();
  53092. // Alpha test
  53093. if (material && material.needAlphaTesting()) {
  53094. defines.push("#define ALPHATEST");
  53095. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53096. attribs.push(BABYLON.VertexBuffer.UVKind);
  53097. defines.push("#define UV1");
  53098. }
  53099. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53100. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53101. defines.push("#define UV2");
  53102. }
  53103. }
  53104. // Buffers
  53105. if (this._enablePosition) {
  53106. defines.push("#define POSITION");
  53107. }
  53108. // Bones
  53109. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53110. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53111. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53112. if (mesh.numBoneInfluencers > 4) {
  53113. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53114. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53115. }
  53116. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53117. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53118. }
  53119. else {
  53120. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53121. }
  53122. // Instances
  53123. if (useInstances) {
  53124. defines.push("#define INSTANCES");
  53125. attribs.push("world0");
  53126. attribs.push("world1");
  53127. attribs.push("world2");
  53128. attribs.push("world3");
  53129. }
  53130. // Get correct effect
  53131. var join = defines.join("\n");
  53132. if (this._cachedDefines !== join) {
  53133. this._cachedDefines = join;
  53134. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  53135. }
  53136. return this._effect.isReady();
  53137. };
  53138. GeometryBufferRenderer.prototype.getGBuffer = function () {
  53139. return this._multiRenderTarget;
  53140. };
  53141. // Methods
  53142. GeometryBufferRenderer.prototype.dispose = function () {
  53143. this.getGBuffer().dispose();
  53144. };
  53145. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  53146. var _this = this;
  53147. var engine = this._scene.getEngine();
  53148. var count = this._enablePosition ? 3 : 2;
  53149. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  53150. if (!this.isSupported) {
  53151. return null;
  53152. }
  53153. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53154. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53155. this._multiRenderTarget.refreshRate = 1;
  53156. this._multiRenderTarget.renderParticles = false;
  53157. this._multiRenderTarget.renderList = null;
  53158. // set default depth value to 1.0 (far away)
  53159. this._multiRenderTarget.onClearObservable.add(function (engine) {
  53160. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  53161. });
  53162. // Custom render function
  53163. var renderSubMesh = function (subMesh) {
  53164. var mesh = subMesh.getRenderingMesh();
  53165. var scene = _this._scene;
  53166. var engine = scene.getEngine();
  53167. // Culling
  53168. engine.setState(subMesh.getMaterial().backFaceCulling);
  53169. // Managing instances
  53170. var batch = mesh._getInstancesRenderList(subMesh._id);
  53171. if (batch.mustReturn) {
  53172. return;
  53173. }
  53174. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53175. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53176. engine.enableEffect(_this._effect);
  53177. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53178. var material = subMesh.getMaterial();
  53179. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53180. _this._effect.setMatrix("view", scene.getViewMatrix());
  53181. // Alpha test
  53182. if (material && material.needAlphaTesting()) {
  53183. var alphaTexture = material.getAlphaTestTexture();
  53184. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53185. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53186. }
  53187. // Bones
  53188. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53189. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53190. }
  53191. // Draw
  53192. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53193. }
  53194. };
  53195. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53196. var index;
  53197. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53198. renderSubMesh(opaqueSubMeshes.data[index]);
  53199. }
  53200. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53201. renderSubMesh(alphaTestSubMeshes.data[index]);
  53202. }
  53203. };
  53204. };
  53205. return GeometryBufferRenderer;
  53206. }());
  53207. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  53208. })(BABYLON || (BABYLON = {}));
  53209. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  53210. var BABYLON;
  53211. (function (BABYLON) {
  53212. var RefractionPostProcess = (function (_super) {
  53213. __extends(RefractionPostProcess, _super);
  53214. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  53215. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  53216. _this.color = color;
  53217. _this.depth = depth;
  53218. _this.colorLevel = colorLevel;
  53219. _this.onActivateObservable.add(function (cam) {
  53220. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  53221. });
  53222. _this.onApplyObservable.add(function (effect) {
  53223. effect.setColor3("baseColor", _this.color);
  53224. effect.setFloat("depth", _this.depth);
  53225. effect.setFloat("colorLevel", _this.colorLevel);
  53226. effect.setTexture("refractionSampler", _this._refRexture);
  53227. });
  53228. return _this;
  53229. }
  53230. // Methods
  53231. RefractionPostProcess.prototype.dispose = function (camera) {
  53232. if (this._refRexture) {
  53233. this._refRexture.dispose();
  53234. }
  53235. _super.prototype.dispose.call(this, camera);
  53236. };
  53237. return RefractionPostProcess;
  53238. }(BABYLON.PostProcess));
  53239. BABYLON.RefractionPostProcess = RefractionPostProcess;
  53240. })(BABYLON || (BABYLON = {}));
  53241. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  53242. var BABYLON;
  53243. (function (BABYLON) {
  53244. var BlackAndWhitePostProcess = (function (_super) {
  53245. __extends(BlackAndWhitePostProcess, _super);
  53246. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  53247. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  53248. _this.degree = 1;
  53249. _this.onApplyObservable.add(function (effect) {
  53250. effect.setFloat("degree", _this.degree);
  53251. });
  53252. return _this;
  53253. }
  53254. return BlackAndWhitePostProcess;
  53255. }(BABYLON.PostProcess));
  53256. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  53257. })(BABYLON || (BABYLON = {}));
  53258. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  53259. var BABYLON;
  53260. (function (BABYLON) {
  53261. var ConvolutionPostProcess = (function (_super) {
  53262. __extends(ConvolutionPostProcess, _super);
  53263. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  53264. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  53265. _this.kernel = kernel;
  53266. _this.onApply = function (effect) {
  53267. effect.setFloat2("screenSize", _this.width, _this.height);
  53268. effect.setArray("kernel", _this.kernel);
  53269. };
  53270. return _this;
  53271. }
  53272. return ConvolutionPostProcess;
  53273. }(BABYLON.PostProcess));
  53274. // Statics
  53275. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  53276. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  53277. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  53278. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  53279. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  53280. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  53281. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  53282. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  53283. })(BABYLON || (BABYLON = {}));
  53284. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  53285. var BABYLON;
  53286. (function (BABYLON) {
  53287. var FilterPostProcess = (function (_super) {
  53288. __extends(FilterPostProcess, _super);
  53289. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  53290. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  53291. _this.kernelMatrix = kernelMatrix;
  53292. _this.onApply = function (effect) {
  53293. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  53294. };
  53295. return _this;
  53296. }
  53297. return FilterPostProcess;
  53298. }(BABYLON.PostProcess));
  53299. BABYLON.FilterPostProcess = FilterPostProcess;
  53300. })(BABYLON || (BABYLON = {}));
  53301. //# sourceMappingURL=babylon.filterPostProcess.js.map
  53302. var BABYLON;
  53303. (function (BABYLON) {
  53304. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53305. var VolumetricLightScatteringPostProcess = (function (_super) {
  53306. __extends(VolumetricLightScatteringPostProcess, _super);
  53307. /**
  53308. * @constructor
  53309. * @param {string} name - The post-process name
  53310. * @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)
  53311. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53312. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53313. * @param {number} samples - The post-process quality, default 100
  53314. * @param {number} samplingMode - The post-process filtering mode
  53315. * @param {BABYLON.Engine} engine - The babylon engine
  53316. * @param {boolean} reusable - If the post-process is reusable
  53317. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53318. */
  53319. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53320. if (samples === void 0) { samples = 100; }
  53321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53322. 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;
  53323. _this._screenCoordinates = BABYLON.Vector2.Zero();
  53324. /**
  53325. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53326. * @type {Vector3}
  53327. */
  53328. _this.customMeshPosition = BABYLON.Vector3.Zero();
  53329. /**
  53330. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53331. * @type {boolean}
  53332. */
  53333. _this.useCustomMeshPosition = false;
  53334. /**
  53335. * If the post-process should inverse the light scattering direction
  53336. * @type {boolean}
  53337. */
  53338. _this.invert = true;
  53339. /**
  53340. * Array containing the excluded meshes not rendered in the internal pass
  53341. */
  53342. _this.excludedMeshes = new Array();
  53343. /**
  53344. * Controls the overall intensity of the post-process
  53345. * @type {number}
  53346. */
  53347. _this.exposure = 0.3;
  53348. /**
  53349. * Dissipates each sample's contribution in range [0, 1]
  53350. * @type {number}
  53351. */
  53352. _this.decay = 0.96815;
  53353. /**
  53354. * Controls the overall intensity of each sample
  53355. * @type {number}
  53356. */
  53357. _this.weight = 0.58767;
  53358. /**
  53359. * Controls the density of each sample
  53360. * @type {number}
  53361. */
  53362. _this.density = 0.926;
  53363. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53364. var engine = scene.getEngine();
  53365. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53366. // Configure mesh
  53367. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53368. // Configure
  53369. _this._createPass(scene, ratio.passRatio || ratio);
  53370. _this.onActivate = function (camera) {
  53371. if (!_this.isSupported) {
  53372. _this.dispose(camera);
  53373. }
  53374. _this.onActivate = null;
  53375. };
  53376. _this.onApplyObservable.add(function (effect) {
  53377. _this._updateMeshScreenCoordinates(scene);
  53378. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53379. effect.setFloat("exposure", _this.exposure);
  53380. effect.setFloat("decay", _this.decay);
  53381. effect.setFloat("weight", _this.weight);
  53382. effect.setFloat("density", _this.density);
  53383. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53384. });
  53385. return _this;
  53386. }
  53387. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53388. get: function () {
  53389. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53390. return false;
  53391. },
  53392. set: function (useDiffuseColor) {
  53393. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53394. },
  53395. enumerable: true,
  53396. configurable: true
  53397. });
  53398. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  53399. return "VolumetricLightScatteringPostProcess";
  53400. };
  53401. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53402. var mesh = subMesh.getMesh();
  53403. // Render this.mesh as default
  53404. if (mesh === this.mesh) {
  53405. return mesh.material.isReady(mesh);
  53406. }
  53407. var defines = [];
  53408. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53409. var material = subMesh.getMaterial();
  53410. var needUV = false;
  53411. // Alpha test
  53412. if (material) {
  53413. if (material.needAlphaTesting()) {
  53414. defines.push("#define ALPHATEST");
  53415. }
  53416. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53417. attribs.push(BABYLON.VertexBuffer.UVKind);
  53418. defines.push("#define UV1");
  53419. }
  53420. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53421. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53422. defines.push("#define UV2");
  53423. }
  53424. }
  53425. // Bones
  53426. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53427. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53428. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53429. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53430. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53431. }
  53432. else {
  53433. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53434. }
  53435. // Instances
  53436. if (useInstances) {
  53437. defines.push("#define INSTANCES");
  53438. attribs.push("world0");
  53439. attribs.push("world1");
  53440. attribs.push("world2");
  53441. attribs.push("world3");
  53442. }
  53443. // Get correct effect
  53444. var join = defines.join("\n");
  53445. if (this._cachedDefines !== join) {
  53446. this._cachedDefines = join;
  53447. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53448. }
  53449. return this._volumetricLightScatteringPass.isReady();
  53450. };
  53451. /**
  53452. * Sets the new light position for light scattering effect
  53453. * @param {BABYLON.Vector3} The new custom light position
  53454. */
  53455. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53456. this.customMeshPosition = position;
  53457. };
  53458. /**
  53459. * Returns the light position for light scattering effect
  53460. * @return {BABYLON.Vector3} The custom light position
  53461. */
  53462. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53463. return this.customMeshPosition;
  53464. };
  53465. /**
  53466. * Disposes the internal assets and detaches the post-process from the camera
  53467. */
  53468. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53469. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53470. if (rttIndex !== -1) {
  53471. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53472. }
  53473. this._volumetricLightScatteringRTT.dispose();
  53474. _super.prototype.dispose.call(this, camera);
  53475. };
  53476. /**
  53477. * Returns the render target texture used by the post-process
  53478. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53479. */
  53480. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53481. return this._volumetricLightScatteringRTT;
  53482. };
  53483. // Private methods
  53484. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53485. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53486. return true;
  53487. }
  53488. return false;
  53489. };
  53490. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53491. var _this = this;
  53492. var engine = scene.getEngine();
  53493. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53494. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53495. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53496. this._volumetricLightScatteringRTT.renderList = null;
  53497. this._volumetricLightScatteringRTT.renderParticles = false;
  53498. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53499. // Custom render function for submeshes
  53500. var renderSubMesh = function (subMesh) {
  53501. var mesh = subMesh.getRenderingMesh();
  53502. if (_this._meshExcluded(mesh)) {
  53503. return;
  53504. }
  53505. var scene = mesh.getScene();
  53506. var engine = scene.getEngine();
  53507. // Culling
  53508. engine.setState(subMesh.getMaterial().backFaceCulling);
  53509. // Managing instances
  53510. var batch = mesh._getInstancesRenderList(subMesh._id);
  53511. if (batch.mustReturn) {
  53512. return;
  53513. }
  53514. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53515. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53516. var effect = _this._volumetricLightScatteringPass;
  53517. if (mesh === _this.mesh) {
  53518. if (subMesh.effect) {
  53519. effect = subMesh.effect;
  53520. }
  53521. else {
  53522. effect = subMesh.getMaterial().getEffect();
  53523. }
  53524. }
  53525. engine.enableEffect(effect);
  53526. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53527. if (mesh === _this.mesh) {
  53528. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53529. }
  53530. else {
  53531. var material = subMesh.getMaterial();
  53532. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53533. // Alpha test
  53534. if (material && material.needAlphaTesting()) {
  53535. var alphaTexture = material.getAlphaTestTexture();
  53536. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53537. if (alphaTexture) {
  53538. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53539. }
  53540. }
  53541. // Bones
  53542. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53543. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53544. }
  53545. }
  53546. // Draw
  53547. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  53548. }
  53549. };
  53550. // Render target texture callbacks
  53551. var savedSceneClearColor;
  53552. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  53553. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  53554. savedSceneClearColor = scene.clearColor;
  53555. scene.clearColor = sceneClearColor;
  53556. });
  53557. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  53558. scene.clearColor = savedSceneClearColor;
  53559. });
  53560. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  53561. var engine = scene.getEngine();
  53562. var index;
  53563. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53564. renderSubMesh(opaqueSubMeshes.data[index]);
  53565. }
  53566. engine.setAlphaTesting(true);
  53567. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53568. renderSubMesh(alphaTestSubMeshes.data[index]);
  53569. }
  53570. engine.setAlphaTesting(false);
  53571. if (transparentSubMeshes.length) {
  53572. // Sort sub meshes
  53573. for (index = 0; index < transparentSubMeshes.length; index++) {
  53574. var submesh = transparentSubMeshes.data[index];
  53575. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  53576. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  53577. }
  53578. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53579. sortedArray.sort(function (a, b) {
  53580. // Alpha index first
  53581. if (a._alphaIndex > b._alphaIndex) {
  53582. return 1;
  53583. }
  53584. if (a._alphaIndex < b._alphaIndex) {
  53585. return -1;
  53586. }
  53587. // Then distance to camera
  53588. if (a._distanceToCamera < b._distanceToCamera) {
  53589. return 1;
  53590. }
  53591. if (a._distanceToCamera > b._distanceToCamera) {
  53592. return -1;
  53593. }
  53594. return 0;
  53595. });
  53596. // Render sub meshes
  53597. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53598. for (index = 0; index < sortedArray.length; index++) {
  53599. renderSubMesh(sortedArray[index]);
  53600. }
  53601. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53602. }
  53603. };
  53604. };
  53605. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  53606. var transform = scene.getTransformMatrix();
  53607. var meshPosition;
  53608. if (this.useCustomMeshPosition) {
  53609. meshPosition = this.customMeshPosition;
  53610. }
  53611. else if (this.attachedNode) {
  53612. meshPosition = this.attachedNode.position;
  53613. }
  53614. else {
  53615. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  53616. }
  53617. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  53618. this._screenCoordinates.x = pos.x / this._viewPort.width;
  53619. this._screenCoordinates.y = pos.y / this._viewPort.height;
  53620. if (this.invert)
  53621. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  53622. };
  53623. // Static methods
  53624. /**
  53625. * Creates a default mesh for the Volumeric Light Scattering post-process
  53626. * @param {string} The mesh name
  53627. * @param {BABYLON.Scene} The scene where to create the mesh
  53628. * @return {BABYLON.Mesh} the default mesh
  53629. */
  53630. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  53631. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  53632. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  53633. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  53634. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  53635. mesh.material = material;
  53636. return mesh;
  53637. };
  53638. return VolumetricLightScatteringPostProcess;
  53639. }(BABYLON.PostProcess));
  53640. __decorate([
  53641. BABYLON.serializeAsVector3()
  53642. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  53643. __decorate([
  53644. BABYLON.serialize()
  53645. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  53646. __decorate([
  53647. BABYLON.serialize()
  53648. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  53649. __decorate([
  53650. BABYLON.serializeAsMeshReference()
  53651. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  53652. __decorate([
  53653. BABYLON.serialize()
  53654. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  53655. __decorate([
  53656. BABYLON.serialize()
  53657. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  53658. __decorate([
  53659. BABYLON.serialize()
  53660. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  53661. __decorate([
  53662. BABYLON.serialize()
  53663. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  53664. __decorate([
  53665. BABYLON.serialize()
  53666. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  53667. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  53668. })(BABYLON || (BABYLON = {}));
  53669. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  53670. //
  53671. // This post-process allows the modification of rendered colors by using
  53672. // a 'look-up table' (LUT). This effect is also called Color Grading.
  53673. //
  53674. // The object needs to be provided an url to a texture containing the color
  53675. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  53676. // Use an image editing software to tweak the LUT to match your needs.
  53677. //
  53678. // For an example of a color LUT, see here:
  53679. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  53680. // For explanations on color grading, see here:
  53681. // http://udn.epicgames.com/Three/ColorGrading.html
  53682. //
  53683. var BABYLON;
  53684. (function (BABYLON) {
  53685. var ColorCorrectionPostProcess = (function (_super) {
  53686. __extends(ColorCorrectionPostProcess, _super);
  53687. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  53688. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  53689. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53690. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  53691. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53692. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53693. _this.onApply = function (effect) {
  53694. effect.setTexture("colorTable", _this._colorTableTexture);
  53695. };
  53696. return _this;
  53697. }
  53698. return ColorCorrectionPostProcess;
  53699. }(BABYLON.PostProcess));
  53700. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  53701. })(BABYLON || (BABYLON = {}));
  53702. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  53703. var BABYLON;
  53704. (function (BABYLON) {
  53705. var TonemappingOperator;
  53706. (function (TonemappingOperator) {
  53707. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53708. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53709. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53710. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53711. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53712. ;
  53713. var TonemapPostProcess = (function (_super) {
  53714. __extends(TonemapPostProcess, _super);
  53715. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53717. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53718. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  53719. _this._operator = _operator;
  53720. _this.exposureAdjustment = exposureAdjustment;
  53721. var defines = "#define ";
  53722. if (_this._operator === TonemappingOperator.Hable)
  53723. defines += "HABLE_TONEMAPPING";
  53724. else if (_this._operator === TonemappingOperator.Reinhard)
  53725. defines += "REINHARD_TONEMAPPING";
  53726. else if (_this._operator === TonemappingOperator.HejiDawson)
  53727. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53728. else if (_this._operator === TonemappingOperator.Photographic)
  53729. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53730. //sadly a second call to create the effect.
  53731. _this.updateEffect(defines);
  53732. _this.onApply = function (effect) {
  53733. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53734. };
  53735. return _this;
  53736. }
  53737. return TonemapPostProcess;
  53738. }(BABYLON.PostProcess));
  53739. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53740. })(BABYLON || (BABYLON = {}));
  53741. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  53742. var BABYLON;
  53743. (function (BABYLON) {
  53744. var DisplayPassPostProcess = (function (_super) {
  53745. __extends(DisplayPassPostProcess, _super);
  53746. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  53747. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  53748. }
  53749. return DisplayPassPostProcess;
  53750. }(BABYLON.PostProcess));
  53751. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  53752. })(BABYLON || (BABYLON = {}));
  53753. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  53754. var BABYLON;
  53755. (function (BABYLON) {
  53756. var HighlightsPostProcess = (function (_super) {
  53757. __extends(HighlightsPostProcess, _super);
  53758. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53759. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53760. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  53761. }
  53762. return HighlightsPostProcess;
  53763. }(BABYLON.PostProcess));
  53764. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  53765. })(BABYLON || (BABYLON = {}));
  53766. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  53767. var BABYLON;
  53768. (function (BABYLON) {
  53769. var ImageProcessingPostProcess = (function (_super) {
  53770. __extends(ImageProcessingPostProcess, _super);
  53771. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53772. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53773. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  53774. _this._fromLinearSpace = true;
  53775. /**
  53776. * Defines cache preventing GC.
  53777. */
  53778. _this._defines = {
  53779. IMAGEPROCESSING: false,
  53780. VIGNETTE: false,
  53781. VIGNETTEBLENDMODEMULTIPLY: false,
  53782. VIGNETTEBLENDMODEOPAQUE: false,
  53783. TONEMAPPING: false,
  53784. CONTRAST: false,
  53785. COLORCURVES: false,
  53786. COLORGRADING: false,
  53787. FROMLINEARSPACE: false,
  53788. SAMPLER3DGREENDEPTH: false,
  53789. SAMPLER3DBGRMAP: false,
  53790. IMAGEPROCESSINGPOSTPROCESS: false,
  53791. EXPOSURE: false,
  53792. };
  53793. // Setup the default processing configuration to the scene.
  53794. _this._attachImageProcessingConfiguration(null, true);
  53795. _this.imageProcessingConfiguration.applyByPostProcess = true;
  53796. _this.onApply = function (effect) {
  53797. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  53798. };
  53799. return _this;
  53800. }
  53801. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  53802. /**
  53803. * Gets the image processing configuration used either in this material.
  53804. */
  53805. get: function () {
  53806. return this._imageProcessingConfiguration;
  53807. },
  53808. /**
  53809. * Sets the Default image processing configuration used either in the this material.
  53810. *
  53811. * If sets to null, the scene one is in use.
  53812. */
  53813. set: function (value) {
  53814. this._attachImageProcessingConfiguration(value);
  53815. },
  53816. enumerable: true,
  53817. configurable: true
  53818. });
  53819. /**
  53820. * Attaches a new image processing configuration to the PBR Material.
  53821. * @param configuration
  53822. */
  53823. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  53824. var _this = this;
  53825. if (doNotBuild === void 0) { doNotBuild = false; }
  53826. if (configuration === this._imageProcessingConfiguration) {
  53827. return;
  53828. }
  53829. // Detaches observer.
  53830. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  53831. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  53832. }
  53833. // Pick the scene configuration if needed.
  53834. if (!configuration) {
  53835. var camera = this.getCamera();
  53836. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  53837. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  53838. }
  53839. else {
  53840. this._imageProcessingConfiguration = configuration;
  53841. }
  53842. // Attaches observer.
  53843. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  53844. _this._updateParameters();
  53845. });
  53846. // Ensure the effect will be rebuilt.
  53847. if (!doNotBuild) {
  53848. this._updateParameters();
  53849. }
  53850. };
  53851. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  53852. /**
  53853. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  53854. */
  53855. get: function () {
  53856. return this.imageProcessingConfiguration.colorCurves;
  53857. },
  53858. /**
  53859. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  53860. */
  53861. set: function (value) {
  53862. this.imageProcessingConfiguration.colorCurves = value;
  53863. },
  53864. enumerable: true,
  53865. configurable: true
  53866. });
  53867. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  53868. /**
  53869. * Gets wether the color curves effect is enabled.
  53870. */
  53871. get: function () {
  53872. return this.imageProcessingConfiguration.colorCurvesEnabled;
  53873. },
  53874. /**
  53875. * Sets wether the color curves effect is enabled.
  53876. */
  53877. set: function (value) {
  53878. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  53879. },
  53880. enumerable: true,
  53881. configurable: true
  53882. });
  53883. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  53884. /**
  53885. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  53886. */
  53887. get: function () {
  53888. return this.imageProcessingConfiguration.colorGradingTexture;
  53889. },
  53890. /**
  53891. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  53892. */
  53893. set: function (value) {
  53894. this.imageProcessingConfiguration.colorGradingTexture = value;
  53895. },
  53896. enumerable: true,
  53897. configurable: true
  53898. });
  53899. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  53900. /**
  53901. * Gets wether the color grading effect is enabled.
  53902. */
  53903. get: function () {
  53904. return this.imageProcessingConfiguration.colorGradingEnabled;
  53905. },
  53906. /**
  53907. * Gets wether the color grading effect is enabled.
  53908. */
  53909. set: function (value) {
  53910. this.imageProcessingConfiguration.colorGradingEnabled = value;
  53911. },
  53912. enumerable: true,
  53913. configurable: true
  53914. });
  53915. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  53916. /**
  53917. * Gets exposure used in the effect.
  53918. */
  53919. get: function () {
  53920. return this.imageProcessingConfiguration.exposure;
  53921. },
  53922. /**
  53923. * Sets exposure used in the effect.
  53924. */
  53925. set: function (value) {
  53926. this.imageProcessingConfiguration.exposure = value;
  53927. },
  53928. enumerable: true,
  53929. configurable: true
  53930. });
  53931. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  53932. /**
  53933. * Gets wether tonemapping is enabled or not.
  53934. */
  53935. get: function () {
  53936. return this._imageProcessingConfiguration.toneMappingEnabled;
  53937. },
  53938. /**
  53939. * Sets wether tonemapping is enabled or not
  53940. */
  53941. set: function (value) {
  53942. this._imageProcessingConfiguration.toneMappingEnabled = value;
  53943. },
  53944. enumerable: true,
  53945. configurable: true
  53946. });
  53947. ;
  53948. ;
  53949. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  53950. /**
  53951. * Gets contrast used in the effect.
  53952. */
  53953. get: function () {
  53954. return this.imageProcessingConfiguration.contrast;
  53955. },
  53956. /**
  53957. * Sets contrast used in the effect.
  53958. */
  53959. set: function (value) {
  53960. this.imageProcessingConfiguration.contrast = value;
  53961. },
  53962. enumerable: true,
  53963. configurable: true
  53964. });
  53965. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  53966. /**
  53967. * Gets Vignette stretch size.
  53968. */
  53969. get: function () {
  53970. return this.imageProcessingConfiguration.vignetteStretch;
  53971. },
  53972. /**
  53973. * Sets Vignette stretch size.
  53974. */
  53975. set: function (value) {
  53976. this.imageProcessingConfiguration.vignetteStretch = value;
  53977. },
  53978. enumerable: true,
  53979. configurable: true
  53980. });
  53981. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  53982. /**
  53983. * Gets Vignette centre X Offset.
  53984. */
  53985. get: function () {
  53986. return this.imageProcessingConfiguration.vignetteCentreX;
  53987. },
  53988. /**
  53989. * Sets Vignette centre X Offset.
  53990. */
  53991. set: function (value) {
  53992. this.imageProcessingConfiguration.vignetteCentreX = value;
  53993. },
  53994. enumerable: true,
  53995. configurable: true
  53996. });
  53997. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  53998. /**
  53999. * Gets Vignette centre Y Offset.
  54000. */
  54001. get: function () {
  54002. return this.imageProcessingConfiguration.vignetteCentreY;
  54003. },
  54004. /**
  54005. * Sets Vignette centre Y Offset.
  54006. */
  54007. set: function (value) {
  54008. this.imageProcessingConfiguration.vignetteCentreY = value;
  54009. },
  54010. enumerable: true,
  54011. configurable: true
  54012. });
  54013. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  54014. /**
  54015. * Gets Vignette weight or intensity of the vignette effect.
  54016. */
  54017. get: function () {
  54018. return this.imageProcessingConfiguration.vignetteWeight;
  54019. },
  54020. /**
  54021. * Sets Vignette weight or intensity of the vignette effect.
  54022. */
  54023. set: function (value) {
  54024. this.imageProcessingConfiguration.vignetteWeight = value;
  54025. },
  54026. enumerable: true,
  54027. configurable: true
  54028. });
  54029. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  54030. /**
  54031. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54032. * if vignetteEnabled is set to true.
  54033. */
  54034. get: function () {
  54035. return this.imageProcessingConfiguration.vignetteColor;
  54036. },
  54037. /**
  54038. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54039. * if vignetteEnabled is set to true.
  54040. */
  54041. set: function (value) {
  54042. this.imageProcessingConfiguration.vignetteColor = value;
  54043. },
  54044. enumerable: true,
  54045. configurable: true
  54046. });
  54047. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  54048. /**
  54049. * Gets Camera field of view used by the Vignette effect.
  54050. */
  54051. get: function () {
  54052. return this.imageProcessingConfiguration.vignetteCameraFov;
  54053. },
  54054. /**
  54055. * Sets Camera field of view used by the Vignette effect.
  54056. */
  54057. set: function (value) {
  54058. this.imageProcessingConfiguration.vignetteCameraFov = value;
  54059. },
  54060. enumerable: true,
  54061. configurable: true
  54062. });
  54063. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  54064. /**
  54065. * Gets the vignette blend mode allowing different kind of effect.
  54066. */
  54067. get: function () {
  54068. return this.imageProcessingConfiguration.vignetteBlendMode;
  54069. },
  54070. /**
  54071. * Sets the vignette blend mode allowing different kind of effect.
  54072. */
  54073. set: function (value) {
  54074. this.imageProcessingConfiguration.vignetteBlendMode = value;
  54075. },
  54076. enumerable: true,
  54077. configurable: true
  54078. });
  54079. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  54080. /**
  54081. * Gets wether the vignette effect is enabled.
  54082. */
  54083. get: function () {
  54084. return this.imageProcessingConfiguration.vignetteEnabled;
  54085. },
  54086. /**
  54087. * Sets wether the vignette effect is enabled.
  54088. */
  54089. set: function (value) {
  54090. this.imageProcessingConfiguration.vignetteEnabled = value;
  54091. },
  54092. enumerable: true,
  54093. configurable: true
  54094. });
  54095. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  54096. /**
  54097. * Gets wether the input of the processing is in Gamma or Linear Space.
  54098. */
  54099. get: function () {
  54100. return this._fromLinearSpace;
  54101. },
  54102. /**
  54103. * Sets wether the input of the processing is in Gamma or Linear Space.
  54104. */
  54105. set: function (value) {
  54106. if (this._fromLinearSpace === value) {
  54107. return;
  54108. }
  54109. this._fromLinearSpace = value;
  54110. this._updateParameters();
  54111. },
  54112. enumerable: true,
  54113. configurable: true
  54114. });
  54115. ImageProcessingPostProcess.prototype.getClassName = function () {
  54116. return "ImageProcessingPostProcess";
  54117. };
  54118. ImageProcessingPostProcess.prototype._updateParameters = function () {
  54119. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  54120. this.imageProcessingConfiguration.prepareDefines(this._defines);
  54121. var defines = "";
  54122. for (var define in this._defines) {
  54123. if (this._defines[define]) {
  54124. defines += "#define " + define + ";\r\n";
  54125. }
  54126. }
  54127. var samplers = ["textureSampler"];
  54128. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  54129. var uniforms = ["scale"];
  54130. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  54131. this.updateEffect(defines, uniforms, samplers);
  54132. };
  54133. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  54134. _super.prototype.dispose.call(this, camera);
  54135. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  54136. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  54137. }
  54138. this.imageProcessingConfiguration.applyByPostProcess = false;
  54139. };
  54140. return ImageProcessingPostProcess;
  54141. }(BABYLON.PostProcess));
  54142. __decorate([
  54143. BABYLON.serialize()
  54144. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  54145. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  54146. })(BABYLON || (BABYLON = {}));
  54147. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  54148. var BABYLON;
  54149. (function (BABYLON) {
  54150. var BlurPostProcess = (function (_super) {
  54151. __extends(BlurPostProcess, _super);
  54152. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  54153. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54154. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54155. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  54156. _this.direction = direction;
  54157. _this._packedFloat = false;
  54158. _this.onApplyObservable.add(function (effect) {
  54159. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  54160. });
  54161. _this.kernel = kernel;
  54162. return _this;
  54163. }
  54164. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  54165. /**
  54166. * Gets the length in pixels of the blur sample region
  54167. */
  54168. get: function () {
  54169. return this._idealKernel;
  54170. },
  54171. /**
  54172. * Sets the length in pixels of the blur sample region
  54173. */
  54174. set: function (v) {
  54175. if (this._idealKernel === v) {
  54176. return;
  54177. }
  54178. v = Math.max(v, 1);
  54179. this._idealKernel = v;
  54180. this._kernel = this._nearestBestKernel(v);
  54181. this._updateParameters();
  54182. },
  54183. enumerable: true,
  54184. configurable: true
  54185. });
  54186. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  54187. /**
  54188. * Gets wether or not the blur is unpacking/repacking floats
  54189. */
  54190. get: function () {
  54191. return this._packedFloat;
  54192. },
  54193. /**
  54194. * Sets wether or not the blur needs to unpack/repack floats
  54195. */
  54196. set: function (v) {
  54197. if (this._packedFloat === v) {
  54198. return;
  54199. }
  54200. this._packedFloat = v;
  54201. this._updateParameters();
  54202. },
  54203. enumerable: true,
  54204. configurable: true
  54205. });
  54206. BlurPostProcess.prototype._updateParameters = function () {
  54207. // Generate sampling offsets and weights
  54208. var N = this._kernel;
  54209. var centerIndex = (N - 1) / 2;
  54210. // Generate Gaussian sampling weights over kernel
  54211. var offsets = [];
  54212. var weights = [];
  54213. var totalWeight = 0;
  54214. for (var i = 0; i < N; i++) {
  54215. var u = i / (N - 1);
  54216. var w = this._gaussianWeight(u * 2.0 - 1);
  54217. offsets[i] = (i - centerIndex);
  54218. weights[i] = w;
  54219. totalWeight += w;
  54220. }
  54221. // Normalize weights
  54222. for (var i = 0; i < weights.length; i++) {
  54223. weights[i] /= totalWeight;
  54224. }
  54225. // Optimize: combine samples to take advantage of hardware linear sampling
  54226. // Walk from left to center, combining pairs (symmetrically)
  54227. var linearSamplingWeights = [];
  54228. var linearSamplingOffsets = [];
  54229. var linearSamplingMap = [];
  54230. for (var i = 0; i <= centerIndex; i += 2) {
  54231. var j = Math.min(i + 1, Math.floor(centerIndex));
  54232. var singleCenterSample = i === j;
  54233. if (singleCenterSample) {
  54234. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  54235. }
  54236. else {
  54237. var sharedCell = j === centerIndex;
  54238. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  54239. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  54240. if (offsetLinear === 0) {
  54241. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  54242. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  54243. }
  54244. else {
  54245. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  54246. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  54247. }
  54248. }
  54249. }
  54250. for (var i = 0; i < linearSamplingMap.length; i++) {
  54251. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  54252. linearSamplingWeights[i] = linearSamplingMap[i].w;
  54253. }
  54254. // Replace with optimized
  54255. offsets = linearSamplingOffsets;
  54256. weights = linearSamplingWeights;
  54257. // Generate shaders
  54258. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  54259. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  54260. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  54261. var defines = "";
  54262. for (var i = 0; i < varyingCount; i++) {
  54263. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  54264. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  54265. }
  54266. var depCount = 0;
  54267. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  54268. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  54269. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  54270. depCount++;
  54271. }
  54272. if (this.packedFloat) {
  54273. defines += "#define PACKEDFLOAT 1";
  54274. }
  54275. this.updateEffect(defines, null, null, {
  54276. varyingCount: varyingCount,
  54277. depCount: depCount
  54278. });
  54279. };
  54280. /**
  54281. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  54282. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  54283. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  54284. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  54285. * The gaps between physical kernels are compensated for in the weighting of the samples
  54286. * @param idealKernel Ideal blur kernel.
  54287. * @return Nearest best kernel.
  54288. */
  54289. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  54290. var v = Math.round(idealKernel);
  54291. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  54292. var k = _a[_i];
  54293. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  54294. return Math.max(k, 3);
  54295. }
  54296. }
  54297. return Math.max(v, 3);
  54298. };
  54299. /**
  54300. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  54301. * @param x The point on the Gaussian distribution to sample.
  54302. * @return the value of the Gaussian function at x.
  54303. */
  54304. BlurPostProcess.prototype._gaussianWeight = function (x) {
  54305. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  54306. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  54307. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  54308. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  54309. // truncated at around 1.3% of peak strength.
  54310. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  54311. var sigma = (1 / 3);
  54312. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  54313. var exponent = -((x * x) / (2.0 * sigma * sigma));
  54314. var weight = (1.0 / denominator) * Math.exp(exponent);
  54315. return weight;
  54316. };
  54317. /**
  54318. * Generates a string that can be used as a floating point number in GLSL.
  54319. * @param x Value to print.
  54320. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  54321. * @return GLSL float string.
  54322. */
  54323. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  54324. if (decimalFigures === void 0) { decimalFigures = 8; }
  54325. return x.toFixed(decimalFigures).replace(/0+$/, '');
  54326. };
  54327. return BlurPostProcess;
  54328. }(BABYLON.PostProcess));
  54329. BABYLON.BlurPostProcess = BlurPostProcess;
  54330. })(BABYLON || (BABYLON = {}));
  54331. //# sourceMappingURL=babylon.blurPostProcess.js.map
  54332. /// <reference path="..\babylon.node.ts" />
  54333. var BABYLON;
  54334. (function (BABYLON) {
  54335. var Bone = (function (_super) {
  54336. __extends(Bone, _super);
  54337. function Bone(name, skeleton, parentBone, matrix, restPose) {
  54338. if (parentBone === void 0) { parentBone = null; }
  54339. var _this = _super.call(this, name, skeleton.getScene()) || this;
  54340. _this.name = name;
  54341. _this.children = new Array();
  54342. _this.animations = new Array();
  54343. _this._worldTransform = new BABYLON.Matrix();
  54344. _this._absoluteTransform = new BABYLON.Matrix();
  54345. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  54346. _this._scaleMatrix = BABYLON.Matrix.Identity();
  54347. _this._scaleVector = BABYLON.Vector3.One();
  54348. _this._negateScaleChildren = BABYLON.Vector3.One();
  54349. _this._scalingDeterminant = 1;
  54350. _this._skeleton = skeleton;
  54351. _this._localMatrix = matrix ? matrix : BABYLON.Matrix.Identity();
  54352. _this._baseMatrix = _this._localMatrix.clone();
  54353. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  54354. skeleton.bones.push(_this);
  54355. _this.setParent(parentBone, false);
  54356. _this._updateDifferenceMatrix();
  54357. return _this;
  54358. }
  54359. Object.defineProperty(Bone.prototype, "_matrix", {
  54360. get: function () {
  54361. return this._localMatrix;
  54362. },
  54363. set: function (val) {
  54364. if (this._localMatrix) {
  54365. this._localMatrix.copyFrom(val);
  54366. }
  54367. else {
  54368. this._localMatrix = val;
  54369. }
  54370. },
  54371. enumerable: true,
  54372. configurable: true
  54373. });
  54374. // Members
  54375. Bone.prototype.getSkeleton = function () {
  54376. return this._skeleton;
  54377. };
  54378. Bone.prototype.getParent = function () {
  54379. return this._parent;
  54380. };
  54381. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  54382. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  54383. if (this._parent === parent) {
  54384. return;
  54385. }
  54386. if (this._parent) {
  54387. var index = this._parent.children.indexOf(this);
  54388. if (index !== -1) {
  54389. this._parent.children.splice(index);
  54390. }
  54391. }
  54392. this._parent = parent;
  54393. if (this._parent) {
  54394. this._parent.children.push(this);
  54395. }
  54396. if (updateDifferenceMatrix) {
  54397. this._updateDifferenceMatrix();
  54398. }
  54399. };
  54400. Bone.prototype.getLocalMatrix = function () {
  54401. return this._localMatrix;
  54402. };
  54403. Bone.prototype.getBaseMatrix = function () {
  54404. return this._baseMatrix;
  54405. };
  54406. Bone.prototype.getRestPose = function () {
  54407. return this._restPose;
  54408. };
  54409. Bone.prototype.returnToRest = function () {
  54410. this.updateMatrix(this._restPose.clone());
  54411. };
  54412. Bone.prototype.getWorldMatrix = function () {
  54413. return this._worldTransform;
  54414. };
  54415. Bone.prototype.getInvertedAbsoluteTransform = function () {
  54416. return this._invertedAbsoluteTransform;
  54417. };
  54418. Bone.prototype.getAbsoluteTransform = function () {
  54419. return this._absoluteTransform;
  54420. };
  54421. Object.defineProperty(Bone.prototype, "position", {
  54422. // Properties (matches AbstractMesh properties)
  54423. get: function () {
  54424. return this.getPosition();
  54425. },
  54426. set: function (newPosition) {
  54427. this.setPosition(newPosition);
  54428. },
  54429. enumerable: true,
  54430. configurable: true
  54431. });
  54432. Object.defineProperty(Bone.prototype, "rotation", {
  54433. get: function () {
  54434. return this.getRotation();
  54435. },
  54436. set: function (newRotation) {
  54437. this.setRotation(newRotation);
  54438. },
  54439. enumerable: true,
  54440. configurable: true
  54441. });
  54442. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  54443. get: function () {
  54444. return this.getRotationQuaternion();
  54445. },
  54446. set: function (newRotation) {
  54447. this.setRotationQuaternion(newRotation);
  54448. },
  54449. enumerable: true,
  54450. configurable: true
  54451. });
  54452. Object.defineProperty(Bone.prototype, "scaling", {
  54453. get: function () {
  54454. return this.getScale();
  54455. },
  54456. set: function (newScaling) {
  54457. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  54458. },
  54459. enumerable: true,
  54460. configurable: true
  54461. });
  54462. // Methods
  54463. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  54464. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  54465. this._baseMatrix = matrix.clone();
  54466. this._localMatrix = matrix.clone();
  54467. this._skeleton._markAsDirty();
  54468. if (updateDifferenceMatrix) {
  54469. this._updateDifferenceMatrix();
  54470. }
  54471. };
  54472. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  54473. if (!rootMatrix) {
  54474. rootMatrix = this._baseMatrix;
  54475. }
  54476. if (this._parent) {
  54477. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  54478. }
  54479. else {
  54480. this._absoluteTransform.copyFrom(rootMatrix);
  54481. }
  54482. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  54483. for (var index = 0; index < this.children.length; index++) {
  54484. this.children[index]._updateDifferenceMatrix();
  54485. }
  54486. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  54487. };
  54488. Bone.prototype.markAsDirty = function () {
  54489. this._currentRenderId++;
  54490. this._skeleton._markAsDirty();
  54491. };
  54492. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  54493. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  54494. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  54495. // all animation may be coming from a library skeleton, so may need to create animation
  54496. if (this.animations.length === 0) {
  54497. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  54498. this.animations[0].setKeys([]);
  54499. }
  54500. // get animation info / verify there is such a range from the source bone
  54501. var sourceRange = source.animations[0].getRange(rangeName);
  54502. if (!sourceRange) {
  54503. return false;
  54504. }
  54505. var from = sourceRange.from;
  54506. var to = sourceRange.to;
  54507. var sourceKeys = source.animations[0].getKeys();
  54508. // rescaling prep
  54509. var sourceBoneLength = source.length;
  54510. var sourceParent = source.getParent();
  54511. var parent = this.getParent();
  54512. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  54513. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  54514. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  54515. var destKeys = this.animations[0].getKeys();
  54516. // loop vars declaration
  54517. var orig;
  54518. var origTranslation;
  54519. var mat;
  54520. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  54521. orig = sourceKeys[key];
  54522. if (orig.frame >= from && orig.frame <= to) {
  54523. if (rescaleAsRequired) {
  54524. mat = orig.value.clone();
  54525. // scale based on parent ratio, when bone has parent
  54526. if (parentScalingReqd) {
  54527. origTranslation = mat.getTranslation();
  54528. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  54529. // scale based on skeleton dimension ratio when root bone, and value is passed
  54530. }
  54531. else if (dimensionsScalingReqd) {
  54532. origTranslation = mat.getTranslation();
  54533. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  54534. // use original when root bone, and no data for skelDimensionsRatio
  54535. }
  54536. else {
  54537. mat = orig.value;
  54538. }
  54539. }
  54540. else {
  54541. mat = orig.value;
  54542. }
  54543. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  54544. }
  54545. }
  54546. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  54547. return true;
  54548. };
  54549. /**
  54550. * Translate the bone in local or world space.
  54551. * @param vec The amount to translate the bone.
  54552. * @param space The space that the translation is in.
  54553. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54554. */
  54555. Bone.prototype.translate = function (vec, space, mesh) {
  54556. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54557. var lm = this.getLocalMatrix();
  54558. if (space == BABYLON.Space.LOCAL) {
  54559. lm.m[12] += vec.x;
  54560. lm.m[13] += vec.y;
  54561. lm.m[14] += vec.z;
  54562. }
  54563. else {
  54564. var wm;
  54565. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54566. if (mesh) {
  54567. wm = mesh.getWorldMatrix();
  54568. }
  54569. this._skeleton.computeAbsoluteTransforms();
  54570. var tmat = Bone._tmpMats[0];
  54571. var tvec = Bone._tmpVecs[0];
  54572. if (mesh) {
  54573. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54574. tmat.multiplyToRef(wm, tmat);
  54575. }
  54576. else {
  54577. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54578. }
  54579. tmat.m[12] = 0;
  54580. tmat.m[13] = 0;
  54581. tmat.m[14] = 0;
  54582. tmat.invert();
  54583. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  54584. lm.m[12] += tvec.x;
  54585. lm.m[13] += tvec.y;
  54586. lm.m[14] += tvec.z;
  54587. }
  54588. this.markAsDirty();
  54589. };
  54590. /**
  54591. * Set the postion of the bone in local or world space.
  54592. * @param position The position to set the bone.
  54593. * @param space The space that the position is in.
  54594. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54595. */
  54596. Bone.prototype.setPosition = function (position, space, mesh) {
  54597. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54598. var lm = this.getLocalMatrix();
  54599. if (space == BABYLON.Space.LOCAL) {
  54600. lm.m[12] = position.x;
  54601. lm.m[13] = position.y;
  54602. lm.m[14] = position.z;
  54603. }
  54604. else {
  54605. var wm;
  54606. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54607. if (mesh) {
  54608. wm = mesh.getWorldMatrix();
  54609. }
  54610. this._skeleton.computeAbsoluteTransforms();
  54611. var tmat = Bone._tmpMats[0];
  54612. var vec = Bone._tmpVecs[0];
  54613. if (mesh) {
  54614. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54615. tmat.multiplyToRef(wm, tmat);
  54616. }
  54617. else {
  54618. tmat.copyFrom(this._parent.getAbsoluteTransform());
  54619. }
  54620. tmat.invert();
  54621. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  54622. lm.m[12] = vec.x;
  54623. lm.m[13] = vec.y;
  54624. lm.m[14] = vec.z;
  54625. }
  54626. this.markAsDirty();
  54627. };
  54628. /**
  54629. * Set the absolute postion of the bone (world space).
  54630. * @param position The position to set the bone.
  54631. * @param mesh The mesh that this bone is attached to.
  54632. */
  54633. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  54634. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  54635. };
  54636. /**
  54637. * Set the scale of the bone on the x, y and z axes.
  54638. * @param x The scale of the bone on the x axis.
  54639. * @param x The scale of the bone on the y axis.
  54640. * @param z The scale of the bone on the z axis.
  54641. * @param scaleChildren Set this to true if children of the bone should be scaled.
  54642. */
  54643. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  54644. if (scaleChildren === void 0) { scaleChildren = false; }
  54645. if (this.animations[0] && !this.animations[0].isStopped()) {
  54646. if (!scaleChildren) {
  54647. this._negateScaleChildren.x = 1 / x;
  54648. this._negateScaleChildren.y = 1 / y;
  54649. this._negateScaleChildren.z = 1 / z;
  54650. }
  54651. this._syncScaleVector();
  54652. }
  54653. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  54654. };
  54655. /**
  54656. * Scale the bone on the x, y and z axes.
  54657. * @param x The amount to scale the bone on the x axis.
  54658. * @param x The amount to scale the bone on the y axis.
  54659. * @param z The amount to scale the bone on the z axis.
  54660. * @param scaleChildren Set this to true if children of the bone should be scaled.
  54661. */
  54662. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  54663. if (scaleChildren === void 0) { scaleChildren = false; }
  54664. var locMat = this.getLocalMatrix();
  54665. var origLocMat = Bone._tmpMats[0];
  54666. origLocMat.copyFrom(locMat);
  54667. var origLocMatInv = Bone._tmpMats[1];
  54668. origLocMatInv.copyFrom(origLocMat);
  54669. origLocMatInv.invert();
  54670. var scaleMat = Bone._tmpMats[2];
  54671. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  54672. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  54673. this._scaleVector.x *= x;
  54674. this._scaleVector.y *= y;
  54675. this._scaleVector.z *= z;
  54676. locMat.multiplyToRef(origLocMatInv, locMat);
  54677. locMat.multiplyToRef(scaleMat, locMat);
  54678. locMat.multiplyToRef(origLocMat, locMat);
  54679. var parent = this.getParent();
  54680. if (parent) {
  54681. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  54682. }
  54683. else {
  54684. this.getAbsoluteTransform().copyFrom(locMat);
  54685. }
  54686. var len = this.children.length;
  54687. scaleMat.invert();
  54688. for (var i = 0; i < len; i++) {
  54689. var child = this.children[i];
  54690. var cm = child.getLocalMatrix();
  54691. cm.multiplyToRef(scaleMat, cm);
  54692. var lm = child.getLocalMatrix();
  54693. lm.m[12] *= x;
  54694. lm.m[13] *= y;
  54695. lm.m[14] *= z;
  54696. }
  54697. this.computeAbsoluteTransforms();
  54698. if (scaleChildren) {
  54699. for (var i = 0; i < len; i++) {
  54700. this.children[i].scale(x, y, z, scaleChildren);
  54701. }
  54702. }
  54703. this.markAsDirty();
  54704. };
  54705. /**
  54706. * Set the yaw, pitch, and roll of the bone in local or world space.
  54707. * @param yaw The rotation of the bone on the y axis.
  54708. * @param pitch The rotation of the bone on the x axis.
  54709. * @param roll The rotation of the bone on the z axis.
  54710. * @param space The space that the axes of rotation are in.
  54711. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54712. */
  54713. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  54714. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54715. var rotMat = Bone._tmpMats[0];
  54716. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  54717. var rotMatInv = Bone._tmpMats[1];
  54718. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54719. rotMatInv.multiplyToRef(rotMat, rotMat);
  54720. this._rotateWithMatrix(rotMat, space, mesh);
  54721. };
  54722. /**
  54723. * Rotate the bone on an axis in local or world space.
  54724. * @param axis The axis to rotate the bone on.
  54725. * @param amount The amount to rotate the bone.
  54726. * @param space The space that the axis is in.
  54727. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54728. */
  54729. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  54730. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54731. var rmat = Bone._tmpMats[0];
  54732. rmat.m[12] = 0;
  54733. rmat.m[13] = 0;
  54734. rmat.m[14] = 0;
  54735. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  54736. this._rotateWithMatrix(rmat, space, mesh);
  54737. };
  54738. /**
  54739. * Set the rotation of the bone to a particular axis angle in local or world space.
  54740. * @param axis The axis to rotate the bone on.
  54741. * @param angle The angle that the bone should be rotated to.
  54742. * @param space The space that the axis is in.
  54743. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54744. */
  54745. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  54746. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54747. var rotMat = Bone._tmpMats[0];
  54748. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  54749. var rotMatInv = Bone._tmpMats[1];
  54750. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54751. rotMatInv.multiplyToRef(rotMat, rotMat);
  54752. this._rotateWithMatrix(rotMat, space, mesh);
  54753. };
  54754. /**
  54755. * Set the euler rotation of the bone in local of world space.
  54756. * @param rotation The euler rotation that the bone should be set to.
  54757. * @param space The space that the rotation is in.
  54758. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54759. */
  54760. Bone.prototype.setRotation = function (rotation, space, mesh) {
  54761. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54762. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  54763. };
  54764. /**
  54765. * Set the quaternion rotation of the bone in local of world space.
  54766. * @param quat The quaternion rotation that the bone should be set to.
  54767. * @param space The space that the rotation is in.
  54768. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54769. */
  54770. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  54771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54772. var rotMatInv = Bone._tmpMats[0];
  54773. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54774. var rotMat = Bone._tmpMats[1];
  54775. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  54776. rotMatInv.multiplyToRef(rotMat, rotMat);
  54777. this._rotateWithMatrix(rotMat, space, mesh);
  54778. };
  54779. /**
  54780. * Set the rotation matrix of the bone in local of world space.
  54781. * @param rotMat The rotation matrix that the bone should be set to.
  54782. * @param space The space that the rotation is in.
  54783. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54784. */
  54785. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  54786. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54787. var rotMatInv = Bone._tmpMats[0];
  54788. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  54789. var rotMat2 = Bone._tmpMats[1];
  54790. rotMat2.copyFrom(rotMat);
  54791. rotMatInv.multiplyToRef(rotMat, rotMat2);
  54792. this._rotateWithMatrix(rotMat2, space, mesh);
  54793. };
  54794. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  54795. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54796. var lmat = this.getLocalMatrix();
  54797. var lx = lmat.m[12];
  54798. var ly = lmat.m[13];
  54799. var lz = lmat.m[14];
  54800. var parent = this.getParent();
  54801. var parentScale = Bone._tmpMats[3];
  54802. var parentScaleInv = Bone._tmpMats[4];
  54803. if (parent) {
  54804. if (space == BABYLON.Space.WORLD) {
  54805. if (mesh) {
  54806. parentScale.copyFrom(mesh.getWorldMatrix());
  54807. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  54808. }
  54809. else {
  54810. parentScale.copyFrom(parent.getAbsoluteTransform());
  54811. }
  54812. }
  54813. else {
  54814. parentScale = parent._scaleMatrix;
  54815. }
  54816. parentScaleInv.copyFrom(parentScale);
  54817. parentScaleInv.invert();
  54818. lmat.multiplyToRef(parentScale, lmat);
  54819. lmat.multiplyToRef(rmat, lmat);
  54820. lmat.multiplyToRef(parentScaleInv, lmat);
  54821. }
  54822. else {
  54823. if (space == BABYLON.Space.WORLD && mesh) {
  54824. parentScale.copyFrom(mesh.getWorldMatrix());
  54825. parentScaleInv.copyFrom(parentScale);
  54826. parentScaleInv.invert();
  54827. lmat.multiplyToRef(parentScale, lmat);
  54828. lmat.multiplyToRef(rmat, lmat);
  54829. lmat.multiplyToRef(parentScaleInv, lmat);
  54830. }
  54831. else {
  54832. lmat.multiplyToRef(rmat, lmat);
  54833. }
  54834. }
  54835. lmat.m[12] = lx;
  54836. lmat.m[13] = ly;
  54837. lmat.m[14] = lz;
  54838. this.computeAbsoluteTransforms();
  54839. this.markAsDirty();
  54840. };
  54841. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  54842. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54843. if (space == BABYLON.Space.WORLD) {
  54844. var scaleMatrix = Bone._tmpMats[2];
  54845. scaleMatrix.copyFrom(this._scaleMatrix);
  54846. rotMatInv.copyFrom(this.getAbsoluteTransform());
  54847. if (mesh) {
  54848. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  54849. var meshScale = Bone._tmpMats[3];
  54850. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  54851. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  54852. }
  54853. rotMatInv.invert();
  54854. scaleMatrix.m[0] *= this._scalingDeterminant;
  54855. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  54856. }
  54857. else {
  54858. rotMatInv.copyFrom(this.getLocalMatrix());
  54859. rotMatInv.invert();
  54860. var scaleMatrix = Bone._tmpMats[2];
  54861. scaleMatrix.copyFrom(this._scaleMatrix);
  54862. if (this._parent) {
  54863. var pscaleMatrix = Bone._tmpMats[3];
  54864. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  54865. pscaleMatrix.invert();
  54866. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  54867. }
  54868. else {
  54869. scaleMatrix.m[0] *= this._scalingDeterminant;
  54870. }
  54871. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  54872. }
  54873. };
  54874. /**
  54875. * Get the scale of the bone
  54876. * @returns the scale of the bone
  54877. */
  54878. Bone.prototype.getScale = function () {
  54879. return this._scaleVector.clone();
  54880. };
  54881. /**
  54882. * Copy the scale of the bone to a vector3.
  54883. * @param result The vector3 to copy the scale to
  54884. */
  54885. Bone.prototype.getScaleToRef = function (result) {
  54886. result.copyFrom(this._scaleVector);
  54887. };
  54888. /**
  54889. * Get the position of the bone in local or world space.
  54890. * @param space The space that the returned position is in.
  54891. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54892. * @returns The position of the bone
  54893. */
  54894. Bone.prototype.getPosition = function (space, mesh) {
  54895. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54896. var pos = BABYLON.Vector3.Zero();
  54897. this.getPositionToRef(space, mesh, pos);
  54898. return pos;
  54899. };
  54900. /**
  54901. * Copy the position of the bone to a vector3 in local or world space.
  54902. * @param space The space that the returned position is in.
  54903. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  54904. * @param result The vector3 to copy the position to.
  54905. */
  54906. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  54907. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  54908. if (space == BABYLON.Space.LOCAL) {
  54909. var lm = this.getLocalMatrix();
  54910. result.x = lm.m[12];
  54911. result.y = lm.m[13];
  54912. result.z = lm.m[14];
  54913. }
  54914. else {
  54915. var wm;
  54916. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  54917. if (mesh) {
  54918. wm = mesh.getWorldMatrix();
  54919. }
  54920. this._skeleton.computeAbsoluteTransforms();
  54921. var tmat = Bone._tmpMats[0];
  54922. if (mesh) {
  54923. tmat.copyFrom(this.getAbsoluteTransform());
  54924. tmat.multiplyToRef(wm, tmat);
  54925. }
  54926. else {
  54927. tmat = this.getAbsoluteTransform();
  54928. }
  54929. result.x = tmat.m[12];
  54930. result.y = tmat.m[13];
  54931. result.z = tmat.m[14];
  54932. }
  54933. };
  54934. /**
  54935. * Get the absolute position of the bone (world space).
  54936. * @param mesh The mesh that this bone is attached to.
  54937. * @returns The absolute position of the bone
  54938. */
  54939. Bone.prototype.getAbsolutePosition = function (mesh) {
  54940. var pos = BABYLON.Vector3.Zero();
  54941. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  54942. return pos;
  54943. };
  54944. /**
  54945. * Copy the absolute position of the bone (world space) to the result param.
  54946. * @param mesh The mesh that this bone is attached to.
  54947. * @param result The vector3 to copy the absolute position to.
  54948. */
  54949. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  54950. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  54951. };
  54952. /**
  54953. * Compute the absolute transforms of this bone and its children.
  54954. */
  54955. Bone.prototype.computeAbsoluteTransforms = function () {
  54956. if (this._parent) {
  54957. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  54958. }
  54959. else {
  54960. this._absoluteTransform.copyFrom(this._localMatrix);
  54961. var poseMatrix = this._skeleton.getPoseMatrix();
  54962. if (poseMatrix) {
  54963. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  54964. }
  54965. }
  54966. var children = this.children;
  54967. var len = children.length;
  54968. for (var i = 0; i < len; i++) {
  54969. children[i].computeAbsoluteTransforms();
  54970. }
  54971. };
  54972. Bone.prototype._syncScaleVector = function () {
  54973. var lm = this.getLocalMatrix();
  54974. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  54975. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  54976. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  54977. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  54978. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  54979. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  54980. this._scaleVector.x = xs * Math.sqrt(xsq);
  54981. this._scaleVector.y = ys * Math.sqrt(ysq);
  54982. this._scaleVector.z = zs * Math.sqrt(zsq);
  54983. if (this._parent) {
  54984. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  54985. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  54986. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  54987. }
  54988. 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);
  54989. };
  54990. /**
  54991. * Get the world direction from an axis that is in the local space of the bone.
  54992. * @param localAxis The local direction that is used to compute the world direction.
  54993. * @param mesh The mesh that this bone is attached to.
  54994. * @returns The world direction
  54995. */
  54996. Bone.prototype.getDirection = function (localAxis, mesh) {
  54997. var result = BABYLON.Vector3.Zero();
  54998. this.getDirectionToRef(localAxis, mesh, result);
  54999. return result;
  55000. };
  55001. /**
  55002. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  55003. * @param localAxis The local direction that is used to compute the world direction.
  55004. * @param mesh The mesh that this bone is attached to.
  55005. * @param result The vector3 that the world direction will be copied to.
  55006. */
  55007. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  55008. var wm;
  55009. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55010. if (mesh) {
  55011. wm = mesh.getWorldMatrix();
  55012. }
  55013. this._skeleton.computeAbsoluteTransforms();
  55014. var mat = Bone._tmpMats[0];
  55015. mat.copyFrom(this.getAbsoluteTransform());
  55016. if (mesh) {
  55017. mat.multiplyToRef(wm, mat);
  55018. }
  55019. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  55020. result.normalize();
  55021. };
  55022. /**
  55023. * Get the euler rotation of the bone in local or world space.
  55024. * @param space The space that the rotation should be in.
  55025. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55026. * @returns The euler rotation
  55027. */
  55028. Bone.prototype.getRotation = function (space, mesh) {
  55029. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55030. var result = BABYLON.Vector3.Zero();
  55031. this.getRotationToRef(space, mesh, result);
  55032. return result;
  55033. };
  55034. /**
  55035. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  55036. * @param space The space that the rotation should be in.
  55037. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55038. * @param result The vector3 that the rotation should be copied to.
  55039. */
  55040. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  55041. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55042. var quat = Bone._tmpQuat;
  55043. this.getRotationQuaternionToRef(space, mesh, quat);
  55044. quat.toEulerAnglesToRef(result);
  55045. };
  55046. /**
  55047. * Get the quaternion rotation of the bone in either local or world space.
  55048. * @param space The space that the rotation should be in.
  55049. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55050. * @returns The quaternion rotation
  55051. */
  55052. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  55053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55054. var result = BABYLON.Quaternion.Identity();
  55055. this.getRotationQuaternionToRef(space, mesh, result);
  55056. return result;
  55057. };
  55058. /**
  55059. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  55060. * @param space The space that the rotation should be in.
  55061. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55062. * @param result The quaternion that the rotation should be copied to.
  55063. */
  55064. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  55065. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55066. if (space == BABYLON.Space.LOCAL) {
  55067. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  55068. }
  55069. else {
  55070. var mat = Bone._tmpMats[0];
  55071. var amat = this.getAbsoluteTransform();
  55072. if (mesh) {
  55073. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  55074. }
  55075. else {
  55076. mat.copyFrom(amat);
  55077. }
  55078. mat.m[0] *= this._scalingDeterminant;
  55079. mat.m[1] *= this._scalingDeterminant;
  55080. mat.m[2] *= this._scalingDeterminant;
  55081. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  55082. }
  55083. };
  55084. /**
  55085. * Get the rotation matrix of the bone in local or world space.
  55086. * @param space The space that the rotation should be in.
  55087. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55088. * @returns The rotation matrix
  55089. */
  55090. Bone.prototype.getRotationMatrix = function (space, mesh) {
  55091. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55092. var result = BABYLON.Matrix.Identity();
  55093. this.getRotationMatrixToRef(space, mesh, result);
  55094. return result;
  55095. };
  55096. /**
  55097. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  55098. * @param space The space that the rotation should be in.
  55099. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55100. * @param result The quaternion that the rotation should be copied to.
  55101. */
  55102. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  55103. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55104. if (space == BABYLON.Space.LOCAL) {
  55105. this.getLocalMatrix().getRotationMatrixToRef(result);
  55106. }
  55107. else {
  55108. var mat = Bone._tmpMats[0];
  55109. var amat = this.getAbsoluteTransform();
  55110. if (mesh) {
  55111. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  55112. }
  55113. else {
  55114. mat.copyFrom(amat);
  55115. }
  55116. mat.m[0] *= this._scalingDeterminant;
  55117. mat.m[1] *= this._scalingDeterminant;
  55118. mat.m[2] *= this._scalingDeterminant;
  55119. mat.getRotationMatrixToRef(result);
  55120. }
  55121. };
  55122. /**
  55123. * Get the world position of a point that is in the local space of the bone.
  55124. * @param position The local position
  55125. * @param mesh The mesh that this bone is attached to.
  55126. * @returns The world position
  55127. */
  55128. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  55129. var result = BABYLON.Vector3.Zero();
  55130. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  55131. return result;
  55132. };
  55133. /**
  55134. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  55135. * @param position The local position
  55136. * @param mesh The mesh that this bone is attached to.
  55137. * @param result The vector3 that the world position should be copied to.
  55138. */
  55139. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  55140. var wm;
  55141. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55142. if (mesh) {
  55143. wm = mesh.getWorldMatrix();
  55144. }
  55145. this._skeleton.computeAbsoluteTransforms();
  55146. var tmat = Bone._tmpMats[0];
  55147. if (mesh) {
  55148. tmat.copyFrom(this.getAbsoluteTransform());
  55149. tmat.multiplyToRef(wm, tmat);
  55150. }
  55151. else {
  55152. tmat = this.getAbsoluteTransform();
  55153. }
  55154. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  55155. };
  55156. /**
  55157. * Get the local position of a point that is in world space.
  55158. * @param position The world position
  55159. * @param mesh The mesh that this bone is attached to.
  55160. * @returns The local position
  55161. */
  55162. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  55163. var result = BABYLON.Vector3.Zero();
  55164. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  55165. return result;
  55166. };
  55167. /**
  55168. * Get the local position of a point that is in world space and copy it to the result param.
  55169. * @param position The world position
  55170. * @param mesh The mesh that this bone is attached to.
  55171. * @param result The vector3 that the local position should be copied to.
  55172. */
  55173. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  55174. var wm;
  55175. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55176. if (mesh) {
  55177. wm = mesh.getWorldMatrix();
  55178. }
  55179. this._skeleton.computeAbsoluteTransforms();
  55180. var tmat = Bone._tmpMats[0];
  55181. tmat.copyFrom(this.getAbsoluteTransform());
  55182. if (mesh) {
  55183. tmat.multiplyToRef(wm, tmat);
  55184. }
  55185. tmat.invert();
  55186. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  55187. };
  55188. return Bone;
  55189. }(BABYLON.Node));
  55190. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55191. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  55192. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  55193. BABYLON.Bone = Bone;
  55194. })(BABYLON || (BABYLON = {}));
  55195. //# sourceMappingURL=babylon.bone.js.map
  55196. var BABYLON;
  55197. (function (BABYLON) {
  55198. var BoneIKController = (function () {
  55199. function BoneIKController(mesh, bone, options) {
  55200. this.targetPosition = BABYLON.Vector3.Zero();
  55201. this.poleTargetPosition = BABYLON.Vector3.Zero();
  55202. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  55203. this.poleAngle = 0;
  55204. this.slerpAmount = 1;
  55205. this._bone1Quat = BABYLON.Quaternion.Identity();
  55206. this._bone1Mat = BABYLON.Matrix.Identity();
  55207. this._bone2Ang = Math.PI;
  55208. this._maxAngle = Math.PI;
  55209. this._rightHandedSystem = false;
  55210. this._bendAxis = BABYLON.Vector3.Right();
  55211. this._slerping = false;
  55212. this._adjustRoll = 0;
  55213. this._bone2 = bone;
  55214. this._bone1 = bone.getParent();
  55215. this.mesh = mesh;
  55216. var bonePos = bone.getPosition();
  55217. if (bone.getAbsoluteTransform().determinant() > 0) {
  55218. this._rightHandedSystem = true;
  55219. this._bendAxis.x = 0;
  55220. this._bendAxis.y = 0;
  55221. this._bendAxis.z = -1;
  55222. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  55223. this._adjustRoll = Math.PI * .5;
  55224. this._bendAxis.z = 1;
  55225. }
  55226. }
  55227. if (this._bone1.length) {
  55228. var boneScale1 = this._bone1.getScale();
  55229. var boneScale2 = this._bone2.getScale();
  55230. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  55231. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  55232. }
  55233. else if (this._bone1.children[0]) {
  55234. mesh.computeWorldMatrix(true);
  55235. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  55236. var pos2 = this._bone2.getAbsolutePosition(mesh);
  55237. var pos3 = this._bone1.getAbsolutePosition(mesh);
  55238. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  55239. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  55240. }
  55241. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  55242. this.maxAngle = Math.PI;
  55243. if (options) {
  55244. if (options.targetMesh) {
  55245. this.targetMesh = options.targetMesh;
  55246. this.targetMesh.computeWorldMatrix(true);
  55247. }
  55248. if (options.poleTargetMesh) {
  55249. this.poleTargetMesh = options.poleTargetMesh;
  55250. this.poleTargetMesh.computeWorldMatrix(true);
  55251. }
  55252. else if (options.poleTargetBone) {
  55253. this.poleTargetBone = options.poleTargetBone;
  55254. }
  55255. else if (this._bone1.getParent()) {
  55256. this.poleTargetBone = this._bone1.getParent();
  55257. }
  55258. if (options.poleTargetLocalOffset) {
  55259. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  55260. }
  55261. if (options.poleAngle) {
  55262. this.poleAngle = options.poleAngle;
  55263. }
  55264. if (options.bendAxis) {
  55265. this._bendAxis.copyFrom(options.bendAxis);
  55266. }
  55267. if (options.maxAngle) {
  55268. this.maxAngle = options.maxAngle;
  55269. }
  55270. if (options.slerpAmount) {
  55271. this.slerpAmount = options.slerpAmount;
  55272. }
  55273. }
  55274. }
  55275. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  55276. get: function () {
  55277. return this._maxAngle;
  55278. },
  55279. set: function (value) {
  55280. this._setMaxAngle(value);
  55281. },
  55282. enumerable: true,
  55283. configurable: true
  55284. });
  55285. BoneIKController.prototype._setMaxAngle = function (ang) {
  55286. if (ang < 0) {
  55287. ang = 0;
  55288. }
  55289. if (ang > Math.PI || ang == undefined) {
  55290. ang = Math.PI;
  55291. }
  55292. this._maxAngle = ang;
  55293. var a = this._bone1Length;
  55294. var b = this._bone2Length;
  55295. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  55296. };
  55297. BoneIKController.prototype.update = function () {
  55298. var bone1 = this._bone1;
  55299. var target = this.targetPosition;
  55300. var poleTarget = this.poleTargetPosition;
  55301. var mat1 = BoneIKController._tmpMats[0];
  55302. var mat2 = BoneIKController._tmpMats[1];
  55303. if (this.targetMesh) {
  55304. target.copyFrom(this.targetMesh.getAbsolutePosition());
  55305. }
  55306. if (this.poleTargetBone) {
  55307. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  55308. }
  55309. else if (this.poleTargetMesh) {
  55310. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  55311. }
  55312. var bonePos = BoneIKController._tmpVecs[0];
  55313. var zaxis = BoneIKController._tmpVecs[1];
  55314. var xaxis = BoneIKController._tmpVecs[2];
  55315. var yaxis = BoneIKController._tmpVecs[3];
  55316. var upAxis = BoneIKController._tmpVecs[4];
  55317. var _tmpQuat = BoneIKController._tmpQuat;
  55318. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  55319. poleTarget.subtractToRef(bonePos, upAxis);
  55320. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  55321. upAxis.y = 1;
  55322. }
  55323. else {
  55324. upAxis.normalize();
  55325. }
  55326. target.subtractToRef(bonePos, yaxis);
  55327. yaxis.normalize();
  55328. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  55329. zaxis.normalize();
  55330. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  55331. xaxis.normalize();
  55332. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  55333. var a = this._bone1Length;
  55334. var b = this._bone2Length;
  55335. var c = BABYLON.Vector3.Distance(bonePos, target);
  55336. if (this._maxReach > 0) {
  55337. c = Math.min(this._maxReach, c);
  55338. }
  55339. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  55340. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  55341. if (acosa > 1) {
  55342. acosa = 1;
  55343. }
  55344. if (acosb > 1) {
  55345. acosb = 1;
  55346. }
  55347. if (acosa < -1) {
  55348. acosa = -1;
  55349. }
  55350. if (acosb < -1) {
  55351. acosb = -1;
  55352. }
  55353. var angA = Math.acos(acosa);
  55354. var angB = Math.acos(acosb);
  55355. var angC = -angA - angB;
  55356. if (this._rightHandedSystem) {
  55357. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  55358. mat2.multiplyToRef(mat1, mat1);
  55359. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  55360. mat2.multiplyToRef(mat1, mat1);
  55361. }
  55362. else {
  55363. var _tmpVec = BoneIKController._tmpVecs[5];
  55364. _tmpVec.copyFrom(this._bendAxis);
  55365. _tmpVec.x *= -1;
  55366. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  55367. mat2.multiplyToRef(mat1, mat1);
  55368. }
  55369. if (this.poleAngle) {
  55370. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  55371. mat1.multiplyToRef(mat2, mat1);
  55372. }
  55373. if (this.slerpAmount < 1) {
  55374. if (!this._slerping) {
  55375. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  55376. }
  55377. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  55378. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  55379. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  55380. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  55381. this._slerping = true;
  55382. }
  55383. else {
  55384. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  55385. this._bone1Mat.copyFrom(mat1);
  55386. this._slerping = false;
  55387. }
  55388. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  55389. this._bone2Ang = angC;
  55390. };
  55391. return BoneIKController;
  55392. }());
  55393. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55394. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  55395. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  55396. BABYLON.BoneIKController = BoneIKController;
  55397. })(BABYLON || (BABYLON = {}));
  55398. //# sourceMappingURL=babylon.boneIKController.js.map
  55399. var BABYLON;
  55400. (function (BABYLON) {
  55401. var BoneLookController = (function () {
  55402. /**
  55403. * Create a BoneLookController
  55404. * @param mesh the mesh that the bone belongs to
  55405. * @param bone the bone that will be looking to the target
  55406. * @param target the target Vector3 to look at
  55407. * @param settings optional settings:
  55408. * - maxYaw: the maximum angle the bone will yaw to
  55409. * - minYaw: the minimum angle the bone will yaw to
  55410. * - maxPitch: the maximum angle the bone will pitch to
  55411. * - minPitch: the minimum angle the bone will yaw to
  55412. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  55413. * - upAxis: the up axis of the coordinate system
  55414. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  55415. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  55416. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  55417. * - adjustYaw: used to make an adjustment to the yaw of the bone
  55418. * - adjustPitch: used to make an adjustment to the pitch of the bone
  55419. * - adjustRoll: used to make an adjustment to the roll of the bone
  55420. **/
  55421. function BoneLookController(mesh, bone, target, options) {
  55422. /**
  55423. * The up axis of the coordinate system that is used when the bone is rotated.
  55424. */
  55425. this.upAxis = BABYLON.Vector3.Up();
  55426. /**
  55427. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  55428. */
  55429. this.upAxisSpace = BABYLON.Space.LOCAL;
  55430. /**
  55431. * Used to make an adjustment to the yaw of the bone.
  55432. */
  55433. this.adjustYaw = 0;
  55434. /**
  55435. * Used to make an adjustment to the pitch of the bone.
  55436. */
  55437. this.adjustPitch = 0;
  55438. /**
  55439. * Used to make an adjustment to the roll of the bone.
  55440. */
  55441. this.adjustRoll = 0;
  55442. /**
  55443. * 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).
  55444. */
  55445. this.slerpAmount = 1;
  55446. this._boneQuat = BABYLON.Quaternion.Identity();
  55447. this._slerping = false;
  55448. this._firstFrameSkipped = false;
  55449. this._fowardAxis = BABYLON.Vector3.Forward();
  55450. this.mesh = mesh;
  55451. this.bone = bone;
  55452. this.target = target;
  55453. if (options) {
  55454. if (options.adjustYaw) {
  55455. this.adjustYaw = options.adjustYaw;
  55456. }
  55457. if (options.adjustPitch) {
  55458. this.adjustPitch = options.adjustPitch;
  55459. }
  55460. if (options.adjustRoll) {
  55461. this.adjustRoll = options.adjustRoll;
  55462. }
  55463. if (options.maxYaw != null) {
  55464. this.maxYaw = options.maxYaw;
  55465. }
  55466. else {
  55467. this.maxYaw = Math.PI;
  55468. }
  55469. if (options.minYaw != null) {
  55470. this.minYaw = options.minYaw;
  55471. }
  55472. else {
  55473. this.minYaw = -Math.PI;
  55474. }
  55475. if (options.maxPitch != null) {
  55476. this.maxPitch = options.maxPitch;
  55477. }
  55478. else {
  55479. this.maxPitch = Math.PI;
  55480. }
  55481. if (options.minPitch != null) {
  55482. this.minPitch = options.minPitch;
  55483. }
  55484. else {
  55485. this.minPitch = -Math.PI;
  55486. }
  55487. if (options.slerpAmount != null) {
  55488. this.slerpAmount = options.slerpAmount;
  55489. }
  55490. if (options.upAxis != null) {
  55491. this.upAxis = options.upAxis;
  55492. }
  55493. if (options.upAxisSpace != null) {
  55494. this.upAxisSpace = options.upAxisSpace;
  55495. }
  55496. if (options.yawAxis != null || options.pitchAxis != null) {
  55497. var newYawAxis = BABYLON.Axis.Y;
  55498. var newPitchAxis = BABYLON.Axis.X;
  55499. if (options.yawAxis != null) {
  55500. newYawAxis = options.yawAxis.clone();
  55501. newYawAxis.normalize();
  55502. }
  55503. if (options.pitchAxis != null) {
  55504. newPitchAxis = options.pitchAxis.clone();
  55505. newPitchAxis.normalize();
  55506. }
  55507. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  55508. this._transformYawPitch = BABYLON.Matrix.Identity();
  55509. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  55510. this._transformYawPitchInv = this._transformYawPitch.clone();
  55511. this._transformYawPitch.invert();
  55512. }
  55513. }
  55514. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  55515. this.upAxisSpace = BABYLON.Space.LOCAL;
  55516. }
  55517. }
  55518. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  55519. /**
  55520. * Get/set the minimum yaw angle that the bone can look to.
  55521. */
  55522. get: function () {
  55523. return this._minYaw;
  55524. },
  55525. set: function (value) {
  55526. this._minYaw = value;
  55527. this._minYawSin = Math.sin(value);
  55528. this._minYawCos = Math.cos(value);
  55529. if (this._maxYaw != null) {
  55530. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  55531. this._yawRange = this._maxYaw - this._minYaw;
  55532. }
  55533. },
  55534. enumerable: true,
  55535. configurable: true
  55536. });
  55537. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  55538. /**
  55539. * Get/set the maximum yaw angle that the bone can look to.
  55540. */
  55541. get: function () {
  55542. return this._maxYaw;
  55543. },
  55544. set: function (value) {
  55545. this._maxYaw = value;
  55546. this._maxYawSin = Math.sin(value);
  55547. this._maxYawCos = Math.cos(value);
  55548. if (this._minYaw != null) {
  55549. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  55550. this._yawRange = this._maxYaw - this._minYaw;
  55551. }
  55552. },
  55553. enumerable: true,
  55554. configurable: true
  55555. });
  55556. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  55557. /**
  55558. * Get/set the minimum pitch angle that the bone can look to.
  55559. */
  55560. get: function () {
  55561. return this._minPitch;
  55562. },
  55563. set: function (value) {
  55564. this._minPitch = value;
  55565. this._minPitchTan = Math.tan(value);
  55566. },
  55567. enumerable: true,
  55568. configurable: true
  55569. });
  55570. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  55571. /**
  55572. * Get/set the maximum pitch angle that the bone can look to.
  55573. */
  55574. get: function () {
  55575. return this._maxPitch;
  55576. },
  55577. set: function (value) {
  55578. this._maxPitch = value;
  55579. this._maxPitchTan = Math.tan(value);
  55580. },
  55581. enumerable: true,
  55582. configurable: true
  55583. });
  55584. /**
  55585. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  55586. */
  55587. BoneLookController.prototype.update = function () {
  55588. //skip the first frame when slerping so that the mesh rotation is correct
  55589. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  55590. this._firstFrameSkipped = true;
  55591. return;
  55592. }
  55593. var bone = this.bone;
  55594. var bonePos = BoneLookController._tmpVecs[0];
  55595. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  55596. var target = this.target;
  55597. var _tmpMat1 = BoneLookController._tmpMats[0];
  55598. var _tmpMat2 = BoneLookController._tmpMats[1];
  55599. var mesh = this.mesh;
  55600. var parentBone = bone.getParent();
  55601. var upAxis = BoneLookController._tmpVecs[1];
  55602. upAxis.copyFrom(this.upAxis);
  55603. if (this.upAxisSpace == BABYLON.Space.BONE) {
  55604. if (this._transformYawPitch) {
  55605. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  55606. }
  55607. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  55608. }
  55609. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  55610. mesh.getDirectionToRef(upAxis, upAxis);
  55611. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  55612. upAxis.normalize();
  55613. }
  55614. }
  55615. var checkYaw = false;
  55616. var checkPitch = false;
  55617. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  55618. checkYaw = true;
  55619. }
  55620. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  55621. checkPitch = true;
  55622. }
  55623. if (checkYaw || checkPitch) {
  55624. var spaceMat = BoneLookController._tmpMats[2];
  55625. var spaceMatInv = BoneLookController._tmpMats[3];
  55626. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  55627. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  55628. }
  55629. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  55630. spaceMat.copyFrom(mesh.getWorldMatrix());
  55631. }
  55632. else {
  55633. var forwardAxis = BoneLookController._tmpVecs[2];
  55634. forwardAxis.copyFrom(this._fowardAxis);
  55635. if (this._transformYawPitch) {
  55636. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  55637. }
  55638. if (parentBone) {
  55639. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  55640. }
  55641. else {
  55642. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  55643. }
  55644. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  55645. rightAxis.normalize();
  55646. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  55647. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  55648. }
  55649. spaceMat.invertToRef(spaceMatInv);
  55650. var xzlen;
  55651. if (checkPitch) {
  55652. var localTarget = BoneLookController._tmpVecs[3];
  55653. target.subtractToRef(bonePos, localTarget);
  55654. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  55655. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55656. var pitch = Math.atan2(localTarget.y, xzlen);
  55657. var newPitch = pitch;
  55658. if (pitch > this._maxPitch) {
  55659. localTarget.y = this._maxPitchTan * xzlen;
  55660. newPitch = this._maxPitch;
  55661. }
  55662. else if (pitch < this._minPitch) {
  55663. localTarget.y = this._minPitchTan * xzlen;
  55664. newPitch = this._minPitch;
  55665. }
  55666. if (pitch != newPitch) {
  55667. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  55668. localTarget.addInPlace(bonePos);
  55669. target = localTarget;
  55670. }
  55671. }
  55672. if (checkYaw) {
  55673. var localTarget = BoneLookController._tmpVecs[4];
  55674. target.subtractToRef(bonePos, localTarget);
  55675. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  55676. var yaw = Math.atan2(localTarget.x, localTarget.z);
  55677. var newYaw = yaw;
  55678. if (yaw > this._maxYaw || yaw < this._minYaw) {
  55679. if (xzlen == null) {
  55680. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55681. }
  55682. if (this._yawRange > Math.PI) {
  55683. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  55684. localTarget.z = this._maxYawCos * xzlen;
  55685. localTarget.x = this._maxYawSin * xzlen;
  55686. newYaw = this._maxYaw;
  55687. }
  55688. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  55689. localTarget.z = this._minYawCos * xzlen;
  55690. localTarget.x = this._minYawSin * xzlen;
  55691. newYaw = this._minYaw;
  55692. }
  55693. }
  55694. else {
  55695. if (yaw > this._maxYaw) {
  55696. localTarget.z = this._maxYawCos * xzlen;
  55697. localTarget.x = this._maxYawSin * xzlen;
  55698. newYaw = this._maxYaw;
  55699. }
  55700. else if (yaw < this._minYaw) {
  55701. localTarget.z = this._minYawCos * xzlen;
  55702. localTarget.x = this._minYawSin * xzlen;
  55703. newYaw = this._minYaw;
  55704. }
  55705. }
  55706. }
  55707. if (this._slerping && this._yawRange > Math.PI) {
  55708. //are we going to be crossing into the min/max region?
  55709. var boneFwd = BoneLookController._tmpVecs[8];
  55710. boneFwd.copyFrom(BABYLON.Axis.Z);
  55711. if (this._transformYawPitch) {
  55712. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  55713. }
  55714. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  55715. this._boneQuat.toRotationMatrix(boneRotMat);
  55716. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  55717. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  55718. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  55719. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  55720. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  55721. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  55722. if (angBtwTar > angBtwMidYaw) {
  55723. if (xzlen == null) {
  55724. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  55725. }
  55726. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  55727. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  55728. if (angBtwMin < angBtwMax) {
  55729. newYaw = boneYaw + Math.PI * .75;
  55730. localTarget.z = Math.cos(newYaw) * xzlen;
  55731. localTarget.x = Math.sin(newYaw) * xzlen;
  55732. }
  55733. else {
  55734. newYaw = boneYaw - Math.PI * .75;
  55735. localTarget.z = Math.cos(newYaw) * xzlen;
  55736. localTarget.x = Math.sin(newYaw) * xzlen;
  55737. }
  55738. }
  55739. }
  55740. if (yaw != newYaw) {
  55741. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  55742. localTarget.addInPlace(bonePos);
  55743. target = localTarget;
  55744. }
  55745. }
  55746. }
  55747. var zaxis = BoneLookController._tmpVecs[5];
  55748. var xaxis = BoneLookController._tmpVecs[6];
  55749. var yaxis = BoneLookController._tmpVecs[7];
  55750. var _tmpQuat = BoneLookController._tmpQuat;
  55751. target.subtractToRef(bonePos, zaxis);
  55752. zaxis.normalize();
  55753. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  55754. xaxis.normalize();
  55755. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  55756. yaxis.normalize();
  55757. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  55758. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  55759. return;
  55760. }
  55761. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  55762. return;
  55763. }
  55764. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  55765. return;
  55766. }
  55767. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  55768. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  55769. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  55770. }
  55771. if (this.slerpAmount < 1) {
  55772. if (!this._slerping) {
  55773. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  55774. }
  55775. if (this._transformYawPitch) {
  55776. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  55777. }
  55778. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  55779. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  55780. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  55781. this._slerping = true;
  55782. }
  55783. else {
  55784. if (this._transformYawPitch) {
  55785. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  55786. }
  55787. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  55788. this._slerping = false;
  55789. }
  55790. };
  55791. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  55792. var angDiff = ang2 - ang1;
  55793. angDiff %= Math.PI * 2;
  55794. if (angDiff > Math.PI) {
  55795. angDiff -= Math.PI * 2;
  55796. }
  55797. else if (angDiff < -Math.PI) {
  55798. angDiff += Math.PI * 2;
  55799. }
  55800. return angDiff;
  55801. };
  55802. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  55803. ang1 %= (2 * Math.PI);
  55804. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  55805. ang2 %= (2 * Math.PI);
  55806. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  55807. var ab = 0;
  55808. if (ang1 < ang2) {
  55809. ab = ang2 - ang1;
  55810. }
  55811. else {
  55812. ab = ang1 - ang2;
  55813. }
  55814. if (ab > Math.PI) {
  55815. ab = Math.PI * 2 - ab;
  55816. }
  55817. return ab;
  55818. };
  55819. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  55820. ang %= (2 * Math.PI);
  55821. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  55822. ang1 %= (2 * Math.PI);
  55823. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  55824. ang2 %= (2 * Math.PI);
  55825. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  55826. if (ang1 < ang2) {
  55827. if (ang > ang1 && ang < ang2) {
  55828. return true;
  55829. }
  55830. }
  55831. else {
  55832. if (ang > ang2 && ang < ang1) {
  55833. return true;
  55834. }
  55835. }
  55836. return false;
  55837. };
  55838. return BoneLookController;
  55839. }());
  55840. 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()];
  55841. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  55842. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  55843. BABYLON.BoneLookController = BoneLookController;
  55844. })(BABYLON || (BABYLON = {}));
  55845. //# sourceMappingURL=babylon.boneLookController.js.map
  55846. var BABYLON;
  55847. (function (BABYLON) {
  55848. var Skeleton = (function () {
  55849. function Skeleton(name, id, scene) {
  55850. this.name = name;
  55851. this.id = id;
  55852. this.bones = new Array();
  55853. this.needInitialSkinMatrix = false;
  55854. this._isDirty = true;
  55855. this._meshesWithPoseMatrix = new Array();
  55856. this._identity = BABYLON.Matrix.Identity();
  55857. this._ranges = {};
  55858. this._lastAbsoluteTransformsUpdateId = -1;
  55859. // Events
  55860. /**
  55861. * An event triggered before computing the skeleton's matrices
  55862. * @type {BABYLON.Observable}
  55863. */
  55864. this.onBeforeComputeObservable = new BABYLON.Observable();
  55865. this.bones = [];
  55866. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55867. scene.skeletons.push(this);
  55868. //make sure it will recalculate the matrix next time prepare is called.
  55869. this._isDirty = true;
  55870. }
  55871. // Members
  55872. Skeleton.prototype.getTransformMatrices = function (mesh) {
  55873. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  55874. return mesh._bonesTransformMatrices;
  55875. }
  55876. if (!this._transformMatrices) {
  55877. this.prepare();
  55878. }
  55879. return this._transformMatrices;
  55880. };
  55881. Skeleton.prototype.getScene = function () {
  55882. return this._scene;
  55883. };
  55884. // Methods
  55885. /**
  55886. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  55887. */
  55888. Skeleton.prototype.toString = function (fullDetails) {
  55889. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  55890. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  55891. if (fullDetails) {
  55892. ret += ", Ranges: {";
  55893. var first = true;
  55894. for (var name_1 in this._ranges) {
  55895. if (first) {
  55896. ret += ", ";
  55897. first = false;
  55898. }
  55899. ret += name_1;
  55900. }
  55901. ret += "}";
  55902. }
  55903. return ret;
  55904. };
  55905. /**
  55906. * Get bone's index searching by name
  55907. * @param {string} name is bone's name to search for
  55908. * @return {number} Indice of the bone. Returns -1 if not found
  55909. */
  55910. Skeleton.prototype.getBoneIndexByName = function (name) {
  55911. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  55912. if (this.bones[boneIndex].name === name) {
  55913. return boneIndex;
  55914. }
  55915. }
  55916. return -1;
  55917. };
  55918. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  55919. // check name not already in use
  55920. if (!this._ranges[name]) {
  55921. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  55922. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  55923. if (this.bones[i].animations[0]) {
  55924. this.bones[i].animations[0].createRange(name, from, to);
  55925. }
  55926. }
  55927. }
  55928. };
  55929. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  55930. if (deleteFrames === void 0) { deleteFrames = true; }
  55931. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  55932. if (this.bones[i].animations[0]) {
  55933. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  55934. }
  55935. }
  55936. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  55937. };
  55938. Skeleton.prototype.getAnimationRange = function (name) {
  55939. return this._ranges[name];
  55940. };
  55941. /**
  55942. * Returns as an Array, all AnimationRanges defined on this skeleton
  55943. */
  55944. Skeleton.prototype.getAnimationRanges = function () {
  55945. var animationRanges = [];
  55946. var name;
  55947. var i = 0;
  55948. for (name in this._ranges) {
  55949. animationRanges[i] = this._ranges[name];
  55950. i++;
  55951. }
  55952. return animationRanges;
  55953. };
  55954. /**
  55955. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  55956. */
  55957. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  55958. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  55959. if (this._ranges[name] || !source.getAnimationRange(name)) {
  55960. return false;
  55961. }
  55962. var ret = true;
  55963. var frameOffset = this._getHighestAnimationFrame() + 1;
  55964. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  55965. var boneDict = {};
  55966. var sourceBones = source.bones;
  55967. var nBones;
  55968. var i;
  55969. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  55970. boneDict[sourceBones[i].name] = sourceBones[i];
  55971. }
  55972. if (this.bones.length !== sourceBones.length) {
  55973. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  55974. ret = false;
  55975. }
  55976. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  55977. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  55978. var boneName = this.bones[i].name;
  55979. var sourceBone = boneDict[boneName];
  55980. if (sourceBone) {
  55981. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  55982. }
  55983. else {
  55984. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  55985. ret = false;
  55986. }
  55987. }
  55988. // do not call createAnimationRange(), since it also is done to bones, which was already done
  55989. var range = source.getAnimationRange(name);
  55990. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  55991. return ret;
  55992. };
  55993. Skeleton.prototype.returnToRest = function () {
  55994. for (var index = 0; index < this.bones.length; index++) {
  55995. this.bones[index].returnToRest();
  55996. }
  55997. };
  55998. Skeleton.prototype._getHighestAnimationFrame = function () {
  55999. var ret = 0;
  56000. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56001. if (this.bones[i].animations[0]) {
  56002. var highest = this.bones[i].animations[0].getHighestFrame();
  56003. if (ret < highest) {
  56004. ret = highest;
  56005. }
  56006. }
  56007. }
  56008. return ret;
  56009. };
  56010. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  56011. var range = this.getAnimationRange(name);
  56012. if (!range) {
  56013. return null;
  56014. }
  56015. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  56016. };
  56017. Skeleton.prototype._markAsDirty = function () {
  56018. this._isDirty = true;
  56019. };
  56020. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  56021. this._meshesWithPoseMatrix.push(mesh);
  56022. };
  56023. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  56024. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  56025. if (index > -1) {
  56026. this._meshesWithPoseMatrix.splice(index, 1);
  56027. }
  56028. };
  56029. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  56030. this.onBeforeComputeObservable.notifyObservers(this);
  56031. for (var index = 0; index < this.bones.length; index++) {
  56032. var bone = this.bones[index];
  56033. var parentBone = bone.getParent();
  56034. if (parentBone) {
  56035. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  56036. }
  56037. else {
  56038. if (initialSkinMatrix) {
  56039. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  56040. }
  56041. else {
  56042. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  56043. }
  56044. }
  56045. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  56046. }
  56047. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  56048. };
  56049. Skeleton.prototype.prepare = function () {
  56050. if (!this._isDirty) {
  56051. return;
  56052. }
  56053. if (this.needInitialSkinMatrix) {
  56054. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  56055. var mesh = this._meshesWithPoseMatrix[index];
  56056. var poseMatrix = mesh.getPoseMatrix();
  56057. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  56058. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  56059. }
  56060. if (this._synchronizedWithMesh !== mesh) {
  56061. this._synchronizedWithMesh = mesh;
  56062. // Prepare bones
  56063. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  56064. var bone = this.bones[boneIndex];
  56065. if (!bone.getParent()) {
  56066. var matrix = bone.getBaseMatrix();
  56067. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  56068. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  56069. }
  56070. }
  56071. }
  56072. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  56073. }
  56074. }
  56075. else {
  56076. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  56077. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  56078. }
  56079. this._computeTransformMatrices(this._transformMatrices, null);
  56080. }
  56081. this._isDirty = false;
  56082. this._scene._activeBones.addCount(this.bones.length, false);
  56083. };
  56084. Skeleton.prototype.getAnimatables = function () {
  56085. if (!this._animatables || this._animatables.length !== this.bones.length) {
  56086. this._animatables = [];
  56087. for (var index = 0; index < this.bones.length; index++) {
  56088. this._animatables.push(this.bones[index]);
  56089. }
  56090. }
  56091. return this._animatables;
  56092. };
  56093. Skeleton.prototype.clone = function (name, id) {
  56094. var result = new Skeleton(name, id || name, this._scene);
  56095. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  56096. for (var index = 0; index < this.bones.length; index++) {
  56097. var source = this.bones[index];
  56098. var parentBone = null;
  56099. if (source.getParent()) {
  56100. var parentIndex = this.bones.indexOf(source.getParent());
  56101. parentBone = result.bones[parentIndex];
  56102. }
  56103. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  56104. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  56105. }
  56106. if (this._ranges) {
  56107. result._ranges = {};
  56108. for (var rangeName in this._ranges) {
  56109. result._ranges[rangeName] = this._ranges[rangeName].clone();
  56110. }
  56111. }
  56112. this._isDirty = true;
  56113. return result;
  56114. };
  56115. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  56116. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  56117. this.bones.forEach(function (bone) {
  56118. bone.animations.forEach(function (animation) {
  56119. animation.enableBlending = true;
  56120. animation.blendingSpeed = blendingSpeed;
  56121. });
  56122. });
  56123. };
  56124. Skeleton.prototype.dispose = function () {
  56125. this._meshesWithPoseMatrix = [];
  56126. // Animations
  56127. this.getScene().stopAnimation(this);
  56128. // Remove from scene
  56129. this.getScene().removeSkeleton(this);
  56130. };
  56131. Skeleton.prototype.serialize = function () {
  56132. var serializationObject = {};
  56133. serializationObject.name = this.name;
  56134. serializationObject.id = this.id;
  56135. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  56136. serializationObject.bones = [];
  56137. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  56138. for (var index = 0; index < this.bones.length; index++) {
  56139. var bone = this.bones[index];
  56140. var serializedBone = {
  56141. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  56142. name: bone.name,
  56143. matrix: bone.getBaseMatrix().toArray(),
  56144. rest: bone.getRestPose().toArray()
  56145. };
  56146. serializationObject.bones.push(serializedBone);
  56147. if (bone.length) {
  56148. serializedBone.length = bone.length;
  56149. }
  56150. if (bone.animations && bone.animations.length > 0) {
  56151. serializedBone.animation = bone.animations[0].serialize();
  56152. }
  56153. serializationObject.ranges = [];
  56154. for (var name in this._ranges) {
  56155. var range = {};
  56156. range.name = name;
  56157. range.from = this._ranges[name].from;
  56158. range.to = this._ranges[name].to;
  56159. serializationObject.ranges.push(range);
  56160. }
  56161. }
  56162. return serializationObject;
  56163. };
  56164. Skeleton.Parse = function (parsedSkeleton, scene) {
  56165. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  56166. if (parsedSkeleton.dimensionsAtRest) {
  56167. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  56168. }
  56169. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  56170. var index;
  56171. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  56172. var parsedBone = parsedSkeleton.bones[index];
  56173. var parentBone = null;
  56174. if (parsedBone.parentBoneIndex > -1) {
  56175. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  56176. }
  56177. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  56178. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  56179. if (parsedBone.length) {
  56180. bone.length = parsedBone.length;
  56181. }
  56182. if (parsedBone.animation) {
  56183. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  56184. }
  56185. }
  56186. // placed after bones, so createAnimationRange can cascade down
  56187. if (parsedSkeleton.ranges) {
  56188. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  56189. var data = parsedSkeleton.ranges[index];
  56190. skeleton.createAnimationRange(data.name, data.from, data.to);
  56191. }
  56192. }
  56193. return skeleton;
  56194. };
  56195. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  56196. if (forceUpdate === void 0) { forceUpdate = false; }
  56197. var renderId = this._scene.getRenderId();
  56198. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  56199. this.bones[0].computeAbsoluteTransforms();
  56200. this._lastAbsoluteTransformsUpdateId = renderId;
  56201. }
  56202. };
  56203. Skeleton.prototype.getPoseMatrix = function () {
  56204. var poseMatrix;
  56205. if (this._meshesWithPoseMatrix.length > 0) {
  56206. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  56207. }
  56208. return poseMatrix;
  56209. };
  56210. return Skeleton;
  56211. }());
  56212. BABYLON.Skeleton = Skeleton;
  56213. })(BABYLON || (BABYLON = {}));
  56214. //# sourceMappingURL=babylon.skeleton.js.map
  56215. var BABYLON;
  56216. (function (BABYLON) {
  56217. var SphericalPolynomial = (function () {
  56218. function SphericalPolynomial() {
  56219. this.x = BABYLON.Vector3.Zero();
  56220. this.y = BABYLON.Vector3.Zero();
  56221. this.z = BABYLON.Vector3.Zero();
  56222. this.xx = BABYLON.Vector3.Zero();
  56223. this.yy = BABYLON.Vector3.Zero();
  56224. this.zz = BABYLON.Vector3.Zero();
  56225. this.xy = BABYLON.Vector3.Zero();
  56226. this.yz = BABYLON.Vector3.Zero();
  56227. this.zx = BABYLON.Vector3.Zero();
  56228. }
  56229. SphericalPolynomial.prototype.addAmbient = function (color) {
  56230. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  56231. this.xx = this.xx.add(colorVector);
  56232. this.yy = this.yy.add(colorVector);
  56233. this.zz = this.zz.add(colorVector);
  56234. };
  56235. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  56236. var result = new SphericalPolynomial();
  56237. result.x = harmonics.L11.scale(1.02333);
  56238. result.y = harmonics.L1_1.scale(1.02333);
  56239. result.z = harmonics.L10.scale(1.02333);
  56240. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  56241. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  56242. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  56243. result.yz = harmonics.L2_1.scale(0.858086);
  56244. result.zx = harmonics.L21.scale(0.858086);
  56245. result.xy = harmonics.L2_2.scale(0.858086);
  56246. result.scale(1.0 / Math.PI);
  56247. return result;
  56248. };
  56249. SphericalPolynomial.prototype.scale = function (scale) {
  56250. this.x = this.x.scale(scale);
  56251. this.y = this.y.scale(scale);
  56252. this.z = this.z.scale(scale);
  56253. this.xx = this.xx.scale(scale);
  56254. this.yy = this.yy.scale(scale);
  56255. this.zz = this.zz.scale(scale);
  56256. this.yz = this.yz.scale(scale);
  56257. this.zx = this.zx.scale(scale);
  56258. this.xy = this.xy.scale(scale);
  56259. };
  56260. return SphericalPolynomial;
  56261. }());
  56262. BABYLON.SphericalPolynomial = SphericalPolynomial;
  56263. var SphericalHarmonics = (function () {
  56264. function SphericalHarmonics() {
  56265. this.L00 = BABYLON.Vector3.Zero();
  56266. this.L1_1 = BABYLON.Vector3.Zero();
  56267. this.L10 = BABYLON.Vector3.Zero();
  56268. this.L11 = BABYLON.Vector3.Zero();
  56269. this.L2_2 = BABYLON.Vector3.Zero();
  56270. this.L2_1 = BABYLON.Vector3.Zero();
  56271. this.L20 = BABYLON.Vector3.Zero();
  56272. this.L21 = BABYLON.Vector3.Zero();
  56273. this.L22 = BABYLON.Vector3.Zero();
  56274. }
  56275. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  56276. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  56277. var c = colorVector.scale(deltaSolidAngle);
  56278. this.L00 = this.L00.add(c.scale(0.282095));
  56279. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  56280. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  56281. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  56282. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  56283. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  56284. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  56285. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  56286. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  56287. };
  56288. SphericalHarmonics.prototype.scale = function (scale) {
  56289. this.L00 = this.L00.scale(scale);
  56290. this.L1_1 = this.L1_1.scale(scale);
  56291. this.L10 = this.L10.scale(scale);
  56292. this.L11 = this.L11.scale(scale);
  56293. this.L2_2 = this.L2_2.scale(scale);
  56294. this.L2_1 = this.L2_1.scale(scale);
  56295. this.L20 = this.L20.scale(scale);
  56296. this.L21 = this.L21.scale(scale);
  56297. this.L22 = this.L22.scale(scale);
  56298. };
  56299. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  56300. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  56301. //
  56302. // E_lm = A_l * L_lm
  56303. //
  56304. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  56305. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  56306. // the scaling factors are given in equation 9.
  56307. // Constant (Band 0)
  56308. this.L00 = this.L00.scale(3.141593);
  56309. // Linear (Band 1)
  56310. this.L1_1 = this.L1_1.scale(2.094395);
  56311. this.L10 = this.L10.scale(2.094395);
  56312. this.L11 = this.L11.scale(2.094395);
  56313. // Quadratic (Band 2)
  56314. this.L2_2 = this.L2_2.scale(0.785398);
  56315. this.L2_1 = this.L2_1.scale(0.785398);
  56316. this.L20 = this.L20.scale(0.785398);
  56317. this.L21 = this.L21.scale(0.785398);
  56318. this.L22 = this.L22.scale(0.785398);
  56319. };
  56320. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  56321. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  56322. // L = (1/pi) * E * rho
  56323. //
  56324. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  56325. this.scale(1.0 / Math.PI);
  56326. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  56327. // (The pixel shader must apply albedo after texture fetches, etc).
  56328. };
  56329. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  56330. var result = new SphericalHarmonics();
  56331. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  56332. result.L1_1 = polynomial.y.scale(0.977204);
  56333. result.L10 = polynomial.z.scale(0.977204);
  56334. result.L11 = polynomial.x.scale(0.977204);
  56335. result.L2_2 = polynomial.xy.scale(1.16538);
  56336. result.L2_1 = polynomial.yz.scale(1.16538);
  56337. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  56338. result.L21 = polynomial.zx.scale(1.16538);
  56339. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  56340. result.scale(Math.PI);
  56341. return result;
  56342. };
  56343. return SphericalHarmonics;
  56344. }());
  56345. BABYLON.SphericalHarmonics = SphericalHarmonics;
  56346. })(BABYLON || (BABYLON = {}));
  56347. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  56348. var BABYLON;
  56349. (function (BABYLON) {
  56350. var Internals;
  56351. (function (Internals) {
  56352. var FileFaceOrientation = (function () {
  56353. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56354. this.name = name;
  56355. this.worldAxisForNormal = worldAxisForNormal;
  56356. this.worldAxisForFileX = worldAxisForFileX;
  56357. this.worldAxisForFileY = worldAxisForFileY;
  56358. }
  56359. return FileFaceOrientation;
  56360. }());
  56361. ;
  56362. /**
  56363. * Helper class dealing with the extraction of spherical polynomial dataArray
  56364. * from a cube map.
  56365. */
  56366. var CubeMapToSphericalPolynomialTools = (function () {
  56367. function CubeMapToSphericalPolynomialTools() {
  56368. }
  56369. /**
  56370. * Converts a texture to the according Spherical Polynomial data.
  56371. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56372. *
  56373. * @param texture The texture to extract the information from.
  56374. * @return The Spherical Polynomial data.
  56375. */
  56376. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  56377. if (!texture.isCube) {
  56378. // Only supports cube Textures currently.
  56379. return null;
  56380. }
  56381. var size = texture.getSize().width;
  56382. var right = texture.readPixels(0);
  56383. var left = texture.readPixels(1);
  56384. var up;
  56385. var down;
  56386. if (texture.isRenderTarget) {
  56387. up = texture.readPixels(3);
  56388. down = texture.readPixels(2);
  56389. }
  56390. else {
  56391. up = texture.readPixels(2);
  56392. down = texture.readPixels(3);
  56393. }
  56394. var front = texture.readPixels(4);
  56395. var back = texture.readPixels(5);
  56396. var gammaSpace = texture.gammaSpace;
  56397. // Always read as RGBA.
  56398. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  56399. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56400. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56401. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56402. }
  56403. var cubeInfo = {
  56404. size: size,
  56405. right: right,
  56406. left: left,
  56407. up: up,
  56408. down: down,
  56409. front: front,
  56410. back: back,
  56411. format: format,
  56412. type: type,
  56413. gammaSpace: gammaSpace,
  56414. };
  56415. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  56416. };
  56417. /**
  56418. * Converts a cubemap to the according Spherical Polynomial data.
  56419. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56420. *
  56421. * @param cubeInfo The Cube map to extract the information from.
  56422. * @return The Spherical Polynomial data.
  56423. */
  56424. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56425. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56426. var totalSolidAngle = 0.0;
  56427. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56428. var du = 2.0 / cubeInfo.size;
  56429. var dv = du;
  56430. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56431. var minUV = du * 0.5 - 1.0;
  56432. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56433. var fileFace = this.FileFaces[faceIndex];
  56434. var dataArray = cubeInfo[fileFace.name];
  56435. var v = minUV;
  56436. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56437. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56438. // Because SP is still linear, so summation is fine in that basis.
  56439. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  56440. for (var y = 0; y < cubeInfo.size; y++) {
  56441. var u = minUV;
  56442. for (var x = 0; x < cubeInfo.size; x++) {
  56443. // World direction (not normalised)
  56444. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56445. worldDirection.normalize();
  56446. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56447. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  56448. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  56449. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  56450. // Handle Integer types.
  56451. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56452. r /= 255;
  56453. g /= 255;
  56454. b /= 255;
  56455. }
  56456. // Handle Gamma space textures.
  56457. if (cubeInfo.gammaSpace) {
  56458. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  56459. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  56460. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  56461. }
  56462. var color = new BABYLON.Color3(r, g, b);
  56463. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56464. totalSolidAngle += deltaSolidAngle;
  56465. u += du;
  56466. }
  56467. v += dv;
  56468. }
  56469. }
  56470. // Solid angle for entire sphere is 4*pi
  56471. var sphereSolidAngle = 4.0 * Math.PI;
  56472. // Adjust the solid angle to allow for how many faces we processed.
  56473. var facesProcessed = 6.0;
  56474. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  56475. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  56476. // This is needed because the numerical integration over the cube uses a
  56477. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  56478. // and also to compensate for accumulative error due to float precision in the summation.
  56479. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  56480. sphericalHarmonics.scale(correctionFactor);
  56481. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  56482. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  56483. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56484. };
  56485. return CubeMapToSphericalPolynomialTools;
  56486. }());
  56487. CubeMapToSphericalPolynomialTools.FileFaces = [
  56488. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56489. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56490. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56491. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56492. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56493. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56494. ];
  56495. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56496. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56497. })(BABYLON || (BABYLON = {}));
  56498. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  56499. var BABYLON;
  56500. (function (BABYLON) {
  56501. var Internals;
  56502. (function (Internals) {
  56503. /**
  56504. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56505. */
  56506. var PanoramaToCubeMapTools = (function () {
  56507. function PanoramaToCubeMapTools() {
  56508. }
  56509. /**
  56510. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56511. *
  56512. * @param float32Array The source data.
  56513. * @param inputWidth The width of the input panorama.
  56514. * @param inputhHeight The height of the input panorama.
  56515. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56516. * @return The cubemap data
  56517. */
  56518. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56519. if (!float32Array) {
  56520. throw "ConvertPanoramaToCubemap: input cannot be null";
  56521. }
  56522. if (float32Array.length != inputWidth * inputHeight * 3) {
  56523. throw "ConvertPanoramaToCubemap: input size is wrong";
  56524. }
  56525. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56526. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56527. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56528. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56529. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56530. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56531. return {
  56532. front: textureFront,
  56533. back: textureBack,
  56534. left: textureLeft,
  56535. right: textureRight,
  56536. up: textureUp,
  56537. down: textureDown,
  56538. size: size,
  56539. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  56540. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  56541. gammaSpace: false,
  56542. };
  56543. };
  56544. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56545. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56546. var textureArray = new Float32Array(buffer);
  56547. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56548. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56549. var dy = 1 / texSize;
  56550. var fy = 0;
  56551. for (var y = 0; y < texSize; y++) {
  56552. var xv1 = faceData[0];
  56553. var xv2 = faceData[2];
  56554. for (var x = 0; x < texSize; x++) {
  56555. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56556. v.normalize();
  56557. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56558. // 3 channels per pixels
  56559. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56560. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56561. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56562. xv1 = xv1.add(rotDX1);
  56563. xv2 = xv2.add(rotDX2);
  56564. }
  56565. fy += dy;
  56566. }
  56567. return textureArray;
  56568. };
  56569. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56570. var theta = Math.atan2(vDir.z, vDir.x);
  56571. var phi = Math.acos(vDir.y);
  56572. while (theta < -Math.PI)
  56573. theta += 2 * Math.PI;
  56574. while (theta > Math.PI)
  56575. theta -= 2 * Math.PI;
  56576. var dx = theta / Math.PI;
  56577. var dy = phi / Math.PI;
  56578. // recenter.
  56579. dx = dx * 0.5 + 0.5;
  56580. var px = Math.round(dx * inputWidth);
  56581. if (px < 0)
  56582. px = 0;
  56583. else if (px >= inputWidth)
  56584. px = inputWidth - 1;
  56585. var py = Math.round(dy * inputHeight);
  56586. if (py < 0)
  56587. py = 0;
  56588. else if (py >= inputHeight)
  56589. py = inputHeight - 1;
  56590. var inputY = (inputHeight - py - 1);
  56591. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56592. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56593. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56594. return {
  56595. r: r,
  56596. g: g,
  56597. b: b
  56598. };
  56599. };
  56600. return PanoramaToCubeMapTools;
  56601. }());
  56602. PanoramaToCubeMapTools.FACE_FRONT = [
  56603. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56604. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56605. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56606. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56607. ];
  56608. PanoramaToCubeMapTools.FACE_BACK = [
  56609. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56610. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56611. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56612. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56613. ];
  56614. PanoramaToCubeMapTools.FACE_RIGHT = [
  56615. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56616. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56617. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56618. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56619. ];
  56620. PanoramaToCubeMapTools.FACE_LEFT = [
  56621. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56622. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56623. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56624. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56625. ];
  56626. PanoramaToCubeMapTools.FACE_DOWN = [
  56627. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56628. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56629. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56630. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56631. ];
  56632. PanoramaToCubeMapTools.FACE_UP = [
  56633. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56634. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56635. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56636. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56637. ];
  56638. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56639. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56640. })(BABYLON || (BABYLON = {}));
  56641. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  56642. var BABYLON;
  56643. (function (BABYLON) {
  56644. var Internals;
  56645. (function (Internals) {
  56646. ;
  56647. /**
  56648. * This groups tools to convert HDR texture to native colors array.
  56649. */
  56650. var HDRTools = (function () {
  56651. function HDRTools() {
  56652. }
  56653. HDRTools.Ldexp = function (mantissa, exponent) {
  56654. if (exponent > 1023) {
  56655. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56656. }
  56657. if (exponent < -1074) {
  56658. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56659. }
  56660. return mantissa * Math.pow(2, exponent);
  56661. };
  56662. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56663. if (exponent > 0) {
  56664. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56665. float32array[index + 0] = red * exponent;
  56666. float32array[index + 1] = green * exponent;
  56667. float32array[index + 2] = blue * exponent;
  56668. }
  56669. else {
  56670. float32array[index + 0] = 0;
  56671. float32array[index + 1] = 0;
  56672. float32array[index + 2] = 0;
  56673. }
  56674. };
  56675. HDRTools.readStringLine = function (uint8array, startIndex) {
  56676. var line = "";
  56677. var character = "";
  56678. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56679. character = String.fromCharCode(uint8array[i]);
  56680. if (character == "\n") {
  56681. break;
  56682. }
  56683. line += character;
  56684. }
  56685. return line;
  56686. };
  56687. /**
  56688. * Reads header information from an RGBE texture stored in a native array.
  56689. * More information on this format are available here:
  56690. * https://en.wikipedia.org/wiki/RGBE_image_format
  56691. *
  56692. * @param uint8array The binary file stored in native array.
  56693. * @return The header information.
  56694. */
  56695. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56696. var height = 0;
  56697. var width = 0;
  56698. var line = this.readStringLine(uint8array, 0);
  56699. if (line[0] != '#' || line[1] != '?') {
  56700. throw "Bad HDR Format.";
  56701. }
  56702. var endOfHeader = false;
  56703. var findFormat = false;
  56704. var lineIndex = 0;
  56705. do {
  56706. lineIndex += (line.length + 1);
  56707. line = this.readStringLine(uint8array, lineIndex);
  56708. if (line == "FORMAT=32-bit_rle_rgbe") {
  56709. findFormat = true;
  56710. }
  56711. else if (line.length == 0) {
  56712. endOfHeader = true;
  56713. }
  56714. } while (!endOfHeader);
  56715. if (!findFormat) {
  56716. throw "HDR Bad header format, unsupported FORMAT";
  56717. }
  56718. lineIndex += (line.length + 1);
  56719. line = this.readStringLine(uint8array, lineIndex);
  56720. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56721. var match = sizeRegexp.exec(line);
  56722. // TODO. Support +Y and -X if needed.
  56723. if (match.length < 3) {
  56724. throw "HDR Bad header format, no size";
  56725. }
  56726. width = parseInt(match[2]);
  56727. height = parseInt(match[1]);
  56728. if (width < 8 || width > 0x7fff) {
  56729. throw "HDR Bad header format, unsupported size";
  56730. }
  56731. lineIndex += (line.length + 1);
  56732. return {
  56733. height: height,
  56734. width: width,
  56735. dataPosition: lineIndex
  56736. };
  56737. };
  56738. /**
  56739. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56740. * This RGBE texture needs to store the information as a panorama.
  56741. *
  56742. * More information on this format are available here:
  56743. * https://en.wikipedia.org/wiki/RGBE_image_format
  56744. *
  56745. * @param buffer The binary file stored in an array buffer.
  56746. * @param size The expected size of the extracted cubemap.
  56747. * @return The Cube Map information.
  56748. */
  56749. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56750. var uint8array = new Uint8Array(buffer);
  56751. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56752. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56753. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56754. return cubeMapData;
  56755. };
  56756. /**
  56757. * Returns the pixels data extracted from an RGBE texture.
  56758. * This pixels will be stored left to right up to down in the R G B order in one array.
  56759. *
  56760. * More information on this format are available here:
  56761. * https://en.wikipedia.org/wiki/RGBE_image_format
  56762. *
  56763. * @param uint8array The binary file stored in an array buffer.
  56764. * @param hdrInfo The header information of the file.
  56765. * @return The pixels data in RGB right to left up to down order.
  56766. */
  56767. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56768. // Keep for multi format supports.
  56769. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56770. };
  56771. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56772. var num_scanlines = hdrInfo.height;
  56773. var scanline_width = hdrInfo.width;
  56774. var a, b, c, d, count;
  56775. var dataIndex = hdrInfo.dataPosition;
  56776. var index = 0, endIndex = 0, i = 0;
  56777. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56778. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56779. // 3 channels of 4 bytes per pixel in float.
  56780. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56781. var resultArray = new Float32Array(resultBuffer);
  56782. // read in each successive scanline
  56783. while (num_scanlines > 0) {
  56784. a = uint8array[dataIndex++];
  56785. b = uint8array[dataIndex++];
  56786. c = uint8array[dataIndex++];
  56787. d = uint8array[dataIndex++];
  56788. if (a != 2 || b != 2 || (c & 0x80)) {
  56789. // this file is not run length encoded
  56790. throw "HDR Bad header format, not RLE";
  56791. }
  56792. if (((c << 8) | d) != scanline_width) {
  56793. throw "HDR Bad header format, wrong scan line width";
  56794. }
  56795. index = 0;
  56796. // read each of the four channels for the scanline into the buffer
  56797. for (i = 0; i < 4; i++) {
  56798. endIndex = (i + 1) * scanline_width;
  56799. while (index < endIndex) {
  56800. a = uint8array[dataIndex++];
  56801. b = uint8array[dataIndex++];
  56802. if (a > 128) {
  56803. // a run of the same value
  56804. count = a - 128;
  56805. if ((count == 0) || (count > endIndex - index)) {
  56806. throw "HDR Bad Format, bad scanline data (run)";
  56807. }
  56808. while (count-- > 0) {
  56809. scanLineArray[index++] = b;
  56810. }
  56811. }
  56812. else {
  56813. // a non-run
  56814. count = a;
  56815. if ((count == 0) || (count > endIndex - index)) {
  56816. throw "HDR Bad Format, bad scanline data (non-run)";
  56817. }
  56818. scanLineArray[index++] = b;
  56819. if (--count > 0) {
  56820. for (var j = 0; j < count; j++) {
  56821. scanLineArray[index++] = uint8array[dataIndex++];
  56822. }
  56823. }
  56824. }
  56825. }
  56826. }
  56827. // now convert data from buffer into floats
  56828. for (i = 0; i < scanline_width; i++) {
  56829. a = scanLineArray[i];
  56830. b = scanLineArray[i + scanline_width];
  56831. c = scanLineArray[i + 2 * scanline_width];
  56832. d = scanLineArray[i + 3 * scanline_width];
  56833. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  56834. }
  56835. num_scanlines--;
  56836. }
  56837. return resultArray;
  56838. };
  56839. return HDRTools;
  56840. }());
  56841. Internals.HDRTools = HDRTools;
  56842. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56843. })(BABYLON || (BABYLON = {}));
  56844. //# sourceMappingURL=babylon.hdr.js.map
  56845. var BABYLON;
  56846. (function (BABYLON) {
  56847. /**
  56848. * This represents a texture coming from an HDR input.
  56849. *
  56850. * The only supported format is currently panorama picture stored in RGBE format.
  56851. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56852. */
  56853. var HDRCubeTexture = (function (_super) {
  56854. __extends(HDRCubeTexture, _super);
  56855. /**
  56856. * Instantiates an HDRTexture from the following parameters.
  56857. *
  56858. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56859. * @param scene The scene the texture will be used in
  56860. * @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.
  56861. * @param noMipmap Forces to not generate the mipmap if true
  56862. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56863. * @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)
  56864. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56865. */
  56866. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56867. if (noMipmap === void 0) { noMipmap = false; }
  56868. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56869. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56870. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56871. if (onLoad === void 0) { onLoad = null; }
  56872. if (onError === void 0) { onError = null; }
  56873. var _this = _super.call(this, scene) || this;
  56874. _this._useInGammaSpace = false;
  56875. _this._generateHarmonics = true;
  56876. _this._isBABYLONPreprocessed = false;
  56877. _this._onLoad = null;
  56878. _this._onError = null;
  56879. /**
  56880. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56881. */
  56882. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56883. /**
  56884. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56885. * This is usefull at run time to apply the good shader.
  56886. */
  56887. _this.isPMREM = false;
  56888. _this._isBlocking = true;
  56889. if (!url) {
  56890. return _this;
  56891. }
  56892. _this.name = url;
  56893. _this.url = url;
  56894. _this.hasAlpha = false;
  56895. _this.isCube = true;
  56896. _this._textureMatrix = BABYLON.Matrix.Identity();
  56897. _this._onLoad = onLoad;
  56898. _this._onError = onError;
  56899. _this.gammaSpace = false;
  56900. if (size) {
  56901. _this._isBABYLONPreprocessed = false;
  56902. _this._noMipmap = noMipmap;
  56903. _this._size = size;
  56904. _this._useInGammaSpace = useInGammaSpace;
  56905. _this._usePMREMGenerator = usePMREMGenerator &&
  56906. scene.getEngine().getCaps().textureLOD &&
  56907. _this.getScene().getEngine().getCaps().textureFloat &&
  56908. !_this._useInGammaSpace;
  56909. }
  56910. else {
  56911. _this._isBABYLONPreprocessed = true;
  56912. _this._noMipmap = false;
  56913. _this._useInGammaSpace = false;
  56914. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56915. _this.getScene().getEngine().getCaps().textureFloat &&
  56916. !_this._useInGammaSpace;
  56917. }
  56918. _this.isPMREM = _this._usePMREMGenerator;
  56919. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56920. if (!_this._texture) {
  56921. if (!scene.useDelayedTextureLoading) {
  56922. _this.loadTexture();
  56923. }
  56924. else {
  56925. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56926. }
  56927. }
  56928. return _this;
  56929. }
  56930. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  56931. /**
  56932. * Gets wether or not the texture is blocking during loading.
  56933. */
  56934. get: function () {
  56935. return this._isBlocking;
  56936. },
  56937. /**
  56938. * Sets wether or not the texture is blocking during loading.
  56939. */
  56940. set: function (value) {
  56941. this._isBlocking = value;
  56942. },
  56943. enumerable: true,
  56944. configurable: true
  56945. });
  56946. /**
  56947. * Occurs when the file is a preprocessed .babylon.hdr file.
  56948. */
  56949. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56950. var _this = this;
  56951. var mipLevels = 0;
  56952. var floatArrayView = null;
  56953. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56954. var mips = [];
  56955. var startIndex = 30;
  56956. for (var level = 0; level < mipLevels; level++) {
  56957. mips.push([]);
  56958. // Fill each pixel of the mip level.
  56959. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56960. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56961. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56962. mips[level].push(faceData);
  56963. startIndex += faceSize;
  56964. }
  56965. }
  56966. return mips;
  56967. } : null;
  56968. var callback = function (buffer) {
  56969. // Create Native Array Views
  56970. var intArrayView = new Int32Array(buffer);
  56971. floatArrayView = new Float32Array(buffer);
  56972. // Fill header.
  56973. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56974. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56975. // Update Texture Information.
  56976. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56977. // Fill polynomial information.
  56978. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56979. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56980. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56981. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56982. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56983. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56984. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56985. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56986. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56987. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56988. _this.sphericalPolynomial = sphericalPolynomial;
  56989. // Fill pixel data.
  56990. mipLevels = intArrayView[29]; // Number of mip levels.
  56991. var startIndex = 30;
  56992. var data = [];
  56993. var faceSize = Math.pow(_this._size, 2) * 3;
  56994. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56995. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56996. startIndex += faceSize;
  56997. }
  56998. var results = [];
  56999. var byteArray = null;
  57000. // Push each faces.
  57001. for (var k = 0; k < 6; k++) {
  57002. var dataFace = null;
  57003. // To be deprecated.
  57004. if (version === 1) {
  57005. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  57006. dataFace = data[j];
  57007. }
  57008. // If special cases.
  57009. if (!mipmapGenerator) {
  57010. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57011. // 3 channels of 1 bytes per pixel in bytes.
  57012. var byteBuffer = new ArrayBuffer(faceSize);
  57013. byteArray = new Uint8Array(byteBuffer);
  57014. }
  57015. for (var i = 0; i < _this._size * _this._size; i++) {
  57016. // Put in gamma space if requested.
  57017. if (_this._useInGammaSpace) {
  57018. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57019. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57020. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57021. }
  57022. // Convert to int texture for fallback.
  57023. if (byteArray) {
  57024. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57025. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57026. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57027. // May use luminance instead if the result is not accurate.
  57028. var max = Math.max(Math.max(r, g), b);
  57029. if (max > 255) {
  57030. var scale = 255 / max;
  57031. r *= scale;
  57032. g *= scale;
  57033. b *= scale;
  57034. }
  57035. byteArray[(i * 3) + 0] = r;
  57036. byteArray[(i * 3) + 1] = g;
  57037. byteArray[(i * 3) + 2] = b;
  57038. }
  57039. }
  57040. }
  57041. // Fill the array accordingly.
  57042. if (byteArray) {
  57043. results.push(byteArray);
  57044. }
  57045. else {
  57046. results.push(dataFace);
  57047. }
  57048. }
  57049. return results;
  57050. };
  57051. 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);
  57052. };
  57053. /**
  57054. * Occurs when the file is raw .hdr file.
  57055. */
  57056. HDRCubeTexture.prototype.loadHDRTexture = function () {
  57057. var _this = this;
  57058. var callback = function (buffer) {
  57059. // Extract the raw linear data.
  57060. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  57061. // Generate harmonics if needed.
  57062. if (_this._generateHarmonics) {
  57063. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  57064. _this.sphericalPolynomial = sphericalPolynomial;
  57065. }
  57066. var results = [];
  57067. var byteArray = null;
  57068. // Push each faces.
  57069. for (var j = 0; j < 6; j++) {
  57070. // Create uintarray fallback.
  57071. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57072. // 3 channels of 1 bytes per pixel in bytes.
  57073. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  57074. byteArray = new Uint8Array(byteBuffer);
  57075. }
  57076. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  57077. // If special cases.
  57078. if (_this._useInGammaSpace || byteArray) {
  57079. for (var i = 0; i < _this._size * _this._size; i++) {
  57080. // Put in gamma space if requested.
  57081. if (_this._useInGammaSpace) {
  57082. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57083. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57084. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57085. }
  57086. // Convert to int texture for fallback.
  57087. if (byteArray) {
  57088. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57089. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57090. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57091. // May use luminance instead if the result is not accurate.
  57092. var max = Math.max(Math.max(r, g), b);
  57093. if (max > 255) {
  57094. var scale = 255 / max;
  57095. r *= scale;
  57096. g *= scale;
  57097. b *= scale;
  57098. }
  57099. byteArray[(i * 3) + 0] = r;
  57100. byteArray[(i * 3) + 1] = g;
  57101. byteArray[(i * 3) + 2] = b;
  57102. }
  57103. }
  57104. }
  57105. if (byteArray) {
  57106. results.push(byteArray);
  57107. }
  57108. else {
  57109. results.push(dataFace);
  57110. }
  57111. }
  57112. return results;
  57113. };
  57114. var mipmapGenerator = null;
  57115. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  57116. // if (!this._noMipmap &&
  57117. // this._usePMREMGenerator) {
  57118. // mipmapGenerator = (data: ArrayBufferView[]) => {
  57119. // // Custom setup of the generator matching with the PBR shader values.
  57120. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  57121. // this._size,
  57122. // this._size,
  57123. // 0,
  57124. // 3,
  57125. // this.getScene().getEngine().getCaps().textureFloat,
  57126. // 2048,
  57127. // 0.25,
  57128. // false,
  57129. // true);
  57130. // return generator.filterCubeMap();
  57131. // };
  57132. // }
  57133. 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);
  57134. };
  57135. /**
  57136. * Starts the loading process of the texture.
  57137. */
  57138. HDRCubeTexture.prototype.loadTexture = function () {
  57139. if (this._isBABYLONPreprocessed) {
  57140. this.loadBabylonTexture();
  57141. }
  57142. else {
  57143. this.loadHDRTexture();
  57144. }
  57145. };
  57146. HDRCubeTexture.prototype.clone = function () {
  57147. var size = this._isBABYLONPreprocessed ? null : this._size;
  57148. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  57149. // Base texture
  57150. newTexture.level = this.level;
  57151. newTexture.wrapU = this.wrapU;
  57152. newTexture.wrapV = this.wrapV;
  57153. newTexture.coordinatesIndex = this.coordinatesIndex;
  57154. newTexture.coordinatesMode = this.coordinatesMode;
  57155. return newTexture;
  57156. };
  57157. // Methods
  57158. HDRCubeTexture.prototype.delayLoad = function () {
  57159. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57160. return;
  57161. }
  57162. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57163. this._texture = this._getFromCache(this.url, this._noMipmap);
  57164. if (!this._texture) {
  57165. this.loadTexture();
  57166. }
  57167. };
  57168. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  57169. return this._textureMatrix;
  57170. };
  57171. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57172. this._textureMatrix = value;
  57173. };
  57174. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57175. var texture = null;
  57176. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57177. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  57178. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  57179. texture.name = parsedTexture.name;
  57180. texture.hasAlpha = parsedTexture.hasAlpha;
  57181. texture.level = parsedTexture.level;
  57182. texture.coordinatesMode = parsedTexture.coordinatesMode;
  57183. texture.isBlocking = parsedTexture.isBlocking;
  57184. }
  57185. return texture;
  57186. };
  57187. HDRCubeTexture.prototype.serialize = function () {
  57188. if (!this.name) {
  57189. return null;
  57190. }
  57191. var serializationObject = {};
  57192. serializationObject.name = this.name;
  57193. serializationObject.hasAlpha = this.hasAlpha;
  57194. serializationObject.isCube = true;
  57195. serializationObject.level = this.level;
  57196. serializationObject.size = this._size;
  57197. serializationObject.coordinatesMode = this.coordinatesMode;
  57198. serializationObject.useInGammaSpace = this._useInGammaSpace;
  57199. serializationObject.generateHarmonics = this._generateHarmonics;
  57200. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  57201. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  57202. serializationObject.customType = "BABYLON.HDRCubeTexture";
  57203. serializationObject.noMipmap = this._noMipmap;
  57204. serializationObject.isBlocking = this._isBlocking;
  57205. return serializationObject;
  57206. };
  57207. /**
  57208. * Saves as a file the data contained in the texture in a binary format.
  57209. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57210. * as the spherical used in the lighting.
  57211. * @param url The HDR file url.
  57212. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57213. * @param onError Method called if any error happens during download.
  57214. * @return The packed binary data.
  57215. */
  57216. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  57217. if (onError === void 0) { onError = null; }
  57218. var callback = function (buffer) {
  57219. var data = new Blob([buffer], { type: 'application/octet-stream' });
  57220. // Returns a URL you can use as a href.
  57221. var objUrl = window.URL.createObjectURL(data);
  57222. // Simulates a link to it and click to dowload.
  57223. var a = document.createElement("a");
  57224. document.body.appendChild(a);
  57225. a.style.display = "none";
  57226. a.href = objUrl;
  57227. a.download = "envmap.babylon.hdr";
  57228. a.click();
  57229. };
  57230. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  57231. };
  57232. /**
  57233. * Serializes the data contained in the texture in a binary format.
  57234. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57235. * as the spherical used in the lighting.
  57236. * @param url The HDR file url.
  57237. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57238. * @param onError Method called if any error happens during download.
  57239. * @return The packed binary data.
  57240. */
  57241. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  57242. if (onError === void 0) { onError = null; }
  57243. // Needs the url tho create the texture.
  57244. if (!url) {
  57245. return null;
  57246. }
  57247. // Check Power of two size.
  57248. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  57249. return null;
  57250. }
  57251. // Coming Back in 3.1.
  57252. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  57253. return null;
  57254. };
  57255. return HDRCubeTexture;
  57256. }(BABYLON.BaseTexture));
  57257. HDRCubeTexture._facesMapping = [
  57258. "right",
  57259. "left",
  57260. "up",
  57261. "down",
  57262. "front",
  57263. "back"
  57264. ];
  57265. BABYLON.HDRCubeTexture = HDRCubeTexture;
  57266. })(BABYLON || (BABYLON = {}));
  57267. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  57268. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  57269. // Huge respect for a such great lib.
  57270. // Earcut license:
  57271. // Copyright (c) 2016, Mapbox
  57272. //
  57273. // Permission to use, copy, modify, and/or distribute this software for any purpose
  57274. // with or without fee is hereby granted, provided that the above copyright notice
  57275. // and this permission notice appear in all copies.
  57276. //
  57277. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  57278. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  57279. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  57280. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  57281. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  57282. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  57283. // THIS SOFTWARE.
  57284. var Earcut;
  57285. (function (Earcut) {
  57286. /**
  57287. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  57288. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  57289. * @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).
  57290. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  57291. */
  57292. function earcut(data, holeIndices, dim) {
  57293. dim = dim || 2;
  57294. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  57295. if (!outerNode)
  57296. return triangles;
  57297. var minX, minY, maxX, maxY, x, y, size;
  57298. if (hasHoles)
  57299. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  57300. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  57301. if (data.length > 80 * dim) {
  57302. minX = maxX = data[0];
  57303. minY = maxY = data[1];
  57304. for (var i = dim; i < outerLen; i += dim) {
  57305. x = data[i];
  57306. y = data[i + 1];
  57307. if (x < minX)
  57308. minX = x;
  57309. if (y < minY)
  57310. minY = y;
  57311. if (x > maxX)
  57312. maxX = x;
  57313. if (y > maxY)
  57314. maxY = y;
  57315. }
  57316. // minX, minY and size are later used to transform coords into integers for z-order calculation
  57317. size = Math.max(maxX - minX, maxY - minY);
  57318. }
  57319. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  57320. return triangles;
  57321. }
  57322. Earcut.earcut = earcut;
  57323. // create a circular doubly linked list from polygon points in the specified winding order
  57324. function linkedList(data, start, end, dim, clockwise) {
  57325. var i, last;
  57326. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  57327. for (i = start; i < end; i += dim)
  57328. last = insertNode(i, data[i], data[i + 1], last);
  57329. }
  57330. else {
  57331. for (i = end - dim; i >= start; i -= dim)
  57332. last = insertNode(i, data[i], data[i + 1], last);
  57333. }
  57334. if (last && equals(last, last.next)) {
  57335. removeNode(last);
  57336. last = last.next;
  57337. }
  57338. return last;
  57339. }
  57340. // eliminate colinear or duplicate points
  57341. function filterPoints(start, end) {
  57342. if (!start)
  57343. return start;
  57344. if (!end)
  57345. end = start;
  57346. var p = start, again;
  57347. do {
  57348. again = false;
  57349. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  57350. removeNode(p);
  57351. p = end = p.prev;
  57352. if (p === p.next)
  57353. return null;
  57354. again = true;
  57355. }
  57356. else {
  57357. p = p.next;
  57358. }
  57359. } while (again || p !== end);
  57360. return end;
  57361. }
  57362. // main ear slicing loop which triangulates a polygon (given as a linked list)
  57363. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  57364. if (!ear)
  57365. return;
  57366. // interlink polygon nodes in z-order
  57367. if (!pass && size)
  57368. indexCurve(ear, minX, minY, size);
  57369. var stop = ear, prev, next;
  57370. // iterate through ears, slicing them one by one
  57371. while (ear.prev !== ear.next) {
  57372. prev = ear.prev;
  57373. next = ear.next;
  57374. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  57375. // cut off the triangle
  57376. triangles.push(prev.i / dim);
  57377. triangles.push(ear.i / dim);
  57378. triangles.push(next.i / dim);
  57379. removeNode(ear);
  57380. // skipping the next vertice leads to less sliver triangles
  57381. ear = next.next;
  57382. stop = next.next;
  57383. continue;
  57384. }
  57385. ear = next;
  57386. // if we looped through the whole remaining polygon and can't find any more ears
  57387. if (ear === stop) {
  57388. // try filtering points and slicing again
  57389. if (!pass) {
  57390. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  57391. // if this didn't work, try curing all small self-intersections locally
  57392. }
  57393. else if (pass === 1) {
  57394. ear = cureLocalIntersections(ear, triangles, dim);
  57395. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  57396. // as a last resort, try splitting the remaining polygon into two
  57397. }
  57398. else if (pass === 2) {
  57399. splitEarcut(ear, triangles, dim, minX, minY, size);
  57400. }
  57401. break;
  57402. }
  57403. }
  57404. }
  57405. // check whether a polygon node forms a valid ear with adjacent nodes
  57406. function isEar(ear) {
  57407. var a = ear.prev, b = ear, c = ear.next;
  57408. if (area(a, b, c) >= 0)
  57409. return false; // reflex, can't be an ear
  57410. // now make sure we don't have other points inside the potential ear
  57411. var p = ear.next.next;
  57412. while (p !== ear.prev) {
  57413. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57414. area(p.prev, p, p.next) >= 0)
  57415. return false;
  57416. p = p.next;
  57417. }
  57418. return true;
  57419. }
  57420. function isEarHashed(ear, minX, minY, size) {
  57421. var a = ear.prev, b = ear, c = ear.next;
  57422. if (area(a, b, c) >= 0)
  57423. return false; // reflex, can't be an ear
  57424. // triangle bbox; min & max are calculated like this for speed
  57425. 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);
  57426. // z-order range for the current triangle bbox;
  57427. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  57428. // first look for points inside the triangle in increasing z-order
  57429. var p = ear.nextZ;
  57430. while (p && p.z <= maxZ) {
  57431. if (p !== ear.prev &&
  57432. p !== ear.next &&
  57433. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57434. area(p.prev, p, p.next) >= 0)
  57435. return false;
  57436. p = p.nextZ;
  57437. }
  57438. // then look for points in decreasing z-order
  57439. p = ear.prevZ;
  57440. while (p && p.z >= minZ) {
  57441. if (p !== ear.prev &&
  57442. p !== ear.next &&
  57443. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57444. area(p.prev, p, p.next) >= 0)
  57445. return false;
  57446. p = p.prevZ;
  57447. }
  57448. return true;
  57449. }
  57450. // go through all polygon nodes and cure small local self-intersections
  57451. function cureLocalIntersections(start, triangles, dim) {
  57452. var p = start;
  57453. do {
  57454. var a = p.prev, b = p.next.next;
  57455. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  57456. triangles.push(a.i / dim);
  57457. triangles.push(p.i / dim);
  57458. triangles.push(b.i / dim);
  57459. // remove two nodes involved
  57460. removeNode(p);
  57461. removeNode(p.next);
  57462. p = start = b;
  57463. }
  57464. p = p.next;
  57465. } while (p !== start);
  57466. return p;
  57467. }
  57468. // try splitting polygon into two and triangulate them independently
  57469. function splitEarcut(start, triangles, dim, minX, minY, size) {
  57470. // look for a valid diagonal that divides the polygon into two
  57471. var a = start;
  57472. do {
  57473. var b = a.next.next;
  57474. while (b !== a.prev) {
  57475. if (a.i !== b.i && isValidDiagonal(a, b)) {
  57476. // split the polygon in two by the diagonal
  57477. var c = splitPolygon(a, b);
  57478. // filter colinear points around the cuts
  57479. a = filterPoints(a, a.next);
  57480. c = filterPoints(c, c.next);
  57481. // run earcut on each half
  57482. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  57483. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  57484. return;
  57485. }
  57486. b = b.next;
  57487. }
  57488. a = a.next;
  57489. } while (a !== start);
  57490. }
  57491. // link every hole into the outer loop, producing a single-ring polygon without holes
  57492. function eliminateHoles(data, holeIndices, outerNode, dim) {
  57493. var queue = [], i, len, start, end, list;
  57494. for (i = 0, len = holeIndices.length; i < len; i++) {
  57495. start = holeIndices[i] * dim;
  57496. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57497. list = linkedList(data, start, end, dim, false);
  57498. if (list === list.next)
  57499. list.steiner = true;
  57500. queue.push(getLeftmost(list));
  57501. }
  57502. queue.sort(compareX);
  57503. // process holes from left to right
  57504. for (i = 0; i < queue.length; i++) {
  57505. eliminateHole(queue[i], outerNode);
  57506. outerNode = filterPoints(outerNode, outerNode.next);
  57507. }
  57508. return outerNode;
  57509. }
  57510. function compareX(a, b) {
  57511. return a.x - b.x;
  57512. }
  57513. // find a bridge between vertices that connects hole with an outer ring and and link it
  57514. function eliminateHole(hole, outerNode) {
  57515. outerNode = findHoleBridge(hole, outerNode);
  57516. if (outerNode) {
  57517. var b = splitPolygon(outerNode, hole);
  57518. filterPoints(b, b.next);
  57519. }
  57520. }
  57521. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  57522. function findHoleBridge(hole, outerNode) {
  57523. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  57524. // find a segment intersected by a ray from the hole's leftmost point to the left;
  57525. // segment's endpoint with lesser x will be potential connection point
  57526. do {
  57527. if (hy <= p.y && hy >= p.next.y) {
  57528. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  57529. if (x <= hx && x > qx) {
  57530. qx = x;
  57531. if (x === hx) {
  57532. if (hy === p.y)
  57533. return p;
  57534. if (hy === p.next.y)
  57535. return p.next;
  57536. }
  57537. m = p.x < p.next.x ? p : p.next;
  57538. }
  57539. }
  57540. p = p.next;
  57541. } while (p !== outerNode);
  57542. if (!m)
  57543. return null;
  57544. if (hx === qx)
  57545. return m.prev; // hole touches outer segment; pick lower endpoint
  57546. // look for points inside the triangle of hole point, segment intersection and endpoint;
  57547. // if there are no points found, we have a valid connection;
  57548. // otherwise choose the point of the minimum angle with the ray as connection point
  57549. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  57550. p = m.next;
  57551. while (p !== stop) {
  57552. if (hx >= p.x &&
  57553. p.x >= mx &&
  57554. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  57555. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  57556. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  57557. m = p;
  57558. tanMin = tan;
  57559. }
  57560. }
  57561. p = p.next;
  57562. }
  57563. return m;
  57564. }
  57565. // interlink polygon nodes in z-order
  57566. function indexCurve(start, minX, minY, size) {
  57567. var p = start;
  57568. do {
  57569. if (p.z === null)
  57570. p.z = zOrder(p.x, p.y, minX, minY, size);
  57571. p.prevZ = p.prev;
  57572. p.nextZ = p.next;
  57573. p = p.next;
  57574. } while (p !== start);
  57575. p.prevZ.nextZ = null;
  57576. p.prevZ = null;
  57577. sortLinked(p);
  57578. }
  57579. // Simon Tatham's linked list merge sort algorithm
  57580. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  57581. function sortLinked(list) {
  57582. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  57583. do {
  57584. p = list;
  57585. list = null;
  57586. tail = null;
  57587. numMerges = 0;
  57588. while (p) {
  57589. numMerges++;
  57590. q = p;
  57591. pSize = 0;
  57592. for (i = 0; i < inSize; i++) {
  57593. pSize++;
  57594. q = q.nextZ;
  57595. if (!q)
  57596. break;
  57597. }
  57598. qSize = inSize;
  57599. while (pSize > 0 || (qSize > 0 && q)) {
  57600. if (pSize === 0) {
  57601. e = q;
  57602. q = q.nextZ;
  57603. qSize--;
  57604. }
  57605. else if (qSize === 0 || !q) {
  57606. e = p;
  57607. p = p.nextZ;
  57608. pSize--;
  57609. }
  57610. else if (p.z <= q.z) {
  57611. e = p;
  57612. p = p.nextZ;
  57613. pSize--;
  57614. }
  57615. else {
  57616. e = q;
  57617. q = q.nextZ;
  57618. qSize--;
  57619. }
  57620. if (tail)
  57621. tail.nextZ = e;
  57622. else
  57623. list = e;
  57624. e.prevZ = tail;
  57625. tail = e;
  57626. }
  57627. p = q;
  57628. }
  57629. tail.nextZ = null;
  57630. inSize *= 2;
  57631. } while (numMerges > 1);
  57632. return list;
  57633. }
  57634. // z-order of a point given coords and size of the data bounding box
  57635. function zOrder(x, y, minX, minY, size) {
  57636. // coords are transformed into non-negative 15-bit integer range
  57637. x = 32767 * (x - minX) / size;
  57638. y = 32767 * (y - minY) / size;
  57639. x = (x | (x << 8)) & 0x00FF00FF;
  57640. x = (x | (x << 4)) & 0x0F0F0F0F;
  57641. x = (x | (x << 2)) & 0x33333333;
  57642. x = (x | (x << 1)) & 0x55555555;
  57643. y = (y | (y << 8)) & 0x00FF00FF;
  57644. y = (y | (y << 4)) & 0x0F0F0F0F;
  57645. y = (y | (y << 2)) & 0x33333333;
  57646. y = (y | (y << 1)) & 0x55555555;
  57647. return x | (y << 1);
  57648. }
  57649. // find the leftmost node of a polygon ring
  57650. function getLeftmost(start) {
  57651. var p = start, leftmost = start;
  57652. do {
  57653. if (p.x < leftmost.x)
  57654. leftmost = p;
  57655. p = p.next;
  57656. } while (p !== start);
  57657. return leftmost;
  57658. }
  57659. // check if a point lies within a convex triangle
  57660. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  57661. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  57662. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  57663. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  57664. }
  57665. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  57666. function isValidDiagonal(a, b) {
  57667. return a.next.i !== b.i &&
  57668. a.prev.i !== b.i &&
  57669. !intersectsPolygon(a, b) &&
  57670. locallyInside(a, b) &&
  57671. locallyInside(b, a) &&
  57672. middleInside(a, b);
  57673. }
  57674. // signed area of a triangle
  57675. function area(p, q, r) {
  57676. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  57677. }
  57678. // check if two points are equal
  57679. function equals(p1, p2) {
  57680. return p1.x === p2.x && p1.y === p2.y;
  57681. }
  57682. // check if two segments intersect
  57683. function intersects(p1, q1, p2, q2) {
  57684. if ((equals(p1, q1) && equals(p2, q2)) ||
  57685. (equals(p1, q2) && equals(p2, q1)))
  57686. return true;
  57687. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  57688. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  57689. }
  57690. // check if a polygon diagonal intersects any polygon segments
  57691. function intersectsPolygon(a, b) {
  57692. var p = a;
  57693. do {
  57694. if (p.i !== a.i &&
  57695. p.next.i !== a.i &&
  57696. p.i !== b.i &&
  57697. p.next.i !== b.i &&
  57698. intersects(p, p.next, a, b))
  57699. return true;
  57700. p = p.next;
  57701. } while (p !== a);
  57702. return false;
  57703. }
  57704. // check if a polygon diagonal is locally inside the polygon
  57705. function locallyInside(a, b) {
  57706. return area(a.prev, a, a.next) < 0
  57707. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  57708. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  57709. }
  57710. // check if the middle point of a polygon diagonal is inside the polygon
  57711. function middleInside(a, b) {
  57712. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  57713. do {
  57714. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  57715. inside = !inside;
  57716. p = p.next;
  57717. } while (p !== a);
  57718. return inside;
  57719. }
  57720. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  57721. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  57722. function splitPolygon(a, b) {
  57723. 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;
  57724. a.next = b;
  57725. b.prev = a;
  57726. a2.next = an;
  57727. an.prev = a2;
  57728. b2.next = a2;
  57729. a2.prev = b2;
  57730. bp.next = b2;
  57731. b2.prev = bp;
  57732. return b2;
  57733. }
  57734. // create a node and optionally link it with previous one (in a circular doubly linked list)
  57735. function insertNode(i, x, y, last) {
  57736. var p = new Node(i, x, y);
  57737. if (!last) {
  57738. p.prev = p;
  57739. p.next = p;
  57740. }
  57741. else {
  57742. p.next = last.next;
  57743. p.prev = last;
  57744. last.next.prev = p;
  57745. last.next = p;
  57746. }
  57747. return p;
  57748. }
  57749. function removeNode(p) {
  57750. p.next.prev = p.prev;
  57751. p.prev.next = p.next;
  57752. if (p.prevZ)
  57753. p.prevZ.nextZ = p.nextZ;
  57754. if (p.nextZ)
  57755. p.nextZ.prevZ = p.prevZ;
  57756. }
  57757. function Node(i, x, y) {
  57758. // vertice index in coordinates array
  57759. this.i = i;
  57760. // vertex coordinates
  57761. this.x = x;
  57762. this.y = y;
  57763. // previous and next vertice nodes in a polygon ring
  57764. this.prev = null;
  57765. this.next = null;
  57766. // z-order curve value
  57767. this.z = null;
  57768. // previous and next nodes in z-order
  57769. this.prevZ = null;
  57770. this.nextZ = null;
  57771. // indicates whether this is a steiner point
  57772. this.steiner = false;
  57773. }
  57774. /**
  57775. * return a percentage difference between the polygon area and its triangulation area;
  57776. * used to verify correctness of triangulation
  57777. */
  57778. function deviation(data, holeIndices, dim, triangles) {
  57779. var hasHoles = holeIndices && holeIndices.length;
  57780. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  57781. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  57782. if (hasHoles) {
  57783. for (var i = 0, len = holeIndices.length; i < len; i++) {
  57784. var start = holeIndices[i] * dim;
  57785. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57786. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  57787. }
  57788. }
  57789. var trianglesArea = 0;
  57790. for (i = 0; i < triangles.length; i += 3) {
  57791. var a = triangles[i] * dim;
  57792. var b = triangles[i + 1] * dim;
  57793. var c = triangles[i + 2] * dim;
  57794. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  57795. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  57796. }
  57797. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  57798. }
  57799. Earcut.deviation = deviation;
  57800. ;
  57801. function signedArea(data, start, end, dim) {
  57802. var sum = 0;
  57803. for (var i = start, j = end - dim; i < end; i += dim) {
  57804. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  57805. j = i;
  57806. }
  57807. return sum;
  57808. }
  57809. /**
  57810. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  57811. */
  57812. function flatten(data) {
  57813. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  57814. for (var i = 0; i < data.length; i++) {
  57815. for (var j = 0; j < data[i].length; j++) {
  57816. for (var d = 0; d < dim; d++)
  57817. result.vertices.push(data[i][j][d]);
  57818. }
  57819. if (i > 0) {
  57820. holeIndex += data[i - 1].length;
  57821. result.holes.push(holeIndex);
  57822. }
  57823. }
  57824. return result;
  57825. }
  57826. Earcut.flatten = flatten;
  57827. ;
  57828. })(Earcut || (Earcut = {}));
  57829. //# sourceMappingURL=babylon.earcut.js.map
  57830. /// <reference path="..\Math\babylon.math.ts" />
  57831. var BABYLON;
  57832. (function (BABYLON) {
  57833. var IndexedVector2 = (function (_super) {
  57834. __extends(IndexedVector2, _super);
  57835. function IndexedVector2(original, index) {
  57836. var _this = _super.call(this, original.x, original.y) || this;
  57837. _this.index = index;
  57838. return _this;
  57839. }
  57840. return IndexedVector2;
  57841. }(BABYLON.Vector2));
  57842. var PolygonPoints = (function () {
  57843. function PolygonPoints() {
  57844. this.elements = new Array();
  57845. }
  57846. PolygonPoints.prototype.add = function (originalPoints) {
  57847. var _this = this;
  57848. var result = new Array();
  57849. originalPoints.forEach(function (point) {
  57850. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  57851. var newPoint = new IndexedVector2(point, _this.elements.length);
  57852. result.push(newPoint);
  57853. _this.elements.push(newPoint);
  57854. }
  57855. });
  57856. return result;
  57857. };
  57858. PolygonPoints.prototype.computeBounds = function () {
  57859. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57860. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  57861. this.elements.forEach(function (point) {
  57862. // x
  57863. if (point.x < lmin.x) {
  57864. lmin.x = point.x;
  57865. }
  57866. else if (point.x > lmax.x) {
  57867. lmax.x = point.x;
  57868. }
  57869. // y
  57870. if (point.y < lmin.y) {
  57871. lmin.y = point.y;
  57872. }
  57873. else if (point.y > lmax.y) {
  57874. lmax.y = point.y;
  57875. }
  57876. });
  57877. return {
  57878. min: lmin,
  57879. max: lmax,
  57880. width: lmax.x - lmin.x,
  57881. height: lmax.y - lmin.y
  57882. };
  57883. };
  57884. return PolygonPoints;
  57885. }());
  57886. var Polygon = (function () {
  57887. function Polygon() {
  57888. }
  57889. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  57890. return [
  57891. new BABYLON.Vector2(xmin, ymin),
  57892. new BABYLON.Vector2(xmax, ymin),
  57893. new BABYLON.Vector2(xmax, ymax),
  57894. new BABYLON.Vector2(xmin, ymax)
  57895. ];
  57896. };
  57897. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  57898. if (cx === void 0) { cx = 0; }
  57899. if (cy === void 0) { cy = 0; }
  57900. if (numberOfSides === void 0) { numberOfSides = 32; }
  57901. var result = new Array();
  57902. var angle = 0;
  57903. var increment = (Math.PI * 2) / numberOfSides;
  57904. for (var i = 0; i < numberOfSides; i++) {
  57905. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  57906. angle -= increment;
  57907. }
  57908. return result;
  57909. };
  57910. Polygon.Parse = function (input) {
  57911. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  57912. var i, result = [];
  57913. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  57914. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  57915. }
  57916. return result;
  57917. };
  57918. Polygon.StartingAt = function (x, y) {
  57919. return BABYLON.Path2.StartingAt(x, y);
  57920. };
  57921. return Polygon;
  57922. }());
  57923. BABYLON.Polygon = Polygon;
  57924. var PolygonMeshBuilder = (function () {
  57925. function PolygonMeshBuilder(name, contours, scene) {
  57926. this._points = new PolygonPoints();
  57927. this._outlinepoints = new PolygonPoints();
  57928. this._holes = [];
  57929. this._epoints = new Array();
  57930. this._eholes = new Array();
  57931. this._name = name;
  57932. this._scene = scene;
  57933. var points;
  57934. if (contours instanceof BABYLON.Path2) {
  57935. points = contours.getPoints();
  57936. }
  57937. else {
  57938. points = contours;
  57939. }
  57940. this._addToepoint(points);
  57941. this._points.add(points);
  57942. this._outlinepoints.add(points);
  57943. }
  57944. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  57945. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  57946. var p = points_1[_i];
  57947. this._epoints.push(p.x, p.y);
  57948. }
  57949. };
  57950. PolygonMeshBuilder.prototype.addHole = function (hole) {
  57951. this._points.add(hole);
  57952. var holepoints = new PolygonPoints();
  57953. holepoints.add(hole);
  57954. this._holes.push(holepoints);
  57955. this._eholes.push(this._epoints.length / 2);
  57956. this._addToepoint(hole);
  57957. return this;
  57958. };
  57959. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  57960. var _this = this;
  57961. if (updatable === void 0) { updatable = false; }
  57962. var result = new BABYLON.Mesh(this._name, this._scene);
  57963. var normals = [];
  57964. var positions = [];
  57965. var uvs = [];
  57966. var bounds = this._points.computeBounds();
  57967. this._points.elements.forEach(function (p) {
  57968. normals.push(0, 1.0, 0);
  57969. positions.push(p.x, 0, p.y);
  57970. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  57971. });
  57972. var indices = [];
  57973. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  57974. for (var i = 0; i < res.length; i++) {
  57975. indices.push(res[i]);
  57976. }
  57977. if (depth > 0) {
  57978. var positionscount = (positions.length / 3); //get the current pointcount
  57979. this._points.elements.forEach(function (p) {
  57980. normals.push(0, -1.0, 0);
  57981. positions.push(p.x, -depth, p.y);
  57982. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  57983. });
  57984. var totalCount = indices.length;
  57985. for (var i = 0; i < totalCount; i += 3) {
  57986. var i0 = indices[i + 0];
  57987. var i1 = indices[i + 1];
  57988. var i2 = indices[i + 2];
  57989. indices.push(i2 + positionscount);
  57990. indices.push(i1 + positionscount);
  57991. indices.push(i0 + positionscount);
  57992. }
  57993. //Add the sides
  57994. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  57995. this._holes.forEach(function (hole) {
  57996. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  57997. });
  57998. }
  57999. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  58000. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  58001. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  58002. result.setIndices(indices);
  58003. return result;
  58004. };
  58005. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  58006. var StartIndex = positions.length / 3;
  58007. var ulength = 0;
  58008. for (var i = 0; i < points.elements.length; i++) {
  58009. var p = points.elements[i];
  58010. var p1;
  58011. if ((i + 1) > points.elements.length - 1) {
  58012. p1 = points.elements[0];
  58013. }
  58014. else {
  58015. p1 = points.elements[i + 1];
  58016. }
  58017. positions.push(p.x, 0, p.y);
  58018. positions.push(p.x, -depth, p.y);
  58019. positions.push(p1.x, 0, p1.y);
  58020. positions.push(p1.x, -depth, p1.y);
  58021. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  58022. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  58023. var v3 = v2.subtract(v1);
  58024. var v4 = new BABYLON.Vector3(0, 1, 0);
  58025. var vn = BABYLON.Vector3.Cross(v3, v4);
  58026. vn = vn.normalize();
  58027. uvs.push(ulength / bounds.width, 0);
  58028. uvs.push(ulength / bounds.width, 1);
  58029. ulength += v3.length();
  58030. uvs.push((ulength / bounds.width), 0);
  58031. uvs.push((ulength / bounds.width), 1);
  58032. if (!flip) {
  58033. normals.push(-vn.x, -vn.y, -vn.z);
  58034. normals.push(-vn.x, -vn.y, -vn.z);
  58035. normals.push(-vn.x, -vn.y, -vn.z);
  58036. normals.push(-vn.x, -vn.y, -vn.z);
  58037. indices.push(StartIndex);
  58038. indices.push(StartIndex + 1);
  58039. indices.push(StartIndex + 2);
  58040. indices.push(StartIndex + 1);
  58041. indices.push(StartIndex + 3);
  58042. indices.push(StartIndex + 2);
  58043. }
  58044. else {
  58045. normals.push(vn.x, vn.y, vn.z);
  58046. normals.push(vn.x, vn.y, vn.z);
  58047. normals.push(vn.x, vn.y, vn.z);
  58048. normals.push(vn.x, vn.y, vn.z);
  58049. indices.push(StartIndex);
  58050. indices.push(StartIndex + 2);
  58051. indices.push(StartIndex + 1);
  58052. indices.push(StartIndex + 1);
  58053. indices.push(StartIndex + 2);
  58054. indices.push(StartIndex + 3);
  58055. }
  58056. StartIndex += 4;
  58057. }
  58058. ;
  58059. };
  58060. return PolygonMeshBuilder;
  58061. }());
  58062. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  58063. })(BABYLON || (BABYLON = {}));
  58064. //# sourceMappingURL=babylon.polygonMesh.js.map
  58065. var BABYLON;
  58066. (function (BABYLON) {
  58067. // Unique ID when we import meshes from Babylon to CSG
  58068. var currentCSGMeshId = 0;
  58069. // # class Vertex
  58070. // Represents a vertex of a polygon. Use your own vertex class instead of this
  58071. // one to provide additional features like texture coordinates and vertex
  58072. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  58073. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  58074. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  58075. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  58076. // is not used anywhere else.
  58077. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  58078. var Vertex = (function () {
  58079. function Vertex(pos, normal, uv) {
  58080. this.pos = pos;
  58081. this.normal = normal;
  58082. this.uv = uv;
  58083. }
  58084. Vertex.prototype.clone = function () {
  58085. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  58086. };
  58087. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  58088. // orientation of a polygon is flipped.
  58089. Vertex.prototype.flip = function () {
  58090. this.normal = this.normal.scale(-1);
  58091. };
  58092. // Create a new vertex between this vertex and `other` by linearly
  58093. // interpolating all properties using a parameter of `t`. Subclasses should
  58094. // override this to interpolate additional properties.
  58095. Vertex.prototype.interpolate = function (other, t) {
  58096. 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));
  58097. };
  58098. return Vertex;
  58099. }());
  58100. // # class Plane
  58101. // Represents a plane in 3D space.
  58102. var Plane = (function () {
  58103. function Plane(normal, w) {
  58104. this.normal = normal;
  58105. this.w = w;
  58106. }
  58107. Plane.FromPoints = function (a, b, c) {
  58108. var v0 = c.subtract(a);
  58109. var v1 = b.subtract(a);
  58110. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  58111. return null;
  58112. }
  58113. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  58114. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  58115. };
  58116. Plane.prototype.clone = function () {
  58117. return new Plane(this.normal.clone(), this.w);
  58118. };
  58119. Plane.prototype.flip = function () {
  58120. this.normal.scaleInPlace(-1);
  58121. this.w = -this.w;
  58122. };
  58123. // Split `polygon` by this plane if needed, then put the polygon or polygon
  58124. // fragments in the appropriate lists. Coplanar polygons go into either
  58125. // `coplanarFront` or `coplanarBack` depending on their orientation with
  58126. // respect to this plane. Polygons in front or in back of this plane go into
  58127. // either `front` or `back`.
  58128. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  58129. var COPLANAR = 0;
  58130. var FRONT = 1;
  58131. var BACK = 2;
  58132. var SPANNING = 3;
  58133. // Classify each point as well as the entire polygon into one of the above
  58134. // four classes.
  58135. var polygonType = 0;
  58136. var types = [];
  58137. var i;
  58138. var t;
  58139. for (i = 0; i < polygon.vertices.length; i++) {
  58140. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  58141. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  58142. polygonType |= type;
  58143. types.push(type);
  58144. }
  58145. // Put the polygon in the correct list, splitting it when necessary.
  58146. switch (polygonType) {
  58147. case COPLANAR:
  58148. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  58149. break;
  58150. case FRONT:
  58151. front.push(polygon);
  58152. break;
  58153. case BACK:
  58154. back.push(polygon);
  58155. break;
  58156. case SPANNING:
  58157. var f = [], b = [];
  58158. for (i = 0; i < polygon.vertices.length; i++) {
  58159. var j = (i + 1) % polygon.vertices.length;
  58160. var ti = types[i], tj = types[j];
  58161. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  58162. if (ti !== BACK)
  58163. f.push(vi);
  58164. if (ti !== FRONT)
  58165. b.push(ti !== BACK ? vi.clone() : vi);
  58166. if ((ti | tj) === SPANNING) {
  58167. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  58168. var v = vi.interpolate(vj, t);
  58169. f.push(v);
  58170. b.push(v.clone());
  58171. }
  58172. }
  58173. var poly;
  58174. if (f.length >= 3) {
  58175. poly = new Polygon(f, polygon.shared);
  58176. if (poly.plane)
  58177. front.push(poly);
  58178. }
  58179. if (b.length >= 3) {
  58180. poly = new Polygon(b, polygon.shared);
  58181. if (poly.plane)
  58182. back.push(poly);
  58183. }
  58184. break;
  58185. }
  58186. };
  58187. return Plane;
  58188. }());
  58189. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  58190. // point is on the plane.
  58191. Plane.EPSILON = 1e-5;
  58192. // # class Polygon
  58193. // Represents a convex polygon. The vertices used to initialize a polygon must
  58194. // be coplanar and form a convex loop.
  58195. //
  58196. // Each convex polygon has a `shared` property, which is shared between all
  58197. // polygons that are clones of each other or were split from the same polygon.
  58198. // This can be used to define per-polygon properties (such as surface color).
  58199. var Polygon = (function () {
  58200. function Polygon(vertices, shared) {
  58201. this.vertices = vertices;
  58202. this.shared = shared;
  58203. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  58204. }
  58205. Polygon.prototype.clone = function () {
  58206. var vertices = this.vertices.map(function (v) { return v.clone(); });
  58207. return new Polygon(vertices, this.shared);
  58208. };
  58209. Polygon.prototype.flip = function () {
  58210. this.vertices.reverse().map(function (v) { v.flip(); });
  58211. this.plane.flip();
  58212. };
  58213. return Polygon;
  58214. }());
  58215. // # class Node
  58216. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  58217. // by picking a polygon to split along. That polygon (and all other coplanar
  58218. // polygons) are added directly to that node and the other polygons are added to
  58219. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  58220. // no distinction between internal and leaf nodes.
  58221. var Node = (function () {
  58222. function Node(polygons) {
  58223. this.plane = null;
  58224. this.front = null;
  58225. this.back = null;
  58226. this.polygons = [];
  58227. if (polygons) {
  58228. this.build(polygons);
  58229. }
  58230. }
  58231. Node.prototype.clone = function () {
  58232. var node = new Node();
  58233. node.plane = this.plane && this.plane.clone();
  58234. node.front = this.front && this.front.clone();
  58235. node.back = this.back && this.back.clone();
  58236. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  58237. return node;
  58238. };
  58239. // Convert solid space to empty space and empty space to solid space.
  58240. Node.prototype.invert = function () {
  58241. for (var i = 0; i < this.polygons.length; i++) {
  58242. this.polygons[i].flip();
  58243. }
  58244. if (this.plane) {
  58245. this.plane.flip();
  58246. }
  58247. if (this.front) {
  58248. this.front.invert();
  58249. }
  58250. if (this.back) {
  58251. this.back.invert();
  58252. }
  58253. var temp = this.front;
  58254. this.front = this.back;
  58255. this.back = temp;
  58256. };
  58257. // Recursively remove all polygons in `polygons` that are inside this BSP
  58258. // tree.
  58259. Node.prototype.clipPolygons = function (polygons) {
  58260. if (!this.plane)
  58261. return polygons.slice();
  58262. var front = [], back = [];
  58263. for (var i = 0; i < polygons.length; i++) {
  58264. this.plane.splitPolygon(polygons[i], front, back, front, back);
  58265. }
  58266. if (this.front) {
  58267. front = this.front.clipPolygons(front);
  58268. }
  58269. if (this.back) {
  58270. back = this.back.clipPolygons(back);
  58271. }
  58272. else {
  58273. back = [];
  58274. }
  58275. return front.concat(back);
  58276. };
  58277. // Remove all polygons in this BSP tree that are inside the other BSP tree
  58278. // `bsp`.
  58279. Node.prototype.clipTo = function (bsp) {
  58280. this.polygons = bsp.clipPolygons(this.polygons);
  58281. if (this.front)
  58282. this.front.clipTo(bsp);
  58283. if (this.back)
  58284. this.back.clipTo(bsp);
  58285. };
  58286. // Return a list of all polygons in this BSP tree.
  58287. Node.prototype.allPolygons = function () {
  58288. var polygons = this.polygons.slice();
  58289. if (this.front)
  58290. polygons = polygons.concat(this.front.allPolygons());
  58291. if (this.back)
  58292. polygons = polygons.concat(this.back.allPolygons());
  58293. return polygons;
  58294. };
  58295. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  58296. // new polygons are filtered down to the bottom of the tree and become new
  58297. // nodes there. Each set of polygons is partitioned using the first polygon
  58298. // (no heuristic is used to pick a good split).
  58299. Node.prototype.build = function (polygons) {
  58300. if (!polygons.length)
  58301. return;
  58302. if (!this.plane)
  58303. this.plane = polygons[0].plane.clone();
  58304. var front = [], back = [];
  58305. for (var i = 0; i < polygons.length; i++) {
  58306. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  58307. }
  58308. if (front.length) {
  58309. if (!this.front)
  58310. this.front = new Node();
  58311. this.front.build(front);
  58312. }
  58313. if (back.length) {
  58314. if (!this.back)
  58315. this.back = new Node();
  58316. this.back.build(back);
  58317. }
  58318. };
  58319. return Node;
  58320. }());
  58321. var CSG = (function () {
  58322. function CSG() {
  58323. this.polygons = new Array();
  58324. }
  58325. // Convert BABYLON.Mesh to BABYLON.CSG
  58326. CSG.FromMesh = function (mesh) {
  58327. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  58328. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  58329. if (mesh instanceof BABYLON.Mesh) {
  58330. mesh.computeWorldMatrix(true);
  58331. matrix = mesh.getWorldMatrix();
  58332. meshPosition = mesh.position.clone();
  58333. meshRotation = mesh.rotation.clone();
  58334. if (mesh.rotationQuaternion) {
  58335. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  58336. }
  58337. meshScaling = mesh.scaling.clone();
  58338. }
  58339. else {
  58340. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  58341. }
  58342. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58343. var subMeshes = mesh.subMeshes;
  58344. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  58345. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  58346. vertices = [];
  58347. for (var j = 0; j < 3; j++) {
  58348. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  58349. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  58350. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  58351. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  58352. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  58353. vertex = new Vertex(position, normal, uv);
  58354. vertices.push(vertex);
  58355. }
  58356. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  58357. // To handle the case of degenerated triangle
  58358. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  58359. if (polygon.plane)
  58360. polygons.push(polygon);
  58361. }
  58362. }
  58363. var csg = CSG.FromPolygons(polygons);
  58364. csg.matrix = matrix;
  58365. csg.position = meshPosition;
  58366. csg.rotation = meshRotation;
  58367. csg.scaling = meshScaling;
  58368. csg.rotationQuaternion = meshRotationQuaternion;
  58369. currentCSGMeshId++;
  58370. return csg;
  58371. };
  58372. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  58373. CSG.FromPolygons = function (polygons) {
  58374. var csg = new CSG();
  58375. csg.polygons = polygons;
  58376. return csg;
  58377. };
  58378. CSG.prototype.clone = function () {
  58379. var csg = new CSG();
  58380. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  58381. csg.copyTransformAttributes(this);
  58382. return csg;
  58383. };
  58384. CSG.prototype.toPolygons = function () {
  58385. return this.polygons;
  58386. };
  58387. CSG.prototype.union = function (csg) {
  58388. var a = new Node(this.clone().polygons);
  58389. var b = new Node(csg.clone().polygons);
  58390. a.clipTo(b);
  58391. b.clipTo(a);
  58392. b.invert();
  58393. b.clipTo(a);
  58394. b.invert();
  58395. a.build(b.allPolygons());
  58396. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58397. };
  58398. CSG.prototype.unionInPlace = function (csg) {
  58399. var a = new Node(this.polygons);
  58400. var b = new Node(csg.polygons);
  58401. a.clipTo(b);
  58402. b.clipTo(a);
  58403. b.invert();
  58404. b.clipTo(a);
  58405. b.invert();
  58406. a.build(b.allPolygons());
  58407. this.polygons = a.allPolygons();
  58408. };
  58409. CSG.prototype.subtract = function (csg) {
  58410. var a = new Node(this.clone().polygons);
  58411. var b = new Node(csg.clone().polygons);
  58412. a.invert();
  58413. a.clipTo(b);
  58414. b.clipTo(a);
  58415. b.invert();
  58416. b.clipTo(a);
  58417. b.invert();
  58418. a.build(b.allPolygons());
  58419. a.invert();
  58420. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58421. };
  58422. CSG.prototype.subtractInPlace = function (csg) {
  58423. var a = new Node(this.polygons);
  58424. var b = new Node(csg.polygons);
  58425. a.invert();
  58426. a.clipTo(b);
  58427. b.clipTo(a);
  58428. b.invert();
  58429. b.clipTo(a);
  58430. b.invert();
  58431. a.build(b.allPolygons());
  58432. a.invert();
  58433. this.polygons = a.allPolygons();
  58434. };
  58435. CSG.prototype.intersect = function (csg) {
  58436. var a = new Node(this.clone().polygons);
  58437. var b = new Node(csg.clone().polygons);
  58438. a.invert();
  58439. b.clipTo(a);
  58440. b.invert();
  58441. a.clipTo(b);
  58442. b.clipTo(a);
  58443. a.build(b.allPolygons());
  58444. a.invert();
  58445. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58446. };
  58447. CSG.prototype.intersectInPlace = function (csg) {
  58448. var a = new Node(this.polygons);
  58449. var b = new Node(csg.polygons);
  58450. a.invert();
  58451. b.clipTo(a);
  58452. b.invert();
  58453. a.clipTo(b);
  58454. b.clipTo(a);
  58455. a.build(b.allPolygons());
  58456. a.invert();
  58457. this.polygons = a.allPolygons();
  58458. };
  58459. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  58460. // not modified.
  58461. CSG.prototype.inverse = function () {
  58462. var csg = this.clone();
  58463. csg.inverseInPlace();
  58464. return csg;
  58465. };
  58466. CSG.prototype.inverseInPlace = function () {
  58467. this.polygons.map(function (p) { p.flip(); });
  58468. };
  58469. // This is used to keep meshes transformations so they can be restored
  58470. // when we build back a Babylon Mesh
  58471. // NB : All CSG operations are performed in world coordinates
  58472. CSG.prototype.copyTransformAttributes = function (csg) {
  58473. this.matrix = csg.matrix;
  58474. this.position = csg.position;
  58475. this.rotation = csg.rotation;
  58476. this.scaling = csg.scaling;
  58477. this.rotationQuaternion = csg.rotationQuaternion;
  58478. return this;
  58479. };
  58480. // Build Raw mesh from CSG
  58481. // Coordinates here are in world space
  58482. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  58483. var matrix = this.matrix.clone();
  58484. matrix.invert();
  58485. 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;
  58486. if (keepSubMeshes) {
  58487. // Sort Polygons, since subMeshes are indices range
  58488. polygons.sort(function (a, b) {
  58489. if (a.shared.meshId === b.shared.meshId) {
  58490. return a.shared.subMeshId - b.shared.subMeshId;
  58491. }
  58492. else {
  58493. return a.shared.meshId - b.shared.meshId;
  58494. }
  58495. });
  58496. }
  58497. for (var i = 0, il = polygons.length; i < il; i++) {
  58498. polygon = polygons[i];
  58499. // Building SubMeshes
  58500. if (!subMesh_dict[polygon.shared.meshId]) {
  58501. subMesh_dict[polygon.shared.meshId] = {};
  58502. }
  58503. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  58504. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  58505. indexStart: +Infinity,
  58506. indexEnd: -Infinity,
  58507. materialIndex: polygon.shared.materialIndex
  58508. };
  58509. }
  58510. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  58511. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  58512. polygonIndices[0] = 0;
  58513. polygonIndices[1] = j - 1;
  58514. polygonIndices[2] = j;
  58515. for (var k = 0; k < 3; k++) {
  58516. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  58517. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  58518. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  58519. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  58520. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  58521. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  58522. // Check if 2 points can be merged
  58523. if (!(typeof vertex_idx !== 'undefined' &&
  58524. normals[vertex_idx * 3] === localNormal.x &&
  58525. normals[vertex_idx * 3 + 1] === localNormal.y &&
  58526. normals[vertex_idx * 3 + 2] === localNormal.z &&
  58527. uvs[vertex_idx * 2] === uv.x &&
  58528. uvs[vertex_idx * 2 + 1] === uv.y)) {
  58529. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  58530. uvs.push(uv.x, uv.y);
  58531. normals.push(normal.x, normal.y, normal.z);
  58532. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  58533. }
  58534. indices.push(vertex_idx);
  58535. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  58536. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  58537. currentIndex++;
  58538. }
  58539. }
  58540. }
  58541. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  58542. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  58543. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  58544. mesh.setIndices(indices);
  58545. if (keepSubMeshes) {
  58546. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  58547. var materialIndexOffset = 0, materialMaxIndex;
  58548. mesh.subMeshes = new Array();
  58549. for (var m in subMesh_dict) {
  58550. materialMaxIndex = -1;
  58551. for (var sm in subMesh_dict[m]) {
  58552. subMesh_obj = subMesh_dict[m][sm];
  58553. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  58554. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  58555. }
  58556. materialIndexOffset += ++materialMaxIndex;
  58557. }
  58558. }
  58559. return mesh;
  58560. };
  58561. // Build Mesh from CSG taking material and transforms into account
  58562. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  58563. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  58564. mesh.material = material;
  58565. mesh.position.copyFrom(this.position);
  58566. mesh.rotation.copyFrom(this.rotation);
  58567. if (this.rotationQuaternion) {
  58568. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  58569. }
  58570. mesh.scaling.copyFrom(this.scaling);
  58571. mesh.computeWorldMatrix(true);
  58572. return mesh;
  58573. };
  58574. return CSG;
  58575. }());
  58576. BABYLON.CSG = CSG;
  58577. })(BABYLON || (BABYLON = {}));
  58578. //# sourceMappingURL=babylon.csg.js.map
  58579. var BABYLON;
  58580. (function (BABYLON) {
  58581. var LensFlare = (function () {
  58582. function LensFlare(size, position, color, imgUrl, system) {
  58583. this.size = size;
  58584. this.position = position;
  58585. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  58586. this.dispose = function () {
  58587. if (this.texture) {
  58588. this.texture.dispose();
  58589. }
  58590. // Remove from scene
  58591. var index = this._system.lensFlares.indexOf(this);
  58592. this._system.lensFlares.splice(index, 1);
  58593. };
  58594. this.color = color || new BABYLON.Color3(1, 1, 1);
  58595. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  58596. this._system = system;
  58597. system.lensFlares.push(this);
  58598. }
  58599. return LensFlare;
  58600. }());
  58601. BABYLON.LensFlare = LensFlare;
  58602. })(BABYLON || (BABYLON = {}));
  58603. //# sourceMappingURL=babylon.lensFlare.js.map
  58604. var BABYLON;
  58605. (function (BABYLON) {
  58606. var LensFlareSystem = (function () {
  58607. function LensFlareSystem(name, emitter, scene) {
  58608. this.name = name;
  58609. this.lensFlares = new Array();
  58610. this.borderLimit = 300;
  58611. this.viewportBorder = 0;
  58612. this.layerMask = 0x0FFFFFFF;
  58613. this._vertexBuffers = {};
  58614. this._isEnabled = true;
  58615. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58616. this._emitter = emitter;
  58617. this.id = name;
  58618. scene.lensFlareSystems.push(this);
  58619. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  58620. var engine = scene.getEngine();
  58621. // VBO
  58622. var vertices = [];
  58623. vertices.push(1, 1);
  58624. vertices.push(-1, 1);
  58625. vertices.push(-1, -1);
  58626. vertices.push(1, -1);
  58627. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58628. // Indices
  58629. var indices = [];
  58630. indices.push(0);
  58631. indices.push(1);
  58632. indices.push(2);
  58633. indices.push(0);
  58634. indices.push(2);
  58635. indices.push(3);
  58636. this._indexBuffer = engine.createIndexBuffer(indices);
  58637. // Effects
  58638. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  58639. }
  58640. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  58641. get: function () {
  58642. return this._isEnabled;
  58643. },
  58644. set: function (value) {
  58645. this._isEnabled = value;
  58646. },
  58647. enumerable: true,
  58648. configurable: true
  58649. });
  58650. LensFlareSystem.prototype.getScene = function () {
  58651. return this._scene;
  58652. };
  58653. LensFlareSystem.prototype.getEmitter = function () {
  58654. return this._emitter;
  58655. };
  58656. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  58657. this._emitter = newEmitter;
  58658. };
  58659. LensFlareSystem.prototype.getEmitterPosition = function () {
  58660. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  58661. };
  58662. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  58663. var position = this.getEmitterPosition();
  58664. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  58665. this._positionX = position.x;
  58666. this._positionY = position.y;
  58667. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  58668. if (this.viewportBorder > 0) {
  58669. globalViewport.x -= this.viewportBorder;
  58670. globalViewport.y -= this.viewportBorder;
  58671. globalViewport.width += this.viewportBorder * 2;
  58672. globalViewport.height += this.viewportBorder * 2;
  58673. position.x += this.viewportBorder;
  58674. position.y += this.viewportBorder;
  58675. this._positionX += this.viewportBorder;
  58676. this._positionY += this.viewportBorder;
  58677. }
  58678. if (position.z > 0) {
  58679. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  58680. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  58681. return true;
  58682. }
  58683. return true;
  58684. }
  58685. return false;
  58686. };
  58687. LensFlareSystem.prototype._isVisible = function () {
  58688. if (!this._isEnabled) {
  58689. return false;
  58690. }
  58691. var emitterPosition = this.getEmitterPosition();
  58692. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  58693. var distance = direction.length();
  58694. direction.normalize();
  58695. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  58696. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  58697. return !pickInfo.hit || pickInfo.distance > distance;
  58698. };
  58699. LensFlareSystem.prototype.render = function () {
  58700. if (!this._effect.isReady())
  58701. return false;
  58702. var engine = this._scene.getEngine();
  58703. var viewport = this._scene.activeCamera.viewport;
  58704. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  58705. // Position
  58706. if (!this.computeEffectivePosition(globalViewport)) {
  58707. return false;
  58708. }
  58709. // Visibility
  58710. if (!this._isVisible()) {
  58711. return false;
  58712. }
  58713. // Intensity
  58714. var awayX;
  58715. var awayY;
  58716. if (this._positionX < this.borderLimit + globalViewport.x) {
  58717. awayX = this.borderLimit + globalViewport.x - this._positionX;
  58718. }
  58719. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  58720. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  58721. }
  58722. else {
  58723. awayX = 0;
  58724. }
  58725. if (this._positionY < this.borderLimit + globalViewport.y) {
  58726. awayY = this.borderLimit + globalViewport.y - this._positionY;
  58727. }
  58728. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  58729. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  58730. }
  58731. else {
  58732. awayY = 0;
  58733. }
  58734. var away = (awayX > awayY) ? awayX : awayY;
  58735. away -= this.viewportBorder;
  58736. if (away > this.borderLimit) {
  58737. away = this.borderLimit;
  58738. }
  58739. var intensity = 1.0 - (away / this.borderLimit);
  58740. if (intensity < 0) {
  58741. return false;
  58742. }
  58743. if (intensity > 1.0) {
  58744. intensity = 1.0;
  58745. }
  58746. if (this.viewportBorder > 0) {
  58747. globalViewport.x += this.viewportBorder;
  58748. globalViewport.y += this.viewportBorder;
  58749. globalViewport.width -= this.viewportBorder * 2;
  58750. globalViewport.height -= this.viewportBorder * 2;
  58751. this._positionX -= this.viewportBorder;
  58752. this._positionY -= this.viewportBorder;
  58753. }
  58754. // Position
  58755. var centerX = globalViewport.x + globalViewport.width / 2;
  58756. var centerY = globalViewport.y + globalViewport.height / 2;
  58757. var distX = centerX - this._positionX;
  58758. var distY = centerY - this._positionY;
  58759. // Effects
  58760. engine.enableEffect(this._effect);
  58761. engine.setState(false);
  58762. engine.setDepthBuffer(false);
  58763. // VBOs
  58764. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58765. // Flares
  58766. for (var index = 0; index < this.lensFlares.length; index++) {
  58767. var flare = this.lensFlares[index];
  58768. engine.setAlphaMode(flare.alphaMode);
  58769. var x = centerX - (distX * flare.position);
  58770. var y = centerY - (distY * flare.position);
  58771. var cw = flare.size;
  58772. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  58773. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  58774. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  58775. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  58776. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  58777. // Texture
  58778. this._effect.setTexture("textureSampler", flare.texture);
  58779. // Color
  58780. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  58781. // Draw order
  58782. engine.draw(true, 0, 6);
  58783. }
  58784. engine.setDepthBuffer(true);
  58785. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58786. return true;
  58787. };
  58788. LensFlareSystem.prototype.dispose = function () {
  58789. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58790. if (vertexBuffer) {
  58791. vertexBuffer.dispose();
  58792. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58793. }
  58794. if (this._indexBuffer) {
  58795. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58796. this._indexBuffer = null;
  58797. }
  58798. while (this.lensFlares.length) {
  58799. this.lensFlares[0].dispose();
  58800. }
  58801. // Remove from scene
  58802. var index = this._scene.lensFlareSystems.indexOf(this);
  58803. this._scene.lensFlareSystems.splice(index, 1);
  58804. };
  58805. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  58806. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  58807. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  58808. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  58809. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  58810. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  58811. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  58812. var parsedFlare = parsedLensFlareSystem.flares[index];
  58813. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  58814. }
  58815. return lensFlareSystem;
  58816. };
  58817. LensFlareSystem.prototype.serialize = function () {
  58818. var serializationObject = {};
  58819. serializationObject.id = this.id;
  58820. serializationObject.name = this.name;
  58821. serializationObject.emitterId = this.getEmitter().id;
  58822. serializationObject.borderLimit = this.borderLimit;
  58823. serializationObject.flares = [];
  58824. for (var index = 0; index < this.lensFlares.length; index++) {
  58825. var flare = this.lensFlares[index];
  58826. serializationObject.flares.push({
  58827. size: flare.size,
  58828. position: flare.position,
  58829. color: flare.color.asArray(),
  58830. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  58831. });
  58832. }
  58833. return serializationObject;
  58834. };
  58835. return LensFlareSystem;
  58836. }());
  58837. BABYLON.LensFlareSystem = LensFlareSystem;
  58838. })(BABYLON || (BABYLON = {}));
  58839. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  58840. var BABYLON;
  58841. (function (BABYLON) {
  58842. /**
  58843. * This is a holder class for the physics joint created by the physics plugin.
  58844. * It holds a set of functions to control the underlying joint.
  58845. */
  58846. var PhysicsJoint = (function () {
  58847. function PhysicsJoint(type, jointData) {
  58848. this.type = type;
  58849. this.jointData = jointData;
  58850. jointData.nativeParams = jointData.nativeParams || {};
  58851. }
  58852. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  58853. get: function () {
  58854. return this._physicsJoint;
  58855. },
  58856. set: function (newJoint) {
  58857. if (this._physicsJoint) {
  58858. //remove from the wolrd
  58859. }
  58860. this._physicsJoint = newJoint;
  58861. },
  58862. enumerable: true,
  58863. configurable: true
  58864. });
  58865. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  58866. set: function (physicsPlugin) {
  58867. this._physicsPlugin = physicsPlugin;
  58868. },
  58869. enumerable: true,
  58870. configurable: true
  58871. });
  58872. /**
  58873. * Execute a function that is physics-plugin specific.
  58874. * @param {Function} func the function that will be executed.
  58875. * It accepts two parameters: the physics world and the physics joint.
  58876. */
  58877. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  58878. func(this._physicsPlugin.world, this._physicsJoint);
  58879. };
  58880. return PhysicsJoint;
  58881. }());
  58882. //TODO check if the native joints are the same
  58883. //Joint Types
  58884. PhysicsJoint.DistanceJoint = 0;
  58885. PhysicsJoint.HingeJoint = 1;
  58886. PhysicsJoint.BallAndSocketJoint = 2;
  58887. PhysicsJoint.WheelJoint = 3;
  58888. PhysicsJoint.SliderJoint = 4;
  58889. //OIMO
  58890. PhysicsJoint.PrismaticJoint = 5;
  58891. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  58892. PhysicsJoint.UniversalJoint = 6;
  58893. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  58894. //Cannon
  58895. //Similar to a Ball-Joint. Different in params
  58896. PhysicsJoint.PointToPointJoint = 8;
  58897. //Cannon only at the moment
  58898. PhysicsJoint.SpringJoint = 9;
  58899. PhysicsJoint.LockJoint = 10;
  58900. BABYLON.PhysicsJoint = PhysicsJoint;
  58901. /**
  58902. * A class representing a physics distance joint.
  58903. */
  58904. var DistanceJoint = (function (_super) {
  58905. __extends(DistanceJoint, _super);
  58906. function DistanceJoint(jointData) {
  58907. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  58908. }
  58909. /**
  58910. * Update the predefined distance.
  58911. */
  58912. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  58913. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  58914. };
  58915. return DistanceJoint;
  58916. }(PhysicsJoint));
  58917. BABYLON.DistanceJoint = DistanceJoint;
  58918. var MotorEnabledJoint = (function (_super) {
  58919. __extends(MotorEnabledJoint, _super);
  58920. function MotorEnabledJoint(type, jointData) {
  58921. return _super.call(this, type, jointData) || this;
  58922. }
  58923. /**
  58924. * Set the motor values.
  58925. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58926. * @param {number} force the force to apply
  58927. * @param {number} maxForce max force for this motor.
  58928. */
  58929. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  58930. this._physicsPlugin.setMotor(this, force, maxForce);
  58931. };
  58932. /**
  58933. * Set the motor's limits.
  58934. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58935. */
  58936. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58937. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58938. };
  58939. return MotorEnabledJoint;
  58940. }(PhysicsJoint));
  58941. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  58942. /**
  58943. * This class represents a single hinge physics joint
  58944. */
  58945. var HingeJoint = (function (_super) {
  58946. __extends(HingeJoint, _super);
  58947. function HingeJoint(jointData) {
  58948. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  58949. }
  58950. /**
  58951. * Set the motor values.
  58952. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58953. * @param {number} force the force to apply
  58954. * @param {number} maxForce max force for this motor.
  58955. */
  58956. HingeJoint.prototype.setMotor = function (force, maxForce) {
  58957. this._physicsPlugin.setMotor(this, force, maxForce);
  58958. };
  58959. /**
  58960. * Set the motor's limits.
  58961. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58962. */
  58963. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  58964. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  58965. };
  58966. return HingeJoint;
  58967. }(MotorEnabledJoint));
  58968. BABYLON.HingeJoint = HingeJoint;
  58969. /**
  58970. * This class represents a dual hinge physics joint (same as wheel joint)
  58971. */
  58972. var Hinge2Joint = (function (_super) {
  58973. __extends(Hinge2Joint, _super);
  58974. function Hinge2Joint(jointData) {
  58975. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  58976. }
  58977. /**
  58978. * Set the motor values.
  58979. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58980. * @param {number} force the force to apply
  58981. * @param {number} maxForce max force for this motor.
  58982. * @param {motorIndex} the motor's index, 0 or 1.
  58983. */
  58984. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  58985. if (motorIndex === void 0) { motorIndex = 0; }
  58986. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  58987. };
  58988. /**
  58989. * Set the motor limits.
  58990. * Attention, this function is plugin specific. Engines won't react 100% the same.
  58991. * @param {number} upperLimit the upper limit
  58992. * @param {number} lowerLimit lower limit
  58993. * @param {motorIndex} the motor's index, 0 or 1.
  58994. */
  58995. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  58996. if (motorIndex === void 0) { motorIndex = 0; }
  58997. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  58998. };
  58999. return Hinge2Joint;
  59000. }(MotorEnabledJoint));
  59001. BABYLON.Hinge2Joint = Hinge2Joint;
  59002. })(BABYLON || (BABYLON = {}));
  59003. //# sourceMappingURL=babylon.physicsJoint.js.map
  59004. var BABYLON;
  59005. (function (BABYLON) {
  59006. var PhysicsImpostor = (function () {
  59007. function PhysicsImpostor(object, type, _options, _scene) {
  59008. if (_options === void 0) { _options = { mass: 0 }; }
  59009. var _this = this;
  59010. this.object = object;
  59011. this.type = type;
  59012. this._options = _options;
  59013. this._scene = _scene;
  59014. this._bodyUpdateRequired = false;
  59015. this._onBeforePhysicsStepCallbacks = new Array();
  59016. this._onAfterPhysicsStepCallbacks = new Array();
  59017. this._onPhysicsCollideCallbacks = [];
  59018. this._deltaPosition = BABYLON.Vector3.Zero();
  59019. this._isDisposed = false;
  59020. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  59021. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  59022. /**
  59023. * this function is executed by the physics engine.
  59024. */
  59025. this.beforeStep = function () {
  59026. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  59027. //conjugate deltaRotation
  59028. if (_this._deltaRotationConjugated) {
  59029. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  59030. }
  59031. else {
  59032. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  59033. }
  59034. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  59035. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  59036. func(_this);
  59037. });
  59038. };
  59039. /**
  59040. * this function is executed by the physics engine.
  59041. */
  59042. this.afterStep = function () {
  59043. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  59044. func(_this);
  59045. });
  59046. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  59047. _this.object.position.addInPlace(_this._deltaPosition);
  59048. if (_this._deltaRotation) {
  59049. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  59050. }
  59051. };
  59052. /**
  59053. * Legacy collision detection event support
  59054. */
  59055. this.onCollideEvent = null;
  59056. //event and body object due to cannon's event-based architecture.
  59057. this.onCollide = function (e) {
  59058. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  59059. return;
  59060. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  59061. if (otherImpostor) {
  59062. // Legacy collision detection event support
  59063. if (_this.onCollideEvent) {
  59064. _this.onCollideEvent(_this, otherImpostor);
  59065. }
  59066. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  59067. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  59068. }).forEach(function (obj) {
  59069. obj.callback(_this, otherImpostor);
  59070. });
  59071. }
  59072. };
  59073. //sanity check!
  59074. if (!this.object) {
  59075. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  59076. return;
  59077. }
  59078. //legacy support for old syntax.
  59079. if (!this._scene && object.getScene) {
  59080. this._scene = object.getScene();
  59081. }
  59082. this._physicsEngine = this._scene.getPhysicsEngine();
  59083. if (!this._physicsEngine) {
  59084. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  59085. }
  59086. else {
  59087. //set the object's quaternion, if not set
  59088. if (!this.object.rotationQuaternion) {
  59089. if (this.object.rotation) {
  59090. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  59091. }
  59092. else {
  59093. this.object.rotationQuaternion = new BABYLON.Quaternion();
  59094. }
  59095. }
  59096. //default options params
  59097. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  59098. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  59099. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  59100. this._joints = [];
  59101. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  59102. if (!this.object.parent) {
  59103. this._init();
  59104. }
  59105. else if (this.object.parent.physicsImpostor) {
  59106. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  59107. }
  59108. }
  59109. }
  59110. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  59111. get: function () {
  59112. return this._isDisposed;
  59113. },
  59114. enumerable: true,
  59115. configurable: true
  59116. });
  59117. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  59118. get: function () {
  59119. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  59120. },
  59121. set: function (value) {
  59122. this.setMass(value);
  59123. },
  59124. enumerable: true,
  59125. configurable: true
  59126. });
  59127. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  59128. get: function () {
  59129. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  59130. },
  59131. set: function (value) {
  59132. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  59133. },
  59134. enumerable: true,
  59135. configurable: true
  59136. });
  59137. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  59138. get: function () {
  59139. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  59140. },
  59141. set: function (value) {
  59142. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  59143. },
  59144. enumerable: true,
  59145. configurable: true
  59146. });
  59147. /**
  59148. * This function will completly initialize this impostor.
  59149. * It will create a new body - but only if this mesh has no parent.
  59150. * If it has, this impostor will not be used other than to define the impostor
  59151. * of the child mesh.
  59152. */
  59153. PhysicsImpostor.prototype._init = function () {
  59154. this._physicsEngine.removeImpostor(this);
  59155. this.physicsBody = null;
  59156. this._parent = this._parent || this._getPhysicsParent();
  59157. if (!this.parent) {
  59158. this._physicsEngine.addImpostor(this);
  59159. }
  59160. };
  59161. PhysicsImpostor.prototype._getPhysicsParent = function () {
  59162. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  59163. var parentMesh = this.object.parent;
  59164. return parentMesh.physicsImpostor;
  59165. }
  59166. return;
  59167. };
  59168. /**
  59169. * Should a new body be generated.
  59170. */
  59171. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  59172. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  59173. };
  59174. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  59175. this.forceUpdate();
  59176. };
  59177. /**
  59178. * Force a regeneration of this or the parent's impostor's body.
  59179. * Use under cautious - This will remove all joints already implemented.
  59180. */
  59181. PhysicsImpostor.prototype.forceUpdate = function () {
  59182. this._init();
  59183. if (this.parent) {
  59184. this.parent.forceUpdate();
  59185. }
  59186. };
  59187. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  59188. /*public get mesh(): AbstractMesh {
  59189. return this._mesh;
  59190. }*/
  59191. /**
  59192. * Gets the body that holds this impostor. Either its own, or its parent.
  59193. */
  59194. get: function () {
  59195. return this._parent ? this._parent.physicsBody : this._physicsBody;
  59196. },
  59197. /**
  59198. * Set the physics body. Used mainly by the physics engine/plugin
  59199. */
  59200. set: function (physicsBody) {
  59201. if (this._physicsBody) {
  59202. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  59203. }
  59204. this._physicsBody = physicsBody;
  59205. this.resetUpdateFlags();
  59206. },
  59207. enumerable: true,
  59208. configurable: true
  59209. });
  59210. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  59211. get: function () {
  59212. return this._parent;
  59213. },
  59214. set: function (value) {
  59215. this._parent = value;
  59216. },
  59217. enumerable: true,
  59218. configurable: true
  59219. });
  59220. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  59221. this._bodyUpdateRequired = false;
  59222. };
  59223. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  59224. if (this.object.getBoundingInfo) {
  59225. var q = this.object.rotationQuaternion;
  59226. //reset rotation
  59227. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  59228. //calculate the world matrix with no rotation
  59229. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  59230. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  59231. //bring back the rotation
  59232. this.object.rotationQuaternion = q;
  59233. //calculate the world matrix with the new rotation
  59234. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  59235. return size;
  59236. }
  59237. else {
  59238. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  59239. }
  59240. };
  59241. PhysicsImpostor.prototype.getObjectCenter = function () {
  59242. if (this.object.getBoundingInfo) {
  59243. return this.object.getBoundingInfo().boundingBox.centerWorld;
  59244. }
  59245. else {
  59246. return this.object.position;
  59247. }
  59248. };
  59249. /**
  59250. * Get a specific parametes from the options parameter.
  59251. */
  59252. PhysicsImpostor.prototype.getParam = function (paramName) {
  59253. return this._options[paramName];
  59254. };
  59255. /**
  59256. * Sets a specific parameter in the options given to the physics plugin
  59257. */
  59258. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  59259. this._options[paramName] = value;
  59260. this._bodyUpdateRequired = true;
  59261. };
  59262. /**
  59263. * Specifically change the body's mass option. Won't recreate the physics body object
  59264. */
  59265. PhysicsImpostor.prototype.setMass = function (mass) {
  59266. if (this.getParam("mass") !== mass) {
  59267. this.setParam("mass", mass);
  59268. }
  59269. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  59270. };
  59271. PhysicsImpostor.prototype.getLinearVelocity = function () {
  59272. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  59273. };
  59274. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  59275. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  59276. };
  59277. PhysicsImpostor.prototype.getAngularVelocity = function () {
  59278. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  59279. };
  59280. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  59281. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  59282. };
  59283. /**
  59284. * Execute a function with the physics plugin native code.
  59285. * Provide a function the will have two variables - the world object and the physics body object.
  59286. */
  59287. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  59288. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  59289. };
  59290. /**
  59291. * Register a function that will be executed before the physics world is stepping forward.
  59292. */
  59293. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  59294. this._onBeforePhysicsStepCallbacks.push(func);
  59295. };
  59296. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  59297. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  59298. if (index > -1) {
  59299. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  59300. }
  59301. else {
  59302. BABYLON.Tools.Warn("Function to remove was not found");
  59303. }
  59304. };
  59305. /**
  59306. * Register a function that will be executed after the physics step
  59307. */
  59308. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  59309. this._onAfterPhysicsStepCallbacks.push(func);
  59310. };
  59311. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  59312. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  59313. if (index > -1) {
  59314. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  59315. }
  59316. else {
  59317. BABYLON.Tools.Warn("Function to remove was not found");
  59318. }
  59319. };
  59320. /**
  59321. * register a function that will be executed when this impostor collides against a different body.
  59322. */
  59323. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  59324. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  59325. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  59326. };
  59327. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  59328. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  59329. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  59330. if (index > -1) {
  59331. this._onPhysicsCollideCallbacks.splice(index, 1);
  59332. }
  59333. else {
  59334. BABYLON.Tools.Warn("Function to remove was not found");
  59335. }
  59336. };
  59337. /**
  59338. * Apply a force
  59339. */
  59340. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  59341. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  59342. };
  59343. /**
  59344. * Apply an impulse
  59345. */
  59346. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  59347. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  59348. };
  59349. /**
  59350. * A help function to create a joint.
  59351. */
  59352. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  59353. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  59354. this.addJoint(otherImpostor, joint);
  59355. };
  59356. /**
  59357. * Add a joint to this impostor with a different impostor.
  59358. */
  59359. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  59360. this._joints.push({
  59361. otherImpostor: otherImpostor,
  59362. joint: joint
  59363. });
  59364. this._physicsEngine.addJoint(this, otherImpostor, joint);
  59365. };
  59366. /**
  59367. * Will keep this body still, in a sleep mode.
  59368. */
  59369. PhysicsImpostor.prototype.sleep = function () {
  59370. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  59371. };
  59372. /**
  59373. * Wake the body up.
  59374. */
  59375. PhysicsImpostor.prototype.wakeUp = function () {
  59376. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  59377. };
  59378. PhysicsImpostor.prototype.clone = function (newObject) {
  59379. if (!newObject)
  59380. return null;
  59381. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  59382. };
  59383. PhysicsImpostor.prototype.dispose = function () {
  59384. var _this = this;
  59385. //no dispose if no physics engine is available.
  59386. if (!this._physicsEngine) {
  59387. return;
  59388. }
  59389. this._joints.forEach(function (j) {
  59390. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  59391. });
  59392. //dispose the physics body
  59393. this._physicsEngine.removeImpostor(this);
  59394. if (this.parent) {
  59395. this.parent.forceUpdate();
  59396. }
  59397. else {
  59398. /*this._object.getChildMeshes().forEach(function(mesh) {
  59399. if (mesh.physicsImpostor) {
  59400. if (disposeChildren) {
  59401. mesh.physicsImpostor.dispose();
  59402. mesh.physicsImpostor = null;
  59403. }
  59404. }
  59405. })*/
  59406. }
  59407. this._isDisposed = true;
  59408. };
  59409. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  59410. this._deltaPosition.copyFrom(position);
  59411. };
  59412. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  59413. if (!this._deltaRotation) {
  59414. this._deltaRotation = new BABYLON.Quaternion();
  59415. }
  59416. this._deltaRotation.copyFrom(rotation);
  59417. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  59418. };
  59419. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  59420. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  59421. };
  59422. PhysicsImpostor.prototype.getRadius = function () {
  59423. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  59424. };
  59425. /**
  59426. * Sync a bone with this impostor
  59427. * @param bone The bone to sync to the impostor.
  59428. * @param boneMesh The mesh that the bone is influencing.
  59429. * @param jointPivot The pivot of the joint / bone in local space.
  59430. * @param distToJoint Optional distance from the impostor to the joint.
  59431. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  59432. */
  59433. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  59434. var tempVec = PhysicsImpostor._tmpVecs[0];
  59435. var mesh = this.object;
  59436. if (adjustRotation) {
  59437. var tempQuat = PhysicsImpostor._tmpQuat;
  59438. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  59439. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  59440. }
  59441. else {
  59442. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  59443. }
  59444. tempVec.x = 0;
  59445. tempVec.y = 0;
  59446. tempVec.z = 0;
  59447. if (jointPivot) {
  59448. tempVec.x = jointPivot.x;
  59449. tempVec.y = jointPivot.y;
  59450. tempVec.z = jointPivot.z;
  59451. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  59452. if (distToJoint === undefined || distToJoint === null) {
  59453. distToJoint = jointPivot.length();
  59454. }
  59455. tempVec.x *= distToJoint;
  59456. tempVec.y *= distToJoint;
  59457. tempVec.z *= distToJoint;
  59458. }
  59459. if (bone.getParent()) {
  59460. tempVec.addInPlace(mesh.getAbsolutePosition());
  59461. bone.setAbsolutePosition(tempVec, boneMesh);
  59462. }
  59463. else {
  59464. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  59465. boneMesh.position.x -= tempVec.x;
  59466. boneMesh.position.y -= tempVec.y;
  59467. boneMesh.position.z -= tempVec.z;
  59468. }
  59469. };
  59470. /**
  59471. * Sync impostor to a bone
  59472. * @param bone The bone that the impostor will be synced to.
  59473. * @param boneMesh The mesh that the bone is influencing.
  59474. * @param jointPivot The pivot of the joint / bone in local space.
  59475. * @param distToJoint Optional distance from the impostor to the joint.
  59476. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  59477. * @param boneAxis Optional vector3 axis the bone is aligned with
  59478. */
  59479. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  59480. var mesh = this.object;
  59481. if (adjustRotation) {
  59482. var tempQuat = PhysicsImpostor._tmpQuat;
  59483. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  59484. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  59485. }
  59486. else {
  59487. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  59488. }
  59489. var pos = PhysicsImpostor._tmpVecs[0];
  59490. var boneDir = PhysicsImpostor._tmpVecs[1];
  59491. if (!boneAxis) {
  59492. boneAxis = PhysicsImpostor._tmpVecs[2];
  59493. boneAxis.x = 0;
  59494. boneAxis.y = 1;
  59495. boneAxis.z = 0;
  59496. }
  59497. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  59498. bone.getAbsolutePositionToRef(boneMesh, pos);
  59499. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  59500. distToJoint = jointPivot.length();
  59501. }
  59502. if (distToJoint !== undefined && distToJoint !== null) {
  59503. pos.x += boneDir.x * distToJoint;
  59504. pos.y += boneDir.y * distToJoint;
  59505. pos.z += boneDir.z * distToJoint;
  59506. }
  59507. mesh.setAbsolutePosition(pos);
  59508. };
  59509. return PhysicsImpostor;
  59510. }());
  59511. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  59512. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  59513. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59514. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  59515. //Impostor types
  59516. PhysicsImpostor.NoImpostor = 0;
  59517. PhysicsImpostor.SphereImpostor = 1;
  59518. PhysicsImpostor.BoxImpostor = 2;
  59519. PhysicsImpostor.PlaneImpostor = 3;
  59520. PhysicsImpostor.MeshImpostor = 4;
  59521. PhysicsImpostor.CylinderImpostor = 7;
  59522. PhysicsImpostor.ParticleImpostor = 8;
  59523. PhysicsImpostor.HeightmapImpostor = 9;
  59524. BABYLON.PhysicsImpostor = PhysicsImpostor;
  59525. })(BABYLON || (BABYLON = {}));
  59526. //# sourceMappingURL=babylon.physicsImpostor.js.map
  59527. var BABYLON;
  59528. (function (BABYLON) {
  59529. var PhysicsEngine = (function () {
  59530. function PhysicsEngine(gravity, _physicsPlugin) {
  59531. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  59532. this._physicsPlugin = _physicsPlugin;
  59533. //new methods and parameters
  59534. this._impostors = [];
  59535. this._joints = [];
  59536. if (!this._physicsPlugin.isSupported()) {
  59537. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  59538. + "Please make sure it is included.");
  59539. }
  59540. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  59541. this.setGravity(gravity);
  59542. this.setTimeStep();
  59543. }
  59544. PhysicsEngine.prototype.setGravity = function (gravity) {
  59545. this.gravity = gravity;
  59546. this._physicsPlugin.setGravity(this.gravity);
  59547. };
  59548. /**
  59549. * Set the time step of the physics engine.
  59550. * default is 1/60.
  59551. * To slow it down, enter 1/600 for example.
  59552. * To speed it up, 1/30
  59553. * @param {number} newTimeStep the new timestep to apply to this world.
  59554. */
  59555. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  59556. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  59557. this._physicsPlugin.setTimeStep(newTimeStep);
  59558. };
  59559. PhysicsEngine.prototype.dispose = function () {
  59560. this._impostors.forEach(function (impostor) {
  59561. impostor.dispose();
  59562. });
  59563. this._physicsPlugin.dispose();
  59564. };
  59565. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  59566. return this._physicsPlugin.name;
  59567. };
  59568. /**
  59569. * Adding a new impostor for the impostor tracking.
  59570. * This will be done by the impostor itself.
  59571. * @param {PhysicsImpostor} impostor the impostor to add
  59572. */
  59573. PhysicsEngine.prototype.addImpostor = function (impostor) {
  59574. impostor.uniqueId = this._impostors.push(impostor);
  59575. //if no parent, generate the body
  59576. if (!impostor.parent) {
  59577. this._physicsPlugin.generatePhysicsBody(impostor);
  59578. }
  59579. };
  59580. /**
  59581. * Remove an impostor from the engine.
  59582. * This impostor and its mesh will not longer be updated by the physics engine.
  59583. * @param {PhysicsImpostor} impostor the impostor to remove
  59584. */
  59585. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  59586. var index = this._impostors.indexOf(impostor);
  59587. if (index > -1) {
  59588. var removed = this._impostors.splice(index, 1);
  59589. //Is it needed?
  59590. if (removed.length) {
  59591. //this will also remove it from the world.
  59592. removed[0].physicsBody = null;
  59593. }
  59594. }
  59595. };
  59596. /**
  59597. * Add a joint to the physics engine
  59598. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  59599. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  59600. * @param {PhysicsJoint} the joint that will connect both impostors.
  59601. */
  59602. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  59603. var impostorJoint = {
  59604. mainImpostor: mainImpostor,
  59605. connectedImpostor: connectedImpostor,
  59606. joint: joint
  59607. };
  59608. joint.physicsPlugin = this._physicsPlugin;
  59609. this._joints.push(impostorJoint);
  59610. this._physicsPlugin.generateJoint(impostorJoint);
  59611. };
  59612. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  59613. var matchingJoints = this._joints.filter(function (impostorJoint) {
  59614. return (impostorJoint.connectedImpostor === connectedImpostor
  59615. && impostorJoint.joint === joint
  59616. && impostorJoint.mainImpostor === mainImpostor);
  59617. });
  59618. if (matchingJoints.length) {
  59619. this._physicsPlugin.removeJoint(matchingJoints[0]);
  59620. //TODO remove it from the list as well
  59621. }
  59622. };
  59623. /**
  59624. * Called by the scene. no need to call it.
  59625. */
  59626. PhysicsEngine.prototype._step = function (delta) {
  59627. var _this = this;
  59628. //check if any mesh has no body / requires an update
  59629. this._impostors.forEach(function (impostor) {
  59630. if (impostor.isBodyInitRequired()) {
  59631. _this._physicsPlugin.generatePhysicsBody(impostor);
  59632. }
  59633. });
  59634. if (delta > 0.1) {
  59635. delta = 0.1;
  59636. }
  59637. else if (delta <= 0) {
  59638. delta = 1.0 / 60.0;
  59639. }
  59640. this._physicsPlugin.executeStep(delta, this._impostors);
  59641. };
  59642. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  59643. return this._physicsPlugin;
  59644. };
  59645. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  59646. for (var i = 0; i < this._impostors.length; ++i) {
  59647. if (this._impostors[i].object === object) {
  59648. return this._impostors[i];
  59649. }
  59650. }
  59651. };
  59652. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  59653. for (var i = 0; i < this._impostors.length; ++i) {
  59654. if (this._impostors[i].physicsBody === body) {
  59655. return this._impostors[i];
  59656. }
  59657. }
  59658. };
  59659. return PhysicsEngine;
  59660. }());
  59661. // Statics
  59662. PhysicsEngine.Epsilon = 0.001;
  59663. BABYLON.PhysicsEngine = PhysicsEngine;
  59664. })(BABYLON || (BABYLON = {}));
  59665. //# sourceMappingURL=babylon.physicsEngine.js.map
  59666. var BABYLON;
  59667. (function (BABYLON) {
  59668. var CannonJSPlugin = (function () {
  59669. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  59670. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  59671. if (iterations === void 0) { iterations = 10; }
  59672. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  59673. this.name = "CannonJSPlugin";
  59674. this._physicsMaterials = [];
  59675. this._fixedTimeStep = 1 / 60;
  59676. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59677. this._currentCollisionGroup = 2;
  59678. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  59679. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  59680. this._tmpPosition = BABYLON.Vector3.Zero();
  59681. this._tmpQuaternion = new BABYLON.Quaternion();
  59682. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  59683. this._tmpDeltaRotation = new BABYLON.Quaternion();
  59684. this._tmpUnityRotation = new BABYLON.Quaternion();
  59685. if (!this.isSupported()) {
  59686. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  59687. return;
  59688. }
  59689. this.world = new CANNON.World();
  59690. this.world.broadphase = new CANNON.NaiveBroadphase();
  59691. this.world.solver.iterations = iterations;
  59692. }
  59693. CannonJSPlugin.prototype.setGravity = function (gravity) {
  59694. this.world.gravity.copy(gravity);
  59695. };
  59696. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  59697. this._fixedTimeStep = timeStep;
  59698. };
  59699. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  59700. // Delta is in seconds, should be provided in milliseconds
  59701. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  59702. };
  59703. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  59704. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59705. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59706. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  59707. };
  59708. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  59709. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  59710. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  59711. impostor.physicsBody.applyForce(impulse, worldPoint);
  59712. };
  59713. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  59714. //parent-child relationship. Does this impostor has a parent impostor?
  59715. if (impostor.parent) {
  59716. if (impostor.physicsBody) {
  59717. this.removePhysicsBody(impostor);
  59718. //TODO is that needed?
  59719. impostor.forceUpdate();
  59720. }
  59721. return;
  59722. }
  59723. //should a new body be created for this impostor?
  59724. if (impostor.isBodyInitRequired()) {
  59725. var shape = this._createShape(impostor);
  59726. //unregister events, if body is being changed
  59727. var oldBody = impostor.physicsBody;
  59728. if (oldBody) {
  59729. this.removePhysicsBody(impostor);
  59730. }
  59731. //create the body and material
  59732. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  59733. var bodyCreationObject = {
  59734. mass: impostor.getParam("mass"),
  59735. material: material
  59736. };
  59737. // A simple extend, in case native options were used.
  59738. var nativeOptions = impostor.getParam("nativeOptions");
  59739. for (var key in nativeOptions) {
  59740. if (nativeOptions.hasOwnProperty(key)) {
  59741. bodyCreationObject[key] = nativeOptions[key];
  59742. }
  59743. }
  59744. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  59745. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  59746. this.world.addEventListener("preStep", impostor.beforeStep);
  59747. this.world.addEventListener("postStep", impostor.afterStep);
  59748. impostor.physicsBody.addShape(shape);
  59749. this.world.add(impostor.physicsBody);
  59750. //try to keep the body moving in the right direction by taking old properties.
  59751. //Should be tested!
  59752. if (oldBody) {
  59753. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  59754. impostor.physicsBody[param].copy(oldBody[param]);
  59755. });
  59756. }
  59757. this._processChildMeshes(impostor);
  59758. }
  59759. //now update the body's transformation
  59760. this._updatePhysicsBodyTransformation(impostor);
  59761. };
  59762. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  59763. var _this = this;
  59764. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  59765. if (meshChildren.length) {
  59766. var processMesh = function (localPosition, mesh) {
  59767. var childImpostor = mesh.getPhysicsImpostor();
  59768. if (childImpostor) {
  59769. var parent = childImpostor.parent;
  59770. if (parent !== mainImpostor) {
  59771. var localPosition = mesh.position;
  59772. if (childImpostor.physicsBody) {
  59773. _this.removePhysicsBody(childImpostor);
  59774. childImpostor.physicsBody = null;
  59775. }
  59776. childImpostor.parent = mainImpostor;
  59777. childImpostor.resetUpdateFlags();
  59778. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  59779. //Add the mass of the children.
  59780. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  59781. }
  59782. }
  59783. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  59784. };
  59785. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  59786. }
  59787. };
  59788. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  59789. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  59790. this.world.removeEventListener("preStep", impostor.beforeStep);
  59791. this.world.removeEventListener("postStep", impostor.afterStep);
  59792. this.world.remove(impostor.physicsBody);
  59793. };
  59794. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  59795. var mainBody = impostorJoint.mainImpostor.physicsBody;
  59796. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  59797. if (!mainBody || !connectedBody) {
  59798. return;
  59799. }
  59800. var constraint;
  59801. var jointData = impostorJoint.joint.jointData;
  59802. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  59803. var constraintData = {
  59804. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  59805. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  59806. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  59807. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  59808. maxForce: jointData.nativeParams.maxForce,
  59809. collideConnected: !!jointData.collision
  59810. };
  59811. switch (impostorJoint.joint.type) {
  59812. case BABYLON.PhysicsJoint.HingeJoint:
  59813. case BABYLON.PhysicsJoint.Hinge2Joint:
  59814. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  59815. break;
  59816. case BABYLON.PhysicsJoint.DistanceJoint:
  59817. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  59818. break;
  59819. case BABYLON.PhysicsJoint.SpringJoint:
  59820. var springData = jointData;
  59821. constraint = new CANNON.Spring(mainBody, connectedBody, {
  59822. restLength: springData.length,
  59823. stiffness: springData.stiffness,
  59824. damping: springData.damping,
  59825. localAnchorA: constraintData.pivotA,
  59826. localAnchorB: constraintData.pivotB
  59827. });
  59828. break;
  59829. case BABYLON.PhysicsJoint.LockJoint:
  59830. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  59831. break;
  59832. case BABYLON.PhysicsJoint.PointToPointJoint:
  59833. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  59834. default:
  59835. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  59836. break;
  59837. }
  59838. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  59839. constraint.collideConnected = !!jointData.collision;
  59840. impostorJoint.joint.physicsJoint = constraint;
  59841. //don't add spring as constraint, as it is not one.
  59842. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  59843. this.world.addConstraint(constraint);
  59844. }
  59845. else {
  59846. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  59847. constraint.applyForce();
  59848. });
  59849. }
  59850. };
  59851. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  59852. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  59853. };
  59854. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  59855. var index;
  59856. var mat;
  59857. for (index = 0; index < this._physicsMaterials.length; index++) {
  59858. mat = this._physicsMaterials[index];
  59859. if (mat.friction === friction && mat.restitution === restitution) {
  59860. return mat;
  59861. }
  59862. }
  59863. var currentMat = new CANNON.Material(name);
  59864. currentMat.friction = friction;
  59865. currentMat.restitution = restitution;
  59866. this._physicsMaterials.push(currentMat);
  59867. return currentMat;
  59868. };
  59869. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  59870. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  59871. };
  59872. CannonJSPlugin.prototype._createShape = function (impostor) {
  59873. var object = impostor.object;
  59874. var returnValue;
  59875. var extendSize = impostor.getObjectExtendSize();
  59876. switch (impostor.type) {
  59877. case BABYLON.PhysicsImpostor.SphereImpostor:
  59878. var radiusX = extendSize.x;
  59879. var radiusY = extendSize.y;
  59880. var radiusZ = extendSize.z;
  59881. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  59882. break;
  59883. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  59884. case BABYLON.PhysicsImpostor.CylinderImpostor:
  59885. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  59886. break;
  59887. case BABYLON.PhysicsImpostor.BoxImpostor:
  59888. var box = extendSize.scale(0.5);
  59889. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  59890. break;
  59891. case BABYLON.PhysicsImpostor.PlaneImpostor:
  59892. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  59893. returnValue = new CANNON.Plane();
  59894. break;
  59895. case BABYLON.PhysicsImpostor.MeshImpostor:
  59896. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  59897. var rawFaces = object.getIndices ? object.getIndices() : [];
  59898. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  59899. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  59900. break;
  59901. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  59902. returnValue = this._createHeightmap(object);
  59903. break;
  59904. case BABYLON.PhysicsImpostor.ParticleImpostor:
  59905. returnValue = new CANNON.Particle();
  59906. break;
  59907. }
  59908. return returnValue;
  59909. };
  59910. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  59911. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59912. var matrix = [];
  59913. //For now pointDepth will not be used and will be automatically calculated.
  59914. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  59915. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  59916. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59917. var elementSize = dim * 2 / arraySize;
  59918. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59919. for (var i = 0; i < pos.length; i = i + 3) {
  59920. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  59921. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  59922. var y = pos[i + 1] + minY;
  59923. if (!matrix[x]) {
  59924. matrix[x] = [];
  59925. }
  59926. if (!matrix[x][z]) {
  59927. matrix[x][z] = y;
  59928. }
  59929. matrix[x][z] = Math.max(y, matrix[x][z]);
  59930. }
  59931. for (var x = 0; x <= arraySize; ++x) {
  59932. if (!matrix[x]) {
  59933. var loc = 1;
  59934. while (!matrix[(x + loc) % arraySize]) {
  59935. loc++;
  59936. }
  59937. matrix[x] = matrix[(x + loc) % arraySize].slice();
  59938. //console.log("missing x", x);
  59939. }
  59940. for (var z = 0; z <= arraySize; ++z) {
  59941. if (!matrix[x][z]) {
  59942. var loc = 1;
  59943. var newValue;
  59944. while (newValue === undefined) {
  59945. newValue = matrix[x][(z + loc++) % arraySize];
  59946. }
  59947. matrix[x][z] = newValue;
  59948. }
  59949. }
  59950. }
  59951. var shape = new CANNON.Heightfield(matrix, {
  59952. elementSize: elementSize
  59953. });
  59954. //For future reference, needed for body transformation
  59955. shape.minY = minY;
  59956. return shape;
  59957. };
  59958. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  59959. var object = impostor.object;
  59960. //make sure it is updated...
  59961. object.computeWorldMatrix && object.computeWorldMatrix(true);
  59962. // The delta between the mesh position and the mesh bounding box center
  59963. var center = impostor.getObjectCenter();
  59964. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  59965. this._tmpPosition.copyFrom(center);
  59966. var quaternion = object.rotationQuaternion;
  59967. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  59968. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  59969. //-90 DEG in X, precalculated
  59970. quaternion = quaternion.multiply(this._minus90X);
  59971. //Invert! (Precalculated, 90 deg in X)
  59972. //No need to clone. this will never change.
  59973. impostor.setDeltaRotation(this._plus90X);
  59974. }
  59975. //If it is a heightfield, if should be centered.
  59976. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  59977. var mesh = object;
  59978. //calculate the correct body position:
  59979. var rotationQuaternion = mesh.rotationQuaternion;
  59980. mesh.rotationQuaternion = this._tmpUnityRotation;
  59981. mesh.computeWorldMatrix(true);
  59982. //get original center with no rotation
  59983. var c = center.clone();
  59984. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  59985. //rotation is back
  59986. mesh.rotationQuaternion = rotationQuaternion;
  59987. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  59988. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  59989. mesh.setPivotMatrix(p);
  59990. mesh.computeWorldMatrix(true);
  59991. //calculate the translation
  59992. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  59993. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  59994. //add it inverted to the delta
  59995. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  59996. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  59997. mesh.setPivotMatrix(oldPivot);
  59998. mesh.computeWorldMatrix(true);
  59999. }
  60000. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  60001. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  60002. this._tmpPosition.copyFrom(object.position);
  60003. }
  60004. impostor.setDeltaPosition(this._tmpDeltaPosition);
  60005. //Now update the impostor object
  60006. impostor.physicsBody.position.copy(this._tmpPosition);
  60007. impostor.physicsBody.quaternion.copy(quaternion);
  60008. };
  60009. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  60010. impostor.object.position.copyFrom(impostor.physicsBody.position);
  60011. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  60012. };
  60013. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  60014. impostor.physicsBody.position.copy(newPosition);
  60015. impostor.physicsBody.quaternion.copy(newRotation);
  60016. };
  60017. CannonJSPlugin.prototype.isSupported = function () {
  60018. return window.CANNON !== undefined;
  60019. };
  60020. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  60021. impostor.physicsBody.velocity.copy(velocity);
  60022. };
  60023. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  60024. impostor.physicsBody.angularVelocity.copy(velocity);
  60025. };
  60026. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  60027. var v = impostor.physicsBody.velocity;
  60028. if (!v)
  60029. return null;
  60030. return new BABYLON.Vector3(v.x, v.y, v.z);
  60031. };
  60032. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  60033. var v = impostor.physicsBody.angularVelocity;
  60034. if (!v)
  60035. return null;
  60036. return new BABYLON.Vector3(v.x, v.y, v.z);
  60037. };
  60038. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  60039. impostor.physicsBody.mass = mass;
  60040. impostor.physicsBody.updateMassProperties();
  60041. };
  60042. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  60043. return impostor.physicsBody.mass;
  60044. };
  60045. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  60046. return impostor.physicsBody.material.friction;
  60047. };
  60048. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  60049. impostor.physicsBody.material.friction = friction;
  60050. };
  60051. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  60052. return impostor.physicsBody.material.restitution;
  60053. };
  60054. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  60055. impostor.physicsBody.material.restitution = restitution;
  60056. };
  60057. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  60058. impostor.physicsBody.sleep();
  60059. };
  60060. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  60061. impostor.physicsBody.wakeUp();
  60062. };
  60063. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  60064. joint.physicsJoint.distance = maxDistance;
  60065. };
  60066. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  60067. if (!motorIndex) {
  60068. joint.physicsJoint.enableMotor();
  60069. }
  60070. };
  60071. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  60072. if (!motorIndex) {
  60073. joint.physicsJoint.disableMotor();
  60074. }
  60075. };
  60076. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  60077. if (!motorIndex) {
  60078. joint.physicsJoint.enableMotor();
  60079. joint.physicsJoint.setMotorSpeed(speed);
  60080. if (maxForce) {
  60081. this.setLimit(joint, maxForce);
  60082. }
  60083. }
  60084. };
  60085. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  60086. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  60087. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  60088. };
  60089. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  60090. var body = impostor.physicsBody;
  60091. mesh.position.x = body.position.x;
  60092. mesh.position.y = body.position.y;
  60093. mesh.position.z = body.position.z;
  60094. mesh.rotationQuaternion.x = body.quaternion.x;
  60095. mesh.rotationQuaternion.y = body.quaternion.y;
  60096. mesh.rotationQuaternion.z = body.quaternion.z;
  60097. mesh.rotationQuaternion.w = body.quaternion.w;
  60098. };
  60099. CannonJSPlugin.prototype.getRadius = function (impostor) {
  60100. var shape = impostor.physicsBody.shapes[0];
  60101. return shape.boundingSphereRadius;
  60102. };
  60103. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  60104. var shape = impostor.physicsBody.shapes[0];
  60105. result.x = shape.halfExtents.x * 2;
  60106. result.y = shape.halfExtents.y * 2;
  60107. result.z = shape.halfExtents.z * 2;
  60108. };
  60109. CannonJSPlugin.prototype.dispose = function () {
  60110. };
  60111. return CannonJSPlugin;
  60112. }());
  60113. BABYLON.CannonJSPlugin = CannonJSPlugin;
  60114. })(BABYLON || (BABYLON = {}));
  60115. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  60116. var BABYLON;
  60117. (function (BABYLON) {
  60118. var OimoJSPlugin = (function () {
  60119. function OimoJSPlugin(iterations) {
  60120. this.name = "OimoJSPlugin";
  60121. this._tmpImpostorsArray = [];
  60122. this._tmpPositionVector = BABYLON.Vector3.Zero();
  60123. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  60124. this.world.worldscale(1);
  60125. this.world.clear();
  60126. //making sure no stats are calculated
  60127. this.world.isNoStat = true;
  60128. }
  60129. OimoJSPlugin.prototype.setGravity = function (gravity) {
  60130. this.world.gravity.copy(gravity);
  60131. };
  60132. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  60133. this.world.timeStep = timeStep;
  60134. };
  60135. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  60136. var _this = this;
  60137. impostors.forEach(function (impostor) {
  60138. impostor.beforeStep();
  60139. });
  60140. this.world.step();
  60141. impostors.forEach(function (impostor) {
  60142. impostor.afterStep();
  60143. //update the ordered impostors array
  60144. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  60145. });
  60146. //check for collisions
  60147. var contact = this.world.contacts;
  60148. while (contact !== null) {
  60149. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  60150. contact = contact.next;
  60151. continue;
  60152. }
  60153. //is this body colliding with any other? get the impostor
  60154. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  60155. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  60156. if (!mainImpostor || !collidingImpostor) {
  60157. contact = contact.next;
  60158. continue;
  60159. }
  60160. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  60161. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  60162. contact = contact.next;
  60163. }
  60164. };
  60165. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  60166. var mass = impostor.physicsBody.massInfo.mass;
  60167. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  60168. };
  60169. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  60170. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  60171. this.applyImpulse(impostor, force, contactPoint);
  60172. };
  60173. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  60174. var _this = this;
  60175. //parent-child relationship. Does this impostor has a parent impostor?
  60176. if (impostor.parent) {
  60177. if (impostor.physicsBody) {
  60178. this.removePhysicsBody(impostor);
  60179. //TODO is that needed?
  60180. impostor.forceUpdate();
  60181. }
  60182. return;
  60183. }
  60184. if (impostor.isBodyInitRequired()) {
  60185. var bodyConfig = {
  60186. name: impostor.uniqueId,
  60187. //Oimo must have mass, also for static objects.
  60188. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  60189. size: [],
  60190. type: [],
  60191. pos: [],
  60192. rot: [],
  60193. move: impostor.getParam("mass") !== 0,
  60194. //Supporting older versions of Oimo
  60195. world: this.world
  60196. };
  60197. var impostors = [impostor];
  60198. var addToArray = function (parent) {
  60199. if (!parent.getChildMeshes)
  60200. return;
  60201. parent.getChildMeshes().forEach(function (m) {
  60202. if (m.physicsImpostor) {
  60203. impostors.push(m.physicsImpostor);
  60204. m.physicsImpostor._init();
  60205. }
  60206. });
  60207. };
  60208. addToArray(impostor.object);
  60209. var checkWithEpsilon_1 = function (value) {
  60210. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  60211. };
  60212. impostors.forEach(function (i) {
  60213. //get the correct bounding box
  60214. var oldQuaternion = i.object.rotationQuaternion;
  60215. var rot = new OIMO.Euler().setFromQuaternion({
  60216. x: impostor.object.rotationQuaternion.x,
  60217. y: impostor.object.rotationQuaternion.y,
  60218. z: impostor.object.rotationQuaternion.z,
  60219. s: impostor.object.rotationQuaternion.w
  60220. });
  60221. var extendSize = i.getObjectExtendSize();
  60222. if (i === impostor) {
  60223. var center = impostor.getObjectCenter();
  60224. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  60225. //Can also use Array.prototype.push.apply
  60226. bodyConfig.pos.push(center.x);
  60227. bodyConfig.pos.push(center.y);
  60228. bodyConfig.pos.push(center.z);
  60229. //tmp solution
  60230. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  60231. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  60232. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  60233. }
  60234. else {
  60235. bodyConfig.pos.push(i.object.position.x);
  60236. bodyConfig.pos.push(i.object.position.y);
  60237. bodyConfig.pos.push(i.object.position.z);
  60238. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  60239. bodyConfig.rot.push(0);
  60240. bodyConfig.rot.push(0);
  60241. bodyConfig.rot.push(0);
  60242. }
  60243. // register mesh
  60244. switch (i.type) {
  60245. case BABYLON.PhysicsImpostor.ParticleImpostor:
  60246. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  60247. case BABYLON.PhysicsImpostor.SphereImpostor:
  60248. var radiusX = extendSize.x;
  60249. var radiusY = extendSize.y;
  60250. var radiusZ = extendSize.z;
  60251. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  60252. bodyConfig.type.push('sphere');
  60253. //due to the way oimo works with compounds, add 3 times
  60254. bodyConfig.size.push(size);
  60255. bodyConfig.size.push(size);
  60256. bodyConfig.size.push(size);
  60257. break;
  60258. case BABYLON.PhysicsImpostor.CylinderImpostor:
  60259. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  60260. var sizeY = checkWithEpsilon_1(extendSize.y);
  60261. bodyConfig.type.push('cylinder');
  60262. bodyConfig.size.push(sizeX);
  60263. bodyConfig.size.push(sizeY);
  60264. //due to the way oimo works with compounds, add one more value.
  60265. bodyConfig.size.push(sizeY);
  60266. break;
  60267. case BABYLON.PhysicsImpostor.PlaneImpostor:
  60268. case BABYLON.PhysicsImpostor.BoxImpostor:
  60269. default:
  60270. var sizeX = checkWithEpsilon_1(extendSize.x);
  60271. var sizeY = checkWithEpsilon_1(extendSize.y);
  60272. var sizeZ = checkWithEpsilon_1(extendSize.z);
  60273. bodyConfig.type.push('box');
  60274. bodyConfig.size.push(sizeX);
  60275. bodyConfig.size.push(sizeY);
  60276. bodyConfig.size.push(sizeZ);
  60277. break;
  60278. }
  60279. //actually not needed, but hey...
  60280. i.object.rotationQuaternion = oldQuaternion;
  60281. });
  60282. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  60283. }
  60284. else {
  60285. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  60286. }
  60287. impostor.setDeltaPosition(this._tmpPositionVector);
  60288. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  60289. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  60290. };
  60291. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  60292. //impostor.physicsBody.dispose();
  60293. //Same as : (older oimo versions)
  60294. this.world.removeRigidBody(impostor.physicsBody);
  60295. };
  60296. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  60297. var mainBody = impostorJoint.mainImpostor.physicsBody;
  60298. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  60299. if (!mainBody || !connectedBody) {
  60300. return;
  60301. }
  60302. var jointData = impostorJoint.joint.jointData;
  60303. var options = jointData.nativeParams || {};
  60304. var type;
  60305. var nativeJointData = {
  60306. body1: mainBody,
  60307. body2: connectedBody,
  60308. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  60309. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  60310. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  60311. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  60312. min: options.min,
  60313. max: options.max,
  60314. collision: options.collision || jointData.collision,
  60315. spring: options.spring,
  60316. //supporting older version of Oimo
  60317. world: this.world
  60318. };
  60319. switch (impostorJoint.joint.type) {
  60320. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  60321. type = "jointBall";
  60322. break;
  60323. case BABYLON.PhysicsJoint.SpringJoint:
  60324. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  60325. var springData = jointData;
  60326. nativeJointData.min = springData.length || nativeJointData.min;
  60327. //Max should also be set, just make sure it is at least min
  60328. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  60329. case BABYLON.PhysicsJoint.DistanceJoint:
  60330. type = "jointDistance";
  60331. nativeJointData.max = jointData.maxDistance;
  60332. break;
  60333. case BABYLON.PhysicsJoint.PrismaticJoint:
  60334. type = "jointPrisme";
  60335. break;
  60336. case BABYLON.PhysicsJoint.SliderJoint:
  60337. type = "jointSlide";
  60338. break;
  60339. case BABYLON.PhysicsJoint.WheelJoint:
  60340. type = "jointWheel";
  60341. break;
  60342. case BABYLON.PhysicsJoint.HingeJoint:
  60343. default:
  60344. type = "jointHinge";
  60345. break;
  60346. }
  60347. nativeJointData.type = type;
  60348. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  60349. };
  60350. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  60351. //Bug in Oimo prevents us from disposing a joint in the playground
  60352. //joint.joint.physicsJoint.dispose();
  60353. //So we will bruteforce it!
  60354. try {
  60355. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  60356. }
  60357. catch (e) {
  60358. BABYLON.Tools.Warn(e);
  60359. }
  60360. };
  60361. OimoJSPlugin.prototype.isSupported = function () {
  60362. return OIMO !== undefined;
  60363. };
  60364. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  60365. if (!impostor.physicsBody.sleeping) {
  60366. //TODO check that
  60367. if (impostor.physicsBody.shapes.next) {
  60368. var parentShape = this._getLastShape(impostor.physicsBody);
  60369. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  60370. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  60371. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  60372. }
  60373. else {
  60374. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  60375. }
  60376. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  60377. impostor.object.rotationQuaternion.normalize();
  60378. }
  60379. };
  60380. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  60381. var body = impostor.physicsBody;
  60382. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  60383. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  60384. body.syncShapes();
  60385. body.awake();
  60386. };
  60387. OimoJSPlugin.prototype._getLastShape = function (body) {
  60388. var lastShape = body.shapes;
  60389. while (lastShape.next) {
  60390. lastShape = lastShape.next;
  60391. }
  60392. return lastShape;
  60393. };
  60394. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  60395. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  60396. };
  60397. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  60398. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  60399. };
  60400. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  60401. var v = impostor.physicsBody.linearVelocity;
  60402. if (!v)
  60403. return null;
  60404. return new BABYLON.Vector3(v.x, v.y, v.z);
  60405. };
  60406. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  60407. var v = impostor.physicsBody.angularVelocity;
  60408. if (!v)
  60409. return null;
  60410. return new BABYLON.Vector3(v.x, v.y, v.z);
  60411. };
  60412. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  60413. var staticBody = mass === 0;
  60414. //this will actually set the body's density and not its mass.
  60415. //But this is how oimo treats the mass variable.
  60416. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  60417. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  60418. };
  60419. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  60420. return impostor.physicsBody.shapes.density;
  60421. };
  60422. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  60423. return impostor.physicsBody.shapes.friction;
  60424. };
  60425. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  60426. impostor.physicsBody.shapes.friction = friction;
  60427. };
  60428. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  60429. return impostor.physicsBody.shapes.restitution;
  60430. };
  60431. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  60432. impostor.physicsBody.shapes.restitution = restitution;
  60433. };
  60434. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  60435. impostor.physicsBody.sleep();
  60436. };
  60437. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  60438. impostor.physicsBody.awake();
  60439. };
  60440. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  60441. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  60442. if (minDistance !== void 0) {
  60443. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  60444. }
  60445. };
  60446. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  60447. //TODO separate rotational and transational motors.
  60448. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  60449. if (motor) {
  60450. motor.setMotor(speed, maxForce);
  60451. }
  60452. };
  60453. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  60454. //TODO separate rotational and transational motors.
  60455. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  60456. if (motor) {
  60457. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  60458. }
  60459. };
  60460. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  60461. var body = impostor.physicsBody;
  60462. mesh.position.x = body.position.x;
  60463. mesh.position.y = body.position.y;
  60464. mesh.position.z = body.position.z;
  60465. mesh.rotationQuaternion.x = body.orientation.x;
  60466. mesh.rotationQuaternion.y = body.orientation.y;
  60467. mesh.rotationQuaternion.z = body.orientation.z;
  60468. mesh.rotationQuaternion.w = body.orientation.s;
  60469. };
  60470. OimoJSPlugin.prototype.getRadius = function (impostor) {
  60471. return impostor.physicsBody.shapes.radius;
  60472. };
  60473. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  60474. var shape = impostor.physicsBody.shapes;
  60475. result.x = shape.halfWidth * 2;
  60476. result.y = shape.halfHeight * 2;
  60477. result.z = shape.halfDepth * 2;
  60478. };
  60479. OimoJSPlugin.prototype.dispose = function () {
  60480. this.world.clear();
  60481. };
  60482. return OimoJSPlugin;
  60483. }());
  60484. BABYLON.OimoJSPlugin = OimoJSPlugin;
  60485. })(BABYLON || (BABYLON = {}));
  60486. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  60487. var BABYLON;
  60488. (function (BABYLON) {
  60489. var Internals;
  60490. (function (Internals) {
  60491. /*
  60492. * Based on jsTGALoader - Javascript loader for TGA file
  60493. * By Vincent Thibault
  60494. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  60495. */
  60496. var TGATools = (function () {
  60497. function TGATools() {
  60498. }
  60499. TGATools.GetTGAHeader = function (data) {
  60500. var offset = 0;
  60501. var header = {
  60502. id_length: data[offset++],
  60503. colormap_type: data[offset++],
  60504. image_type: data[offset++],
  60505. colormap_index: data[offset++] | data[offset++] << 8,
  60506. colormap_length: data[offset++] | data[offset++] << 8,
  60507. colormap_size: data[offset++],
  60508. origin: [
  60509. data[offset++] | data[offset++] << 8,
  60510. data[offset++] | data[offset++] << 8
  60511. ],
  60512. width: data[offset++] | data[offset++] << 8,
  60513. height: data[offset++] | data[offset++] << 8,
  60514. pixel_size: data[offset++],
  60515. flags: data[offset++]
  60516. };
  60517. return header;
  60518. };
  60519. TGATools.UploadContent = function (gl, data) {
  60520. // Not enough data to contain header ?
  60521. if (data.length < 19) {
  60522. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  60523. return;
  60524. }
  60525. // Read Header
  60526. var offset = 18;
  60527. var header = TGATools.GetTGAHeader(data);
  60528. // Assume it's a valid Targa file.
  60529. if (header.id_length + offset > data.length) {
  60530. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  60531. return;
  60532. }
  60533. // Skip not needed data
  60534. offset += header.id_length;
  60535. var use_rle = false;
  60536. var use_pal = false;
  60537. var use_rgb = false;
  60538. var use_grey = false;
  60539. // Get some informations.
  60540. switch (header.image_type) {
  60541. case TGATools._TYPE_RLE_INDEXED:
  60542. use_rle = true;
  60543. case TGATools._TYPE_INDEXED:
  60544. use_pal = true;
  60545. break;
  60546. case TGATools._TYPE_RLE_RGB:
  60547. use_rle = true;
  60548. case TGATools._TYPE_RGB:
  60549. use_rgb = true;
  60550. break;
  60551. case TGATools._TYPE_RLE_GREY:
  60552. use_rle = true;
  60553. case TGATools._TYPE_GREY:
  60554. use_grey = true;
  60555. break;
  60556. }
  60557. var pixel_data;
  60558. var numAlphaBits = header.flags & 0xf;
  60559. var pixel_size = header.pixel_size >> 3;
  60560. var pixel_total = header.width * header.height * pixel_size;
  60561. // Read palettes
  60562. var palettes;
  60563. if (use_pal) {
  60564. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  60565. }
  60566. // Read LRE
  60567. if (use_rle) {
  60568. pixel_data = new Uint8Array(pixel_total);
  60569. var c, count, i;
  60570. var localOffset = 0;
  60571. var pixels = new Uint8Array(pixel_size);
  60572. while (offset < pixel_total && localOffset < pixel_total) {
  60573. c = data[offset++];
  60574. count = (c & 0x7f) + 1;
  60575. // RLE pixels
  60576. if (c & 0x80) {
  60577. // Bind pixel tmp array
  60578. for (i = 0; i < pixel_size; ++i) {
  60579. pixels[i] = data[offset++];
  60580. }
  60581. // Copy pixel array
  60582. for (i = 0; i < count; ++i) {
  60583. pixel_data.set(pixels, localOffset + i * pixel_size);
  60584. }
  60585. localOffset += pixel_size * count;
  60586. }
  60587. else {
  60588. count *= pixel_size;
  60589. for (i = 0; i < count; ++i) {
  60590. pixel_data[localOffset + i] = data[offset++];
  60591. }
  60592. localOffset += count;
  60593. }
  60594. }
  60595. }
  60596. else {
  60597. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  60598. }
  60599. // Load to texture
  60600. var x_start, y_start, x_step, y_step, y_end, x_end;
  60601. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  60602. default:
  60603. case TGATools._ORIGIN_UL:
  60604. x_start = 0;
  60605. x_step = 1;
  60606. x_end = header.width;
  60607. y_start = 0;
  60608. y_step = 1;
  60609. y_end = header.height;
  60610. break;
  60611. case TGATools._ORIGIN_BL:
  60612. x_start = 0;
  60613. x_step = 1;
  60614. x_end = header.width;
  60615. y_start = header.height - 1;
  60616. y_step = -1;
  60617. y_end = -1;
  60618. break;
  60619. case TGATools._ORIGIN_UR:
  60620. x_start = header.width - 1;
  60621. x_step = -1;
  60622. x_end = -1;
  60623. y_start = 0;
  60624. y_step = 1;
  60625. y_end = header.height;
  60626. break;
  60627. case TGATools._ORIGIN_BR:
  60628. x_start = header.width - 1;
  60629. x_step = -1;
  60630. x_end = -1;
  60631. y_start = header.height - 1;
  60632. y_step = -1;
  60633. y_end = -1;
  60634. break;
  60635. }
  60636. // Load the specify method
  60637. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  60638. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  60639. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  60640. };
  60641. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60642. var image = pixel_data, colormap = palettes;
  60643. var width = header.width, height = header.height;
  60644. var color, i = 0, x, y;
  60645. var imageData = new Uint8Array(width * height * 4);
  60646. for (y = y_start; y !== y_end; y += y_step) {
  60647. for (x = x_start; x !== x_end; x += x_step, i++) {
  60648. color = image[i];
  60649. imageData[(x + width * y) * 4 + 3] = 255;
  60650. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  60651. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  60652. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  60653. }
  60654. }
  60655. return imageData;
  60656. };
  60657. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60658. var image = pixel_data;
  60659. var width = header.width, height = header.height;
  60660. var color, i = 0, x, y;
  60661. var imageData = new Uint8Array(width * height * 4);
  60662. for (y = y_start; y !== y_end; y += y_step) {
  60663. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60664. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  60665. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  60666. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  60667. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  60668. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  60669. }
  60670. }
  60671. return imageData;
  60672. };
  60673. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60674. var image = pixel_data;
  60675. var width = header.width, height = header.height;
  60676. var i = 0, x, y;
  60677. var imageData = new Uint8Array(width * height * 4);
  60678. for (y = y_start; y !== y_end; y += y_step) {
  60679. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  60680. imageData[(x + width * y) * 4 + 3] = 255;
  60681. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60682. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60683. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60684. }
  60685. }
  60686. return imageData;
  60687. };
  60688. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60689. var image = pixel_data;
  60690. var width = header.width, height = header.height;
  60691. var i = 0, x, y;
  60692. var imageData = new Uint8Array(width * height * 4);
  60693. for (y = y_start; y !== y_end; y += y_step) {
  60694. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  60695. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60696. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  60697. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  60698. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  60699. }
  60700. }
  60701. return imageData;
  60702. };
  60703. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60704. var image = pixel_data;
  60705. var width = header.width, height = header.height;
  60706. var color, i = 0, x, y;
  60707. var imageData = new Uint8Array(width * height * 4);
  60708. for (y = y_start; y !== y_end; y += y_step) {
  60709. for (x = x_start; x !== x_end; x += x_step, i++) {
  60710. color = image[i];
  60711. imageData[(x + width * y) * 4 + 0] = color;
  60712. imageData[(x + width * y) * 4 + 1] = color;
  60713. imageData[(x + width * y) * 4 + 2] = color;
  60714. imageData[(x + width * y) * 4 + 3] = 255;
  60715. }
  60716. }
  60717. return imageData;
  60718. };
  60719. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  60720. var image = pixel_data;
  60721. var width = header.width, height = header.height;
  60722. var i = 0, x, y;
  60723. var imageData = new Uint8Array(width * height * 4);
  60724. for (y = y_start; y !== y_end; y += y_step) {
  60725. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  60726. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  60727. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  60728. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  60729. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  60730. }
  60731. }
  60732. return imageData;
  60733. };
  60734. return TGATools;
  60735. }());
  60736. TGATools._TYPE_NO_DATA = 0;
  60737. TGATools._TYPE_INDEXED = 1;
  60738. TGATools._TYPE_RGB = 2;
  60739. TGATools._TYPE_GREY = 3;
  60740. TGATools._TYPE_RLE_INDEXED = 9;
  60741. TGATools._TYPE_RLE_RGB = 10;
  60742. TGATools._TYPE_RLE_GREY = 11;
  60743. TGATools._ORIGIN_MASK = 0x30;
  60744. TGATools._ORIGIN_SHIFT = 0x04;
  60745. TGATools._ORIGIN_BL = 0x00;
  60746. TGATools._ORIGIN_BR = 0x01;
  60747. TGATools._ORIGIN_UL = 0x02;
  60748. TGATools._ORIGIN_UR = 0x03;
  60749. Internals.TGATools = TGATools;
  60750. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60751. })(BABYLON || (BABYLON = {}));
  60752. //# sourceMappingURL=babylon.tga.js.map
  60753. var BABYLON;
  60754. (function (BABYLON) {
  60755. var Internals;
  60756. (function (Internals) {
  60757. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  60758. // All values and structures referenced from:
  60759. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  60760. var DDS_MAGIC = 0x20534444;
  60761. 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;
  60762. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  60763. 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;
  60764. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  60765. function FourCCToInt32(value) {
  60766. return value.charCodeAt(0) +
  60767. (value.charCodeAt(1) << 8) +
  60768. (value.charCodeAt(2) << 16) +
  60769. (value.charCodeAt(3) << 24);
  60770. }
  60771. function Int32ToFourCC(value) {
  60772. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  60773. }
  60774. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  60775. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  60776. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  60777. var FOURCC_DX10 = FourCCToInt32("DX10");
  60778. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  60779. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  60780. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  60781. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  60782. var headerLengthInt = 31; // The header length in 32 bit ints
  60783. // Offsets into the header array
  60784. var off_magic = 0;
  60785. var off_size = 1;
  60786. var off_flags = 2;
  60787. var off_height = 3;
  60788. var off_width = 4;
  60789. var off_mipmapCount = 7;
  60790. var off_pfFlags = 20;
  60791. var off_pfFourCC = 21;
  60792. var off_RGBbpp = 22;
  60793. var off_RMask = 23;
  60794. var off_GMask = 24;
  60795. var off_BMask = 25;
  60796. var off_AMask = 26;
  60797. var off_caps1 = 27;
  60798. var off_caps2 = 28;
  60799. var off_caps3 = 29;
  60800. var off_caps4 = 30;
  60801. var off_dxgiFormat = 32;
  60802. ;
  60803. var DDSTools = (function () {
  60804. function DDSTools() {
  60805. }
  60806. DDSTools.GetDDSInfo = function (arrayBuffer) {
  60807. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  60808. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  60809. var mipmapCount = 1;
  60810. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  60811. mipmapCount = Math.max(1, header[off_mipmapCount]);
  60812. }
  60813. var fourCC = header[off_pfFourCC];
  60814. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  60815. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60816. switch (fourCC) {
  60817. case FOURCC_D3DFMT_R16G16B16A16F:
  60818. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60819. break;
  60820. case FOURCC_D3DFMT_R32G32B32A32F:
  60821. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60822. break;
  60823. case FOURCC_DX10:
  60824. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  60825. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60826. break;
  60827. }
  60828. }
  60829. return {
  60830. width: header[off_width],
  60831. height: header[off_height],
  60832. mipmapCount: mipmapCount,
  60833. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  60834. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  60835. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  60836. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  60837. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  60838. dxgiFormat: dxgiFormat,
  60839. textureType: textureType
  60840. };
  60841. };
  60842. DDSTools._ToHalfFloat = function (value) {
  60843. if (!DDSTools._FloatView) {
  60844. DDSTools._FloatView = new Float32Array(1);
  60845. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  60846. }
  60847. DDSTools._FloatView[0] = value;
  60848. var x = DDSTools._Int32View[0];
  60849. var bits = (x >> 16) & 0x8000; /* Get the sign */
  60850. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  60851. var e = (x >> 23) & 0xff; /* Using int is faster here */
  60852. /* If zero, or denormal, or exponent underflows too much for a denormal
  60853. * half, return signed zero. */
  60854. if (e < 103) {
  60855. return bits;
  60856. }
  60857. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  60858. if (e > 142) {
  60859. bits |= 0x7c00;
  60860. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  60861. * not Inf, so make sure we set one mantissa bit too. */
  60862. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  60863. return bits;
  60864. }
  60865. /* If exponent underflows but not too much, return a denormal */
  60866. if (e < 113) {
  60867. m |= 0x0800;
  60868. /* Extra rounding may overflow and set mantissa to 0 and exponent
  60869. * to 1, which is OK. */
  60870. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  60871. return bits;
  60872. }
  60873. bits |= ((e - 112) << 10) | (m >> 1);
  60874. bits += m & 1;
  60875. return bits;
  60876. };
  60877. DDSTools._FromHalfFloat = function (value) {
  60878. var s = (value & 0x8000) >> 15;
  60879. var e = (value & 0x7C00) >> 10;
  60880. var f = value & 0x03FF;
  60881. if (e === 0) {
  60882. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  60883. }
  60884. else if (e == 0x1F) {
  60885. return f ? NaN : ((s ? -1 : 1) * Infinity);
  60886. }
  60887. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  60888. };
  60889. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60890. var destArray = new Float32Array(dataLength);
  60891. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60892. var index = 0;
  60893. for (var y = 0; y < height; y++) {
  60894. for (var x = 0; x < width; x++) {
  60895. var srcPos = (x + y * width) * 4;
  60896. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  60897. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  60898. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  60899. if (DDSTools.StoreLODInAlphaChannel) {
  60900. destArray[index + 3] = lod;
  60901. }
  60902. else {
  60903. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  60904. }
  60905. index += 4;
  60906. }
  60907. }
  60908. return destArray;
  60909. };
  60910. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60911. if (DDSTools.StoreLODInAlphaChannel) {
  60912. var destArray = new Uint16Array(dataLength);
  60913. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60914. var index = 0;
  60915. for (var y = 0; y < height; y++) {
  60916. for (var x = 0; x < width; x++) {
  60917. var srcPos = (x + y * width) * 4;
  60918. destArray[index] = srcData[srcPos];
  60919. destArray[index + 1] = srcData[srcPos + 1];
  60920. destArray[index + 2] = srcData[srcPos + 2];
  60921. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  60922. index += 4;
  60923. }
  60924. }
  60925. return destArray;
  60926. }
  60927. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  60928. };
  60929. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60930. if (DDSTools.StoreLODInAlphaChannel) {
  60931. var destArray = new Float32Array(dataLength);
  60932. var srcData = new Float32Array(arrayBuffer, dataOffset);
  60933. var index = 0;
  60934. for (var y = 0; y < height; y++) {
  60935. for (var x = 0; x < width; x++) {
  60936. var srcPos = (x + y * width) * 4;
  60937. destArray[index] = srcData[srcPos];
  60938. destArray[index + 1] = srcData[srcPos + 1];
  60939. destArray[index + 2] = srcData[srcPos + 2];
  60940. destArray[index + 3] = lod;
  60941. index += 4;
  60942. }
  60943. }
  60944. return destArray;
  60945. }
  60946. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  60947. };
  60948. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60949. var destArray = new Uint8Array(dataLength);
  60950. var srcData = new Float32Array(arrayBuffer, dataOffset);
  60951. var index = 0;
  60952. for (var y = 0; y < height; y++) {
  60953. for (var x = 0; x < width; x++) {
  60954. var srcPos = (x + y * width) * 4;
  60955. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  60956. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  60957. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  60958. if (DDSTools.StoreLODInAlphaChannel) {
  60959. destArray[index + 3] = lod;
  60960. }
  60961. else {
  60962. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  60963. }
  60964. index += 4;
  60965. }
  60966. }
  60967. return destArray;
  60968. };
  60969. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  60970. var destArray = new Uint8Array(dataLength);
  60971. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  60972. var index = 0;
  60973. for (var y = 0; y < height; y++) {
  60974. for (var x = 0; x < width; x++) {
  60975. var srcPos = (x + y * width) * 4;
  60976. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  60977. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  60978. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  60979. if (DDSTools.StoreLODInAlphaChannel) {
  60980. destArray[index + 3] = lod;
  60981. }
  60982. else {
  60983. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  60984. }
  60985. index += 4;
  60986. }
  60987. }
  60988. return destArray;
  60989. };
  60990. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  60991. var byteArray = new Uint8Array(dataLength);
  60992. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  60993. var index = 0;
  60994. for (var y = 0; y < height; y++) {
  60995. for (var x = 0; x < width; x++) {
  60996. var srcPos = (x + y * width) * 4;
  60997. byteArray[index] = srcData[srcPos + 2];
  60998. byteArray[index + 1] = srcData[srcPos + 1];
  60999. byteArray[index + 2] = srcData[srcPos];
  61000. byteArray[index + 3] = srcData[srcPos + 3];
  61001. index += 4;
  61002. }
  61003. }
  61004. return byteArray;
  61005. };
  61006. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61007. var byteArray = new Uint8Array(dataLength);
  61008. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61009. var index = 0;
  61010. for (var y = 0; y < height; y++) {
  61011. for (var x = 0; x < width; x++) {
  61012. var srcPos = (x + y * width) * 3;
  61013. byteArray[index] = srcData[srcPos + 2];
  61014. byteArray[index + 1] = srcData[srcPos + 1];
  61015. byteArray[index + 2] = srcData[srcPos];
  61016. index += 3;
  61017. }
  61018. }
  61019. return byteArray;
  61020. };
  61021. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61022. var byteArray = new Uint8Array(dataLength);
  61023. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61024. var index = 0;
  61025. for (var y = 0; y < height; y++) {
  61026. for (var x = 0; x < width; x++) {
  61027. var srcPos = (x + y * width);
  61028. byteArray[index] = srcData[srcPos];
  61029. index++;
  61030. }
  61031. }
  61032. return byteArray;
  61033. };
  61034. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  61035. if (lodIndex === void 0) { lodIndex = -1; }
  61036. var gl = engine._gl;
  61037. var ext = engine.getCaps().s3tc;
  61038. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  61039. if (header[off_magic] != DDS_MAGIC) {
  61040. BABYLON.Tools.Error("Invalid magic number in DDS header");
  61041. return;
  61042. }
  61043. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  61044. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  61045. return;
  61046. }
  61047. if (info.isCompressed && !ext) {
  61048. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  61049. return;
  61050. }
  61051. var bpp = header[off_RGBbpp];
  61052. dataOffset = header[off_size] + 4;
  61053. var computeFormats = false;
  61054. if (info.isFourCC) {
  61055. fourCC = header[off_pfFourCC];
  61056. switch (fourCC) {
  61057. case FOURCC_DXT1:
  61058. blockBytes = 8;
  61059. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  61060. break;
  61061. case FOURCC_DXT3:
  61062. blockBytes = 16;
  61063. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  61064. break;
  61065. case FOURCC_DXT5:
  61066. blockBytes = 16;
  61067. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  61068. break;
  61069. case FOURCC_D3DFMT_R16G16B16A16F:
  61070. computeFormats = true;
  61071. break;
  61072. case FOURCC_D3DFMT_R32G32B32A32F:
  61073. computeFormats = true;
  61074. break;
  61075. case FOURCC_DX10:
  61076. // There is an additionnal header so dataOffset need to be changed
  61077. dataOffset += 5 * 4; // 5 uints
  61078. var supported = false;
  61079. switch (info.dxgiFormat) {
  61080. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  61081. computeFormats = true;
  61082. supported = true;
  61083. break;
  61084. case DXGI_FORMAT_B8G8R8X8_UNORM:
  61085. info.isRGB = true;
  61086. info.isFourCC = false;
  61087. bpp = 32;
  61088. supported = true;
  61089. break;
  61090. }
  61091. if (supported) {
  61092. break;
  61093. }
  61094. default:
  61095. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  61096. return;
  61097. }
  61098. }
  61099. if (computeFormats) {
  61100. format = engine._getWebGLTextureType(info.textureType);
  61101. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61102. }
  61103. mipmapCount = 1;
  61104. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  61105. mipmapCount = Math.max(1, header[off_mipmapCount]);
  61106. }
  61107. for (var face = 0; face < faces; face++) {
  61108. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  61109. width = header[off_width];
  61110. height = header[off_height];
  61111. for (mip = 0; mip < mipmapCount; ++mip) {
  61112. if (lodIndex === -1 || lodIndex === mip) {
  61113. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  61114. var i = (lodIndex === -1) ? mip : 0;
  61115. if (!info.isCompressed && info.isFourCC) {
  61116. dataLength = width * height * 4;
  61117. var floatArray;
  61118. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  61119. if (bpp === 128) {
  61120. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61121. }
  61122. else if (bpp === 64) {
  61123. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61124. }
  61125. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61126. format = engine._getWebGLTextureType(info.textureType);
  61127. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61128. }
  61129. else {
  61130. if (bpp === 128) {
  61131. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61132. }
  61133. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  61134. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61135. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61136. format = engine._getWebGLTextureType(info.textureType);
  61137. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61138. }
  61139. else {
  61140. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61141. }
  61142. }
  61143. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  61144. }
  61145. else if (info.isRGB) {
  61146. if (bpp === 24) {
  61147. dataLength = width * height * 3;
  61148. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61149. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  61150. }
  61151. else {
  61152. dataLength = width * height * 4;
  61153. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61154. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  61155. }
  61156. }
  61157. else if (info.isLuminance) {
  61158. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  61159. var unpaddedRowSize = width;
  61160. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  61161. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  61162. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61163. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  61164. }
  61165. else {
  61166. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  61167. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  61168. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  61169. }
  61170. }
  61171. dataOffset += width * height * (bpp / 8);
  61172. width *= 0.5;
  61173. height *= 0.5;
  61174. width = Math.max(1.0, width);
  61175. height = Math.max(1.0, height);
  61176. }
  61177. }
  61178. };
  61179. return DDSTools;
  61180. }());
  61181. DDSTools.StoreLODInAlphaChannel = false;
  61182. Internals.DDSTools = DDSTools;
  61183. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61184. })(BABYLON || (BABYLON = {}));
  61185. //# sourceMappingURL=babylon.dds.js.map
  61186. var BABYLON;
  61187. (function (BABYLON) {
  61188. var Internals;
  61189. (function (Internals) {
  61190. /**
  61191. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  61192. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  61193. */
  61194. var KhronosTextureContainer = (function () {
  61195. /**
  61196. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  61197. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  61198. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  61199. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  61200. */
  61201. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  61202. this.arrayBuffer = arrayBuffer;
  61203. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  61204. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  61205. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  61206. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  61207. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  61208. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  61209. BABYLON.Tools.Error("texture missing KTX identifier");
  61210. return;
  61211. }
  61212. // load the reset of the header in native 32 bit int
  61213. var header = new Int32Array(this.arrayBuffer, 12, 13);
  61214. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  61215. var oppositeEndianess = header[0] === 0x01020304;
  61216. // read all the header elements in order they exist in the file, without modification (sans endainness)
  61217. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  61218. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  61219. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  61220. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  61221. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  61222. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  61223. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  61224. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  61225. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  61226. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  61227. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  61228. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  61229. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  61230. if (this.glType !== 0) {
  61231. BABYLON.Tools.Error("only compressed formats currently supported");
  61232. return;
  61233. }
  61234. else {
  61235. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  61236. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  61237. }
  61238. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  61239. BABYLON.Tools.Error("only 2D textures currently supported");
  61240. return;
  61241. }
  61242. if (this.numberOfArrayElements !== 0) {
  61243. BABYLON.Tools.Error("texture arrays not currently supported");
  61244. return;
  61245. }
  61246. if (this.numberOfFaces !== facesExpected) {
  61247. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  61248. return;
  61249. }
  61250. // we now have a completely validated file, so could use existence of loadType as success
  61251. // would need to make this more elaborate & adjust checks above to support more than one load type
  61252. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  61253. }
  61254. // not as fast hardware based, but will probably never need to use
  61255. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  61256. return ((val & 0xFF) << 24)
  61257. | ((val & 0xFF00) << 8)
  61258. | ((val >> 8) & 0xFF00)
  61259. | ((val >> 24) & 0xFF);
  61260. };
  61261. /**
  61262. * It is assumed that the texture has already been created & is currently bound
  61263. */
  61264. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  61265. switch (this.loadType) {
  61266. case KhronosTextureContainer.COMPRESSED_2D:
  61267. this._upload2DCompressedLevels(gl, loadMipmaps);
  61268. break;
  61269. case KhronosTextureContainer.TEX_2D:
  61270. case KhronosTextureContainer.COMPRESSED_3D:
  61271. case KhronosTextureContainer.TEX_3D:
  61272. }
  61273. };
  61274. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  61275. // initialize width & height for level 1
  61276. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  61277. var width = this.pixelWidth;
  61278. var height = this.pixelHeight;
  61279. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  61280. for (var level = 0; level < mipmapCount; level++) {
  61281. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  61282. for (var face = 0; face < this.numberOfFaces; face++) {
  61283. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  61284. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  61285. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  61286. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  61287. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  61288. }
  61289. width = Math.max(1.0, width * 0.5);
  61290. height = Math.max(1.0, height * 0.5);
  61291. }
  61292. };
  61293. return KhronosTextureContainer;
  61294. }());
  61295. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  61296. // load types
  61297. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  61298. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  61299. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  61300. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  61301. Internals.KhronosTextureContainer = KhronosTextureContainer;
  61302. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61303. })(BABYLON || (BABYLON = {}));
  61304. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  61305. var BABYLON;
  61306. (function (BABYLON) {
  61307. var DynamicFloatArrayElementInfo = (function () {
  61308. function DynamicFloatArrayElementInfo() {
  61309. }
  61310. return DynamicFloatArrayElementInfo;
  61311. }());
  61312. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  61313. /**
  61314. * 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.
  61315. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  61316. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  61317. * 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.
  61318. * 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.
  61319. * 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".
  61320. */
  61321. var DynamicFloatArray = (function () {
  61322. /**
  61323. * Construct an instance of the dynamic float array
  61324. * @param stride size of one element in float (i.e. not bytes!)
  61325. * @param initialElementCount the number of available entries at construction
  61326. */
  61327. function DynamicFloatArray(stride, initialElementCount) {
  61328. this.compareValueOffset = null;
  61329. this.sortingAscending = true;
  61330. this._stride = stride;
  61331. this.buffer = new Float32Array(stride * initialElementCount);
  61332. this._lastUsed = 0;
  61333. this._firstFree = 0;
  61334. this._allEntries = new Array(initialElementCount);
  61335. this._freeEntries = new Array(initialElementCount);
  61336. for (var i = 0; i < initialElementCount; i++) {
  61337. var element = new DynamicFloatArrayElementInfo();
  61338. element.offset = i * stride;
  61339. this._allEntries[i] = element;
  61340. this._freeEntries[initialElementCount - i - 1] = element;
  61341. }
  61342. }
  61343. /**
  61344. * Allocate an element in the array.
  61345. * @return the element info instance that contains the offset into the main buffer of the element's location.
  61346. * Beware, this offset may change when you call pack()
  61347. */
  61348. DynamicFloatArray.prototype.allocElement = function () {
  61349. if (this._freeEntries.length === 0) {
  61350. this._growBuffer();
  61351. }
  61352. var el = this._freeEntries.pop();
  61353. this._lastUsed = Math.max(el.offset, this._lastUsed);
  61354. if (el.offset === this._firstFree) {
  61355. if (this._freeEntries.length > 0) {
  61356. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  61357. }
  61358. else {
  61359. this._firstFree += this._stride;
  61360. }
  61361. }
  61362. return el;
  61363. };
  61364. /**
  61365. * Free the element corresponding to the given element info
  61366. * @param elInfo the element that describe the allocated element
  61367. */
  61368. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  61369. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  61370. this._freeEntries.push(elInfo);
  61371. };
  61372. /**
  61373. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  61374. * 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().
  61375. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  61376. */
  61377. DynamicFloatArray.prototype.pack = function () {
  61378. // no free slot? no need to pack
  61379. if (this._freeEntries.length === 0) {
  61380. return this.buffer;
  61381. }
  61382. // If the buffer is already packed the last used will always be lower than the first free
  61383. // 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.
  61384. if (this._lastUsed < this._firstFree) {
  61385. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  61386. return elementsBuffer_1;
  61387. }
  61388. var s = this._stride;
  61389. // 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
  61390. var lastFree = new DynamicFloatArrayElementInfo();
  61391. lastFree.offset = this.totalElementCount * s;
  61392. this._freeEntries.push(lastFree);
  61393. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  61394. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61395. var firstFreeSlotOffset = sortedFree[0].offset;
  61396. var freeZoneSize = 1;
  61397. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  61398. var prevOffset = sortedFree[0].offset;
  61399. for (var i = 1; i < sortedFree.length; i++) {
  61400. // 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
  61401. if (firstFreeSlotOffset >= occupiedZoneSize) {
  61402. break;
  61403. }
  61404. var curFree = sortedFree[i];
  61405. var curOffset = curFree.offset;
  61406. // Compute the distance between this offset and the previous
  61407. var distance = curOffset - prevOffset;
  61408. // If the distance is the stride size, they are adjacent, it good, move to the next
  61409. if (distance === s) {
  61410. // Free zone is one element bigger
  61411. ++freeZoneSize;
  61412. // as we're about to iterate to the next, the cur becomes the previous...
  61413. prevOffset = curOffset;
  61414. continue;
  61415. }
  61416. // Distance is bigger, which means there's x element between the previous free and this one
  61417. var usedRange = (distance / s) - 1;
  61418. // Two cases the free zone is smaller than the data to move or bigger
  61419. // Copy what can fit in the free zone
  61420. var curMoveOffset = curOffset - s;
  61421. var copyCount = Math.min(freeZoneSize, usedRange);
  61422. for (var j = 0; j < copyCount; j++) {
  61423. var freeI = firstFreeSlotOffset / s;
  61424. var curI = curMoveOffset / s;
  61425. var moveEl = sortedAll[curI];
  61426. this._moveElement(moveEl, firstFreeSlotOffset);
  61427. var replacedEl = sortedAll[freeI];
  61428. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  61429. replacedEl.offset = curMoveOffset;
  61430. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  61431. sortedAll[freeI] = moveEl;
  61432. sortedAll[curI] = replacedEl;
  61433. curMoveOffset -= s;
  61434. firstFreeSlotOffset += s;
  61435. }
  61436. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  61437. if (freeZoneSize <= usedRange) {
  61438. firstFreeSlotOffset = curMoveOffset + s;
  61439. freeZoneSize = 1 + copyCount;
  61440. }
  61441. else {
  61442. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  61443. }
  61444. // as we're about to iterate to the next, the cur becomes the previous...
  61445. prevOffset = curOffset;
  61446. }
  61447. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  61448. this._lastUsed = firstFreeSlotOffset - s;
  61449. this._firstFree = firstFreeSlotOffset;
  61450. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  61451. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  61452. this._allEntries = sortedAll;
  61453. return elementsBuffer;
  61454. };
  61455. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  61456. for (var i = 0; i < this._stride; i++) {
  61457. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  61458. }
  61459. element.offset = destOffset;
  61460. };
  61461. DynamicFloatArray.prototype._growBuffer = function () {
  61462. // Allocate the new buffer with 50% more entries, copy the content of the current one
  61463. var newElCount = Math.floor(this.totalElementCount * 1.5);
  61464. var newBuffer = new Float32Array(newElCount * this._stride);
  61465. newBuffer.set(this.buffer);
  61466. var curCount = this.totalElementCount;
  61467. var addedCount = newElCount - this.totalElementCount;
  61468. for (var i = 0; i < addedCount; i++) {
  61469. var element = new DynamicFloatArrayElementInfo();
  61470. element.offset = (curCount + i) * this.stride;
  61471. this._allEntries.push(element);
  61472. this._freeEntries[addedCount - i - 1] = element;
  61473. }
  61474. this._firstFree = curCount * this.stride;
  61475. this.buffer = newBuffer;
  61476. };
  61477. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  61478. /**
  61479. * Get the total count of entries that can fit in the current buffer
  61480. * @returns the elements count
  61481. */
  61482. get: function () {
  61483. return this._allEntries.length;
  61484. },
  61485. enumerable: true,
  61486. configurable: true
  61487. });
  61488. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  61489. /**
  61490. * Get the count of free entries that can still be allocated without resizing the buffer
  61491. * @returns the free elements count
  61492. */
  61493. get: function () {
  61494. return this._freeEntries.length;
  61495. },
  61496. enumerable: true,
  61497. configurable: true
  61498. });
  61499. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  61500. /**
  61501. * Get the count of allocated elements
  61502. * @returns the allocated elements count
  61503. */
  61504. get: function () {
  61505. return this._allEntries.length - this._freeEntries.length;
  61506. },
  61507. enumerable: true,
  61508. configurable: true
  61509. });
  61510. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  61511. /**
  61512. * Return the size of one element in float
  61513. * @returns the size in float
  61514. */
  61515. get: function () {
  61516. return this._stride;
  61517. },
  61518. enumerable: true,
  61519. configurable: true
  61520. });
  61521. DynamicFloatArray.prototype.sort = function () {
  61522. var _this = this;
  61523. if (!this.compareValueOffset) {
  61524. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  61525. }
  61526. var count = this.usedElementCount;
  61527. // Do we have to (re)create the sort table?
  61528. if (!this._sortTable || this._sortTable.length < count) {
  61529. // 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...
  61530. var newCount = Math.min(this.totalElementCount, count * 2);
  61531. this._sortTable = new Array(newCount);
  61532. }
  61533. if (!this._sortedTable || this._sortedTable.length !== count) {
  61534. this._sortedTable = new Array(count);
  61535. }
  61536. // Because, you know...
  61537. this.pack();
  61538. //let stride = this.stride;
  61539. //for (let i = 0; i < count; i++) {
  61540. // let si = this._sortTable[i];
  61541. // if (!si) {
  61542. // si = new SortInfo();
  61543. // this._sortTable[i] = si;
  61544. // }
  61545. // si.entry = this._allEntries[i];
  61546. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  61547. // si.swapedOffset = null;
  61548. // this._sortedTable[i] = si;
  61549. //}
  61550. var curOffset = 0;
  61551. var stride = this.stride;
  61552. for (var i = 0; i < count; i++, curOffset += stride) {
  61553. var si = this._sortTable[i];
  61554. if (!si) {
  61555. si = new SortInfo();
  61556. this._sortTable[i] = si;
  61557. }
  61558. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  61559. si.offset = curOffset;
  61560. si.swapedOffset = null;
  61561. this._sortedTable[i] = si;
  61562. }
  61563. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  61564. if (this.sortingAscending) {
  61565. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  61566. }
  61567. else {
  61568. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  61569. }
  61570. var swapElements = function (src, dst) {
  61571. for (var i = 0; i < stride; i++) {
  61572. var tps = _this.buffer[dst + i];
  61573. _this.buffer[dst + i] = _this.buffer[src + i];
  61574. _this.buffer[src + i] = tps;
  61575. }
  61576. };
  61577. // 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:
  61578. // 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),
  61579. // and I still want something with a good algorithm complexity.
  61580. // 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,
  61581. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  61582. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  61583. // 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
  61584. // until we find a SortInfo object without a swapedOffset which means we got the right location
  61585. // 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
  61586. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  61587. for (var i = 0; i < count; i++) {
  61588. // Get the element to move
  61589. var sourceSI = this._sortedTable[i];
  61590. var destSI = this._sortTable[i];
  61591. var sourceOff = sourceSI.offset;
  61592. // If the source changed location, find the new one
  61593. if (sourceSI.swapedOffset) {
  61594. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  61595. var curSI = sourceSI;
  61596. while (curSI.swapedOffset) {
  61597. curSI = this._sortTable[curSI.swapedOffset / stride];
  61598. }
  61599. // Finally get the right location
  61600. sourceOff = curSI.offset;
  61601. }
  61602. // Tag the element being replaced with its new location
  61603. destSI.swapedOffset = sourceOff;
  61604. // Swap elements (only if needed)
  61605. if (sourceOff !== destSI.offset) {
  61606. swapElements(sourceOff, destSI.offset);
  61607. }
  61608. // Update the offset in the corresponding DFAE
  61609. //sourceSI.entry.offset = destSI.entry.offset;
  61610. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  61611. }
  61612. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61613. return true;
  61614. };
  61615. return DynamicFloatArray;
  61616. }());
  61617. BABYLON.DynamicFloatArray = DynamicFloatArray;
  61618. var SortInfo = (function () {
  61619. function SortInfo() {
  61620. this.compareData = this.offset = this.swapedOffset = null;
  61621. }
  61622. return SortInfo;
  61623. }());
  61624. })(BABYLON || (BABYLON = {}));
  61625. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  61626. var BABYLON;
  61627. (function (BABYLON) {
  61628. var Debug;
  61629. (function (Debug) {
  61630. /**
  61631. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  61632. */
  61633. var SkeletonViewer = (function () {
  61634. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  61635. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61636. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61637. this.skeleton = skeleton;
  61638. this.mesh = mesh;
  61639. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61640. this.renderingGroupId = renderingGroupId;
  61641. this.color = BABYLON.Color3.White();
  61642. this._debugLines = [];
  61643. this._isEnabled = false;
  61644. this._scene = scene;
  61645. this.update();
  61646. this._renderFunction = this.update.bind(this);
  61647. }
  61648. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61649. get: function () {
  61650. return this._isEnabled;
  61651. },
  61652. set: function (value) {
  61653. if (this._isEnabled === value) {
  61654. return;
  61655. }
  61656. this._isEnabled = value;
  61657. if (value) {
  61658. this._scene.registerBeforeRender(this._renderFunction);
  61659. }
  61660. else {
  61661. this._scene.unregisterBeforeRender(this._renderFunction);
  61662. }
  61663. },
  61664. enumerable: true,
  61665. configurable: true
  61666. });
  61667. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61668. if (x === void 0) { x = 0; }
  61669. if (y === void 0) { y = 0; }
  61670. if (z === void 0) { z = 0; }
  61671. var tmat = BABYLON.Tmp.Matrix[0];
  61672. var parentBone = bone.getParent();
  61673. tmat.copyFrom(bone.getLocalMatrix());
  61674. if (x !== 0 || y !== 0 || z !== 0) {
  61675. var tmat2 = BABYLON.Tmp.Matrix[1];
  61676. BABYLON.Matrix.IdentityToRef(tmat2);
  61677. tmat2.m[12] = x;
  61678. tmat2.m[13] = y;
  61679. tmat2.m[14] = z;
  61680. tmat2.multiplyToRef(tmat, tmat);
  61681. }
  61682. if (parentBone) {
  61683. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61684. }
  61685. tmat.multiplyToRef(meshMat, tmat);
  61686. position.x = tmat.m[12];
  61687. position.y = tmat.m[13];
  61688. position.z = tmat.m[14];
  61689. };
  61690. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61691. var len = bones.length;
  61692. var meshPos = this.mesh.position;
  61693. for (var i = 0; i < len; i++) {
  61694. var bone = bones[i];
  61695. var points = this._debugLines[i];
  61696. if (!points) {
  61697. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61698. this._debugLines[i] = points;
  61699. }
  61700. this._getBonePosition(points[0], bone, meshMat);
  61701. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61702. points[0].subtractInPlace(meshPos);
  61703. points[1].subtractInPlace(meshPos);
  61704. }
  61705. };
  61706. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61707. var len = bones.length;
  61708. var boneNum = 0;
  61709. var meshPos = this.mesh.position;
  61710. for (var i = len - 1; i >= 0; i--) {
  61711. var childBone = bones[i];
  61712. var parentBone = childBone.getParent();
  61713. if (!parentBone) {
  61714. continue;
  61715. }
  61716. var points = this._debugLines[boneNum];
  61717. if (!points) {
  61718. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61719. this._debugLines[boneNum] = points;
  61720. }
  61721. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61722. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61723. points[0].subtractInPlace(meshPos);
  61724. points[1].subtractInPlace(meshPos);
  61725. boneNum++;
  61726. }
  61727. };
  61728. SkeletonViewer.prototype.update = function () {
  61729. if (this.autoUpdateBonesMatrices) {
  61730. this.skeleton.computeAbsoluteTransforms();
  61731. }
  61732. if (this.skeleton.bones[0].length === undefined) {
  61733. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61734. }
  61735. else {
  61736. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61737. }
  61738. if (!this._debugMesh) {
  61739. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  61740. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61741. }
  61742. else {
  61743. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61744. }
  61745. this._debugMesh.position.copyFrom(this.mesh.position);
  61746. this._debugMesh.color = this.color;
  61747. };
  61748. SkeletonViewer.prototype.dispose = function () {
  61749. if (this._debugMesh) {
  61750. this.isEnabled = false;
  61751. this._debugMesh.dispose();
  61752. this._debugMesh = null;
  61753. }
  61754. };
  61755. return SkeletonViewer;
  61756. }());
  61757. Debug.SkeletonViewer = SkeletonViewer;
  61758. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61759. })(BABYLON || (BABYLON = {}));
  61760. //# sourceMappingURL=babylon.skeletonViewer.js.map
  61761. var BABYLON;
  61762. (function (BABYLON) {
  61763. var Debug;
  61764. (function (Debug) {
  61765. var AxesViewer = (function () {
  61766. function AxesViewer(scene, scaleLines) {
  61767. if (scaleLines === void 0) { scaleLines = 1; }
  61768. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61769. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61770. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61771. this.scaleLines = 1;
  61772. this.scaleLines = scaleLines;
  61773. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  61774. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  61775. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  61776. this._xmesh.renderingGroupId = 2;
  61777. this._ymesh.renderingGroupId = 2;
  61778. this._zmesh.renderingGroupId = 2;
  61779. this._xmesh.material.checkReadyOnlyOnce = true;
  61780. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  61781. this._ymesh.material.checkReadyOnlyOnce = true;
  61782. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  61783. this._zmesh.material.checkReadyOnlyOnce = true;
  61784. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  61785. this.scene = scene;
  61786. }
  61787. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  61788. var scaleLines = this.scaleLines;
  61789. this._xmesh.position.copyFrom(position);
  61790. this._ymesh.position.copyFrom(position);
  61791. this._zmesh.position.copyFrom(position);
  61792. var point2 = this._xline[1];
  61793. point2.x = xaxis.x * scaleLines;
  61794. point2.y = xaxis.y * scaleLines;
  61795. point2.z = xaxis.z * scaleLines;
  61796. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  61797. point2 = this._yline[1];
  61798. point2.x = yaxis.x * scaleLines;
  61799. point2.y = yaxis.y * scaleLines;
  61800. point2.z = yaxis.z * scaleLines;
  61801. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  61802. point2 = this._zline[1];
  61803. point2.x = zaxis.x * scaleLines;
  61804. point2.y = zaxis.y * scaleLines;
  61805. point2.z = zaxis.z * scaleLines;
  61806. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  61807. };
  61808. AxesViewer.prototype.dispose = function () {
  61809. if (this._xmesh) {
  61810. this._xmesh.dispose();
  61811. this._ymesh.dispose();
  61812. this._zmesh.dispose();
  61813. this._xmesh = null;
  61814. this._ymesh = null;
  61815. this._zmesh = null;
  61816. this._xline = null;
  61817. this._yline = null;
  61818. this._zline = null;
  61819. this.scene = null;
  61820. }
  61821. };
  61822. return AxesViewer;
  61823. }());
  61824. Debug.AxesViewer = AxesViewer;
  61825. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61826. })(BABYLON || (BABYLON = {}));
  61827. //# sourceMappingURL=babylon.axesViewer.js.map
  61828. var BABYLON;
  61829. (function (BABYLON) {
  61830. var Debug;
  61831. (function (Debug) {
  61832. var BoneAxesViewer = (function (_super) {
  61833. __extends(BoneAxesViewer, _super);
  61834. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61835. if (scaleLines === void 0) { scaleLines = 1; }
  61836. var _this = _super.call(this, scene, scaleLines) || this;
  61837. _this.pos = BABYLON.Vector3.Zero();
  61838. _this.xaxis = BABYLON.Vector3.Zero();
  61839. _this.yaxis = BABYLON.Vector3.Zero();
  61840. _this.zaxis = BABYLON.Vector3.Zero();
  61841. _this.mesh = mesh;
  61842. _this.bone = bone;
  61843. return _this;
  61844. }
  61845. BoneAxesViewer.prototype.update = function () {
  61846. var bone = this.bone;
  61847. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  61848. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  61849. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  61850. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  61851. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  61852. };
  61853. BoneAxesViewer.prototype.dispose = function () {
  61854. if (this.pos) {
  61855. this.pos = null;
  61856. this.xaxis = null;
  61857. this.yaxis = null;
  61858. this.zaxis = null;
  61859. this.mesh = null;
  61860. this.bone = null;
  61861. _super.prototype.dispose.call(this);
  61862. }
  61863. };
  61864. return BoneAxesViewer;
  61865. }(Debug.AxesViewer));
  61866. Debug.BoneAxesViewer = BoneAxesViewer;
  61867. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61868. })(BABYLON || (BABYLON = {}));
  61869. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  61870. var BABYLON;
  61871. (function (BABYLON) {
  61872. var RayHelper = (function () {
  61873. function RayHelper(ray) {
  61874. this.ray = ray;
  61875. }
  61876. RayHelper.CreateAndShow = function (ray, scene, color) {
  61877. var helper = new RayHelper(ray);
  61878. helper.show(scene, color);
  61879. return helper;
  61880. };
  61881. RayHelper.prototype.show = function (scene, color) {
  61882. if (!this._renderFunction) {
  61883. var ray = this.ray;
  61884. this._renderFunction = this._render.bind(this);
  61885. this._scene = scene;
  61886. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  61887. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  61888. this._scene.registerBeforeRender(this._renderFunction);
  61889. }
  61890. if (color) {
  61891. this._renderLine.color.copyFrom(color);
  61892. }
  61893. };
  61894. RayHelper.prototype.hide = function () {
  61895. if (this._renderFunction) {
  61896. this._scene.unregisterBeforeRender(this._renderFunction);
  61897. this._scene = null;
  61898. this._renderFunction = null;
  61899. this._renderLine.dispose();
  61900. this._renderLine = null;
  61901. this._renderPoints = null;
  61902. }
  61903. };
  61904. RayHelper.prototype._render = function () {
  61905. var ray = this.ray;
  61906. var point = this._renderPoints[1];
  61907. var len = Math.min(ray.length, 1000000);
  61908. point.copyFrom(ray.direction);
  61909. point.scaleInPlace(len);
  61910. point.addInPlace(ray.origin);
  61911. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61912. };
  61913. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61914. this._attachedToMesh = mesh;
  61915. var ray = this.ray;
  61916. if (!ray.direction) {
  61917. ray.direction = BABYLON.Vector3.Zero();
  61918. }
  61919. if (!ray.origin) {
  61920. ray.origin = BABYLON.Vector3.Zero();
  61921. }
  61922. if (length) {
  61923. ray.length = length;
  61924. }
  61925. if (!meshSpaceOrigin) {
  61926. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61927. }
  61928. if (!meshSpaceDirection) {
  61929. // -1 so that this will work with Mesh.lookAt
  61930. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61931. }
  61932. if (!this._meshSpaceDirection) {
  61933. this._meshSpaceDirection = meshSpaceDirection.clone();
  61934. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61935. }
  61936. else {
  61937. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61938. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61939. }
  61940. if (!this._updateToMeshFunction) {
  61941. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61942. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61943. }
  61944. this._updateToMesh();
  61945. };
  61946. RayHelper.prototype.detachFromMesh = function () {
  61947. if (this._attachedToMesh) {
  61948. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61949. this._attachedToMesh = null;
  61950. this._updateToMeshFunction = null;
  61951. }
  61952. };
  61953. RayHelper.prototype._updateToMesh = function () {
  61954. var ray = this.ray;
  61955. if (this._attachedToMesh._isDisposed) {
  61956. this.detachFromMesh();
  61957. return;
  61958. }
  61959. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61960. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61961. };
  61962. RayHelper.prototype.dispose = function () {
  61963. this.hide();
  61964. this.detachFromMesh();
  61965. this.ray = null;
  61966. };
  61967. return RayHelper;
  61968. }());
  61969. BABYLON.RayHelper = RayHelper;
  61970. })(BABYLON || (BABYLON = {}));
  61971. //# sourceMappingURL=babylon.rayHelper.js.map
  61972. var BABYLON;
  61973. (function (BABYLON) {
  61974. var DebugLayer = (function () {
  61975. function DebugLayer(scene) {
  61976. this._scene = scene;
  61977. }
  61978. /** Creates the inspector window. */
  61979. DebugLayer.prototype._createInspector = function (config) {
  61980. if (config === void 0) { config = {}; }
  61981. var popup = config.popup || false;
  61982. var initialTab = config.initialTab || 0;
  61983. var parentElement = config.parentElement || null;
  61984. if (!this._inspector) {
  61985. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61986. } // else nothing to do,; instance is already existing
  61987. };
  61988. DebugLayer.prototype.isVisible = function () {
  61989. if (!this._inspector) {
  61990. return false;
  61991. }
  61992. return true;
  61993. };
  61994. DebugLayer.prototype.hide = function () {
  61995. if (this._inspector) {
  61996. try {
  61997. this._inspector.dispose();
  61998. }
  61999. catch (e) {
  62000. // If the inspector has been removed directly from the inspector tool
  62001. }
  62002. this._inspector = null;
  62003. }
  62004. };
  62005. DebugLayer.prototype.show = function (config) {
  62006. if (config === void 0) { config = {}; }
  62007. if (typeof INSPECTOR == 'undefined') {
  62008. // Load inspector and add it to the DOM
  62009. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62010. }
  62011. else {
  62012. // Otherwise creates the inspector
  62013. this._createInspector(config);
  62014. }
  62015. };
  62016. return DebugLayer;
  62017. }());
  62018. // Get protocol used - http or https
  62019. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62020. BABYLON.DebugLayer = DebugLayer;
  62021. })(BABYLON || (BABYLON = {}));
  62022. //# sourceMappingURL=babylon.debugLayer.js.map
  62023. var BABYLON;
  62024. (function (BABYLON) {
  62025. var Debug;
  62026. (function (Debug) {
  62027. var PhysicsViewer = (function () {
  62028. function PhysicsViewer(scene) {
  62029. this._impostors = [];
  62030. this._meshes = [];
  62031. this._numMeshes = 0;
  62032. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62033. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  62034. }
  62035. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62036. var plugin = this._physicsEnginePlugin;
  62037. for (var i = 0; i < this._numMeshes; i++) {
  62038. if (this._impostors[i].isDisposed) {
  62039. this.hideImpostor(this._impostors[i--]);
  62040. }
  62041. else {
  62042. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  62043. }
  62044. }
  62045. };
  62046. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62047. for (var i = 0; i < this._numMeshes; i++) {
  62048. if (this._impostors[i] == impostor) {
  62049. return;
  62050. }
  62051. }
  62052. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62053. if (debugMesh) {
  62054. this._impostors[this._numMeshes] = impostor;
  62055. this._meshes[this._numMeshes] = debugMesh;
  62056. if (this._numMeshes === 0) {
  62057. this._renderFunction = this._updateDebugMeshes.bind(this);
  62058. this._scene.registerBeforeRender(this._renderFunction);
  62059. }
  62060. this._numMeshes++;
  62061. }
  62062. };
  62063. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62064. var removed = false;
  62065. for (var i = 0; i < this._numMeshes; i++) {
  62066. if (this._impostors[i] == impostor) {
  62067. this._scene.removeMesh(this._meshes[i]);
  62068. this._meshes[i].dispose();
  62069. this._numMeshes--;
  62070. if (this._numMeshes > 0) {
  62071. this._meshes[i] = this._meshes[this._numMeshes];
  62072. this._impostors[i] = this._impostors[this._numMeshes];
  62073. this._meshes[this._numMeshes] = null;
  62074. this._impostors[this._numMeshes] = null;
  62075. }
  62076. else {
  62077. this._meshes[0] = null;
  62078. this._impostors[0] = null;
  62079. }
  62080. removed = true;
  62081. break;
  62082. }
  62083. }
  62084. if (removed && this._numMeshes === 0) {
  62085. this._scene.unregisterBeforeRender(this._renderFunction);
  62086. }
  62087. };
  62088. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62089. if (!this._debugMaterial) {
  62090. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62091. this._debugMaterial.wireframe = true;
  62092. }
  62093. return this._debugMaterial;
  62094. };
  62095. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62096. if (!this._debugBoxMesh) {
  62097. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62098. this._debugBoxMesh.renderingGroupId = 1;
  62099. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62100. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62101. scene.removeMesh(this._debugBoxMesh);
  62102. }
  62103. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62104. };
  62105. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62106. if (!this._debugSphereMesh) {
  62107. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62108. this._debugSphereMesh.renderingGroupId = 1;
  62109. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62110. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62111. scene.removeMesh(this._debugSphereMesh);
  62112. }
  62113. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62114. };
  62115. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62116. var body = impostor.physicsBody;
  62117. var shape = body.shapes[0];
  62118. var mesh;
  62119. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62120. mesh = this._getDebugBoxMesh(scene);
  62121. impostor.getBoxSizeToRef(mesh.scaling);
  62122. }
  62123. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62124. mesh = this._getDebugSphereMesh(scene);
  62125. var radius = impostor.getRadius();
  62126. mesh.scaling.x = radius * 2;
  62127. mesh.scaling.y = radius * 2;
  62128. mesh.scaling.z = radius * 2;
  62129. }
  62130. return mesh;
  62131. };
  62132. PhysicsViewer.prototype.dispose = function () {
  62133. for (var i = 0; i < this._numMeshes; i++) {
  62134. this.hideImpostor(this._impostors[i]);
  62135. }
  62136. if (this._debugBoxMesh) {
  62137. this._debugBoxMesh.dispose();
  62138. }
  62139. if (this._debugSphereMesh) {
  62140. this._debugSphereMesh.dispose();
  62141. }
  62142. if (this._debugMaterial) {
  62143. this._debugMaterial.dispose();
  62144. }
  62145. this._impostors.length = 0;
  62146. this._scene = null;
  62147. this._physicsEnginePlugin = null;
  62148. };
  62149. return PhysicsViewer;
  62150. }());
  62151. Debug.PhysicsViewer = PhysicsViewer;
  62152. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62153. })(BABYLON || (BABYLON = {}));
  62154. //# sourceMappingURL=babylon.physicsViewer.js.map
  62155. var BABYLON;
  62156. (function (BABYLON) {
  62157. var BoundingBoxRenderer = (function () {
  62158. function BoundingBoxRenderer(scene) {
  62159. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62160. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62161. this.showBackLines = true;
  62162. this.renderList = new BABYLON.SmartArray(32);
  62163. this._vertexBuffers = {};
  62164. this._scene = scene;
  62165. }
  62166. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62167. if (this._colorShader) {
  62168. return;
  62169. }
  62170. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  62171. attributes: [BABYLON.VertexBuffer.PositionKind],
  62172. uniforms: ["world", "viewProjection", "color"]
  62173. });
  62174. var engine = this._scene.getEngine();
  62175. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  62176. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62177. 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]);
  62178. };
  62179. BoundingBoxRenderer.prototype.reset = function () {
  62180. this.renderList.reset();
  62181. };
  62182. BoundingBoxRenderer.prototype.render = function () {
  62183. if (this.renderList.length === 0) {
  62184. return;
  62185. }
  62186. this._prepareRessources();
  62187. if (!this._colorShader.isReady()) {
  62188. return;
  62189. }
  62190. var engine = this._scene.getEngine();
  62191. engine.setDepthWrite(false);
  62192. this._colorShader._preBind();
  62193. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62194. var boundingBox = this.renderList.data[boundingBoxIndex];
  62195. var min = boundingBox.minimum;
  62196. var max = boundingBox.maximum;
  62197. var diff = max.subtract(min);
  62198. var median = min.add(diff.scale(0.5));
  62199. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62200. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62201. .multiply(boundingBox.getWorldMatrix());
  62202. // VBOs
  62203. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62204. if (this.showBackLines) {
  62205. // Back
  62206. engine.setDepthFunctionToGreaterOrEqual();
  62207. this._scene.resetCachedMaterial();
  62208. this._colorShader.setColor4("color", this.backColor.toColor4());
  62209. this._colorShader.bind(worldMatrix);
  62210. // Draw order
  62211. engine.draw(false, 0, 24);
  62212. }
  62213. // Front
  62214. engine.setDepthFunctionToLess();
  62215. this._scene.resetCachedMaterial();
  62216. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62217. this._colorShader.bind(worldMatrix);
  62218. // Draw order
  62219. engine.draw(false, 0, 24);
  62220. }
  62221. this._colorShader.unbind();
  62222. engine.setDepthFunctionToLessOrEqual();
  62223. engine.setDepthWrite(true);
  62224. };
  62225. BoundingBoxRenderer.prototype.dispose = function () {
  62226. if (!this._colorShader) {
  62227. return;
  62228. }
  62229. this.renderList.dispose();
  62230. this._colorShader.dispose();
  62231. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62232. if (buffer) {
  62233. buffer.dispose();
  62234. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62235. }
  62236. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62237. };
  62238. return BoundingBoxRenderer;
  62239. }());
  62240. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  62241. })(BABYLON || (BABYLON = {}));
  62242. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  62243. var BABYLON;
  62244. (function (BABYLON) {
  62245. var MorphTarget = (function () {
  62246. function MorphTarget(name, influence) {
  62247. if (influence === void 0) { influence = 0; }
  62248. this.name = name;
  62249. this.animations = new Array();
  62250. this.onInfluenceChanged = new BABYLON.Observable();
  62251. this.influence = influence;
  62252. }
  62253. Object.defineProperty(MorphTarget.prototype, "influence", {
  62254. get: function () {
  62255. return this._influence;
  62256. },
  62257. set: function (influence) {
  62258. if (this._influence === influence) {
  62259. return;
  62260. }
  62261. var previous = this._influence;
  62262. this._influence = influence;
  62263. if (this.onInfluenceChanged.hasObservers) {
  62264. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  62265. }
  62266. },
  62267. enumerable: true,
  62268. configurable: true
  62269. });
  62270. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  62271. get: function () {
  62272. return this._normals !== undefined;
  62273. },
  62274. enumerable: true,
  62275. configurable: true
  62276. });
  62277. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  62278. get: function () {
  62279. return this._tangents !== undefined;
  62280. },
  62281. enumerable: true,
  62282. configurable: true
  62283. });
  62284. MorphTarget.prototype.setPositions = function (data) {
  62285. this._positions = new Float32Array(data);
  62286. };
  62287. MorphTarget.prototype.getPositions = function () {
  62288. return this._positions;
  62289. };
  62290. MorphTarget.prototype.setNormals = function (data) {
  62291. this._normals = new Float32Array(data);
  62292. };
  62293. MorphTarget.prototype.getNormals = function () {
  62294. return this._normals;
  62295. };
  62296. MorphTarget.prototype.setTangents = function (data) {
  62297. this._tangents = new Float32Array(data);
  62298. };
  62299. MorphTarget.prototype.getTangents = function () {
  62300. return this._tangents;
  62301. };
  62302. /**
  62303. * Serializes the current target into a Serialization object.
  62304. * Returns the serialized object.
  62305. */
  62306. MorphTarget.prototype.serialize = function () {
  62307. var serializationObject = {};
  62308. serializationObject.name = this.name;
  62309. serializationObject.influence = this.influence;
  62310. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  62311. if (this.hasNormals) {
  62312. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  62313. }
  62314. if (this.hasTangents) {
  62315. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  62316. }
  62317. return serializationObject;
  62318. };
  62319. // Statics
  62320. MorphTarget.Parse = function (serializationObject) {
  62321. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  62322. result.setPositions(serializationObject.positions);
  62323. if (serializationObject.normals) {
  62324. result.setNormals(serializationObject.normals);
  62325. }
  62326. if (serializationObject.tangents) {
  62327. result.setTangents(serializationObject.tangents);
  62328. }
  62329. return result;
  62330. };
  62331. MorphTarget.FromMesh = function (mesh, name, influence) {
  62332. if (!name) {
  62333. name = mesh.name;
  62334. }
  62335. var result = new MorphTarget(name, influence);
  62336. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  62337. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62338. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  62339. }
  62340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  62341. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  62342. }
  62343. return result;
  62344. };
  62345. return MorphTarget;
  62346. }());
  62347. BABYLON.MorphTarget = MorphTarget;
  62348. })(BABYLON || (BABYLON = {}));
  62349. //# sourceMappingURL=babylon.morphTarget.js.map
  62350. var BABYLON;
  62351. (function (BABYLON) {
  62352. var MorphTargetManager = (function () {
  62353. function MorphTargetManager(scene) {
  62354. this._targets = new Array();
  62355. this._targetObservable = new Array();
  62356. this._activeTargets = new BABYLON.SmartArray(16);
  62357. this._supportsNormals = false;
  62358. this._supportsTangents = false;
  62359. this._vertexCount = 0;
  62360. this._uniqueId = 0;
  62361. this._tempInfluences = new Array();
  62362. if (!scene) {
  62363. scene = BABYLON.Engine.LastCreatedScene;
  62364. }
  62365. this._scene = scene;
  62366. this._scene.morphTargetManagers.push(this);
  62367. this._uniqueId = scene.getUniqueId();
  62368. }
  62369. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  62370. get: function () {
  62371. return this._uniqueId;
  62372. },
  62373. enumerable: true,
  62374. configurable: true
  62375. });
  62376. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  62377. get: function () {
  62378. return this._vertexCount;
  62379. },
  62380. enumerable: true,
  62381. configurable: true
  62382. });
  62383. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  62384. get: function () {
  62385. return this._supportsNormals;
  62386. },
  62387. enumerable: true,
  62388. configurable: true
  62389. });
  62390. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  62391. get: function () {
  62392. return this._supportsTangents;
  62393. },
  62394. enumerable: true,
  62395. configurable: true
  62396. });
  62397. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  62398. get: function () {
  62399. return this._targets.length;
  62400. },
  62401. enumerable: true,
  62402. configurable: true
  62403. });
  62404. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  62405. get: function () {
  62406. return this._activeTargets.length;
  62407. },
  62408. enumerable: true,
  62409. configurable: true
  62410. });
  62411. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  62412. get: function () {
  62413. return this._influences;
  62414. },
  62415. enumerable: true,
  62416. configurable: true
  62417. });
  62418. MorphTargetManager.prototype.getActiveTarget = function (index) {
  62419. return this._activeTargets.data[index];
  62420. };
  62421. MorphTargetManager.prototype.getTarget = function (index) {
  62422. return this._targets[index];
  62423. };
  62424. MorphTargetManager.prototype.addTarget = function (target) {
  62425. var _this = this;
  62426. if (this._vertexCount) {
  62427. if (this._vertexCount !== target.getPositions().length / 3) {
  62428. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  62429. return;
  62430. }
  62431. }
  62432. this._targets.push(target);
  62433. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  62434. _this._syncActiveTargets(needUpdate);
  62435. }));
  62436. this._syncActiveTargets(true);
  62437. };
  62438. MorphTargetManager.prototype.removeTarget = function (target) {
  62439. var index = this._targets.indexOf(target);
  62440. if (index >= 0) {
  62441. this._targets.splice(index, 1);
  62442. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  62443. this._vertexCount = 0;
  62444. this._syncActiveTargets(true);
  62445. }
  62446. };
  62447. /**
  62448. * Serializes the current manager into a Serialization object.
  62449. * Returns the serialized object.
  62450. */
  62451. MorphTargetManager.prototype.serialize = function () {
  62452. var serializationObject = {};
  62453. serializationObject.id = this.uniqueId;
  62454. serializationObject.targets = [];
  62455. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  62456. var target = _a[_i];
  62457. serializationObject.targets.push(target.serialize());
  62458. }
  62459. return serializationObject;
  62460. };
  62461. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  62462. this._syncActiveTargets(needUpdate);
  62463. };
  62464. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  62465. var influenceCount = 0;
  62466. this._activeTargets.reset();
  62467. this._supportsNormals = true;
  62468. this._supportsTangents = true;
  62469. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  62470. var target = _a[_i];
  62471. if (target.influence > 0) {
  62472. this._activeTargets.push(target);
  62473. this._tempInfluences[influenceCount++] = target.influence;
  62474. this._supportsNormals = this._supportsNormals && target.hasNormals;
  62475. this._supportsTangents = this._supportsTangents && target.hasTangents;
  62476. if (this._vertexCount === 0) {
  62477. this._vertexCount = target.getPositions().length / 3;
  62478. }
  62479. }
  62480. }
  62481. if (!this._influences || this._influences.length !== influenceCount) {
  62482. this._influences = new Float32Array(influenceCount);
  62483. }
  62484. for (var index = 0; index < influenceCount; index++) {
  62485. this._influences[index] = this._tempInfluences[index];
  62486. }
  62487. if (needUpdate) {
  62488. // Flag meshes as dirty to resync with the active targets
  62489. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  62490. var mesh = _c[_b];
  62491. if (mesh.morphTargetManager === this) {
  62492. mesh._syncGeometryWithMorphTargetManager();
  62493. }
  62494. }
  62495. }
  62496. };
  62497. // Statics
  62498. MorphTargetManager.Parse = function (serializationObject, scene) {
  62499. var result = new MorphTargetManager(scene);
  62500. result._uniqueId = serializationObject.id;
  62501. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  62502. var targetData = _a[_i];
  62503. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  62504. }
  62505. return result;
  62506. };
  62507. return MorphTargetManager;
  62508. }());
  62509. BABYLON.MorphTargetManager = MorphTargetManager;
  62510. })(BABYLON || (BABYLON = {}));
  62511. //# sourceMappingURL=babylon.morphTargetManager.js.map
  62512. var BABYLON;
  62513. (function (BABYLON) {
  62514. /**
  62515. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  62516. * It can help converting any input color in a desired output one. This can then be used to create effects
  62517. * from sepia, black and white to sixties or futuristic rendering...
  62518. *
  62519. * The only supported format is currently 3dl.
  62520. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  62521. */
  62522. var ColorGradingTexture = (function (_super) {
  62523. __extends(ColorGradingTexture, _super);
  62524. /**
  62525. * Instantiates a ColorGradingTexture from the following parameters.
  62526. *
  62527. * @param url The location of the color gradind data (currently only supporting 3dl)
  62528. * @param scene The scene the texture will be used in
  62529. */
  62530. function ColorGradingTexture(url, scene) {
  62531. var _this = _super.call(this, scene) || this;
  62532. if (!url) {
  62533. return _this;
  62534. }
  62535. _this._textureMatrix = BABYLON.Matrix.Identity();
  62536. _this.name = url;
  62537. _this.url = url;
  62538. _this.hasAlpha = false;
  62539. _this.isCube = false;
  62540. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62541. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62542. _this.anisotropicFilteringLevel = 1;
  62543. _this._texture = _this._getFromCache(url, true);
  62544. if (!_this._texture) {
  62545. if (!scene.useDelayedTextureLoading) {
  62546. _this.loadTexture();
  62547. }
  62548. else {
  62549. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62550. }
  62551. }
  62552. return _this;
  62553. }
  62554. /**
  62555. * Returns the texture matrix used in most of the material.
  62556. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  62557. */
  62558. ColorGradingTexture.prototype.getTextureMatrix = function () {
  62559. return this._textureMatrix;
  62560. };
  62561. /**
  62562. * Occurs when the file being loaded is a .3dl LUT file.
  62563. */
  62564. ColorGradingTexture.prototype.load3dlTexture = function () {
  62565. var _this = this;
  62566. var mipLevels = 0;
  62567. var floatArrayView = null;
  62568. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62569. this._texture = texture;
  62570. var callback = function (text) {
  62571. var data;
  62572. var tempData;
  62573. var line;
  62574. var lines = text.split('\n');
  62575. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  62576. var maxColor = 0;
  62577. for (var i = 0; i < lines.length; i++) {
  62578. line = lines[i];
  62579. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  62580. continue;
  62581. if (line.indexOf('#') === 0)
  62582. continue;
  62583. var words = line.split(" ");
  62584. if (size === 0) {
  62585. // Number of space + one
  62586. size = words.length;
  62587. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  62588. tempData = new Float32Array(size * size * size * 4);
  62589. continue;
  62590. }
  62591. if (size != 0) {
  62592. var r = Math.max(parseInt(words[0]), 0);
  62593. var g = Math.max(parseInt(words[1]), 0);
  62594. var b = Math.max(parseInt(words[2]), 0);
  62595. maxColor = Math.max(r, maxColor);
  62596. maxColor = Math.max(g, maxColor);
  62597. maxColor = Math.max(b, maxColor);
  62598. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  62599. tempData[pixelStorageIndex + 0] = r;
  62600. tempData[pixelStorageIndex + 1] = g;
  62601. tempData[pixelStorageIndex + 2] = b;
  62602. pixelIndexSlice++;
  62603. if (pixelIndexSlice % size == 0) {
  62604. pixelIndexH++;
  62605. pixelIndexSlice = 0;
  62606. if (pixelIndexH % size == 0) {
  62607. pixelIndexW++;
  62608. pixelIndexH = 0;
  62609. }
  62610. }
  62611. }
  62612. }
  62613. for (var i = 0; i < tempData.length; i++) {
  62614. if (i > 0 && (i + 1) % 4 === 0) {
  62615. data[i] = 255;
  62616. }
  62617. else {
  62618. var value = tempData[i];
  62619. data[i] = (value / maxColor * 255);
  62620. }
  62621. }
  62622. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  62623. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  62624. };
  62625. BABYLON.Tools.LoadFile(this.url, callback);
  62626. return this._texture;
  62627. };
  62628. /**
  62629. * Starts the loading process of the texture.
  62630. */
  62631. ColorGradingTexture.prototype.loadTexture = function () {
  62632. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  62633. this.load3dlTexture();
  62634. }
  62635. };
  62636. /**
  62637. * Clones the color gradind texture.
  62638. */
  62639. ColorGradingTexture.prototype.clone = function () {
  62640. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  62641. // Base texture
  62642. newTexture.level = this.level;
  62643. return newTexture;
  62644. };
  62645. /**
  62646. * Called during delayed load for textures.
  62647. */
  62648. ColorGradingTexture.prototype.delayLoad = function () {
  62649. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62650. return;
  62651. }
  62652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62653. this._texture = this._getFromCache(this.url, true);
  62654. if (!this._texture) {
  62655. this.loadTexture();
  62656. }
  62657. };
  62658. /**
  62659. * Parses a color grading texture serialized by Babylon.
  62660. * @param parsedTexture The texture information being parsedTexture
  62661. * @param scene The scene to load the texture in
  62662. * @param rootUrl The root url of the data assets to load
  62663. * @return A color gradind texture
  62664. */
  62665. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62666. var texture = null;
  62667. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  62668. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  62669. texture.name = parsedTexture.name;
  62670. texture.level = parsedTexture.level;
  62671. }
  62672. return texture;
  62673. };
  62674. /**
  62675. * Serializes the LUT texture to json format.
  62676. */
  62677. ColorGradingTexture.prototype.serialize = function () {
  62678. if (!this.name) {
  62679. return null;
  62680. }
  62681. var serializationObject = {};
  62682. serializationObject.name = this.name;
  62683. serializationObject.level = this.level;
  62684. serializationObject.customType = "BABYLON.ColorGradingTexture";
  62685. return serializationObject;
  62686. };
  62687. return ColorGradingTexture;
  62688. }(BABYLON.BaseTexture));
  62689. /**
  62690. * Empty line regex stored for GC.
  62691. */
  62692. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  62693. BABYLON.ColorGradingTexture = ColorGradingTexture;
  62694. })(BABYLON || (BABYLON = {}));
  62695. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  62696. var BABYLON;
  62697. (function (BABYLON) {
  62698. /**
  62699. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  62700. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  62701. * 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;
  62702. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  62703. */
  62704. var ColorCurves = (function () {
  62705. function ColorCurves() {
  62706. this._dirty = true;
  62707. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  62708. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  62709. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62710. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  62711. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  62712. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  62713. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  62714. this._globalHue = 30;
  62715. this._globalDensity = 0;
  62716. this._globalSaturation = 0;
  62717. this._globalExposure = 0;
  62718. this._highlightsHue = 30;
  62719. this._highlightsDensity = 0;
  62720. this._highlightsSaturation = 0;
  62721. this._highlightsExposure = 0;
  62722. this._midtonesHue = 30;
  62723. this._midtonesDensity = 0;
  62724. this._midtonesSaturation = 0;
  62725. this._midtonesExposure = 0;
  62726. this._shadowsHue = 30;
  62727. this._shadowsDensity = 0;
  62728. this._shadowsSaturation = 0;
  62729. this._shadowsExposure = 0;
  62730. }
  62731. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  62732. /**
  62733. * Gets the global Hue value.
  62734. * 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).
  62735. */
  62736. get: function () {
  62737. return this._globalHue;
  62738. },
  62739. /**
  62740. * Sets the global Hue value.
  62741. * 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).
  62742. */
  62743. set: function (value) {
  62744. this._globalHue = value;
  62745. this._dirty = true;
  62746. },
  62747. enumerable: true,
  62748. configurable: true
  62749. });
  62750. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  62751. /**
  62752. * Gets the global Density value.
  62753. * 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.
  62754. * Values less than zero provide a filter of opposite hue.
  62755. */
  62756. get: function () {
  62757. return this._globalDensity;
  62758. },
  62759. /**
  62760. * Sets the global Density value.
  62761. * 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.
  62762. * Values less than zero provide a filter of opposite hue.
  62763. */
  62764. set: function (value) {
  62765. this._globalDensity = value;
  62766. this._dirty = true;
  62767. },
  62768. enumerable: true,
  62769. configurable: true
  62770. });
  62771. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  62772. /**
  62773. * Gets the global Saturation value.
  62774. * 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.
  62775. */
  62776. get: function () {
  62777. return this._globalSaturation;
  62778. },
  62779. /**
  62780. * Sets the global Saturation value.
  62781. * 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.
  62782. */
  62783. set: function (value) {
  62784. this._globalSaturation = value;
  62785. this._dirty = true;
  62786. },
  62787. enumerable: true,
  62788. configurable: true
  62789. });
  62790. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  62791. /**
  62792. * Gets the highlights Hue value.
  62793. * 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).
  62794. */
  62795. get: function () {
  62796. return this._highlightsHue;
  62797. },
  62798. /**
  62799. * Sets the highlights Hue value.
  62800. * 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).
  62801. */
  62802. set: function (value) {
  62803. this._highlightsHue = value;
  62804. this._dirty = true;
  62805. },
  62806. enumerable: true,
  62807. configurable: true
  62808. });
  62809. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  62810. /**
  62811. * Gets the highlights Density value.
  62812. * 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.
  62813. * Values less than zero provide a filter of opposite hue.
  62814. */
  62815. get: function () {
  62816. return this._highlightsDensity;
  62817. },
  62818. /**
  62819. * Sets the highlights Density value.
  62820. * 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.
  62821. * Values less than zero provide a filter of opposite hue.
  62822. */
  62823. set: function (value) {
  62824. this._highlightsDensity = value;
  62825. this._dirty = true;
  62826. },
  62827. enumerable: true,
  62828. configurable: true
  62829. });
  62830. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  62831. /**
  62832. * Gets the highlights Saturation value.
  62833. * 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.
  62834. */
  62835. get: function () {
  62836. return this._highlightsSaturation;
  62837. },
  62838. /**
  62839. * Sets the highlights Saturation value.
  62840. * 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.
  62841. */
  62842. set: function (value) {
  62843. this._highlightsSaturation = value;
  62844. this._dirty = true;
  62845. },
  62846. enumerable: true,
  62847. configurable: true
  62848. });
  62849. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  62850. /**
  62851. * Gets the highlights Exposure value.
  62852. * 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.
  62853. */
  62854. get: function () {
  62855. return this._highlightsExposure;
  62856. },
  62857. /**
  62858. * Sets the highlights Exposure value.
  62859. * 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.
  62860. */
  62861. set: function (value) {
  62862. this._highlightsExposure = value;
  62863. this._dirty = true;
  62864. },
  62865. enumerable: true,
  62866. configurable: true
  62867. });
  62868. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  62869. /**
  62870. * Gets the midtones Hue value.
  62871. * 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).
  62872. */
  62873. get: function () {
  62874. return this._midtonesHue;
  62875. },
  62876. /**
  62877. * Sets the midtones Hue value.
  62878. * 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).
  62879. */
  62880. set: function (value) {
  62881. this._midtonesHue = value;
  62882. this._dirty = true;
  62883. },
  62884. enumerable: true,
  62885. configurable: true
  62886. });
  62887. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  62888. /**
  62889. * Gets the midtones Density value.
  62890. * 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.
  62891. * Values less than zero provide a filter of opposite hue.
  62892. */
  62893. get: function () {
  62894. return this._midtonesDensity;
  62895. },
  62896. /**
  62897. * Sets the midtones Density value.
  62898. * 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.
  62899. * Values less than zero provide a filter of opposite hue.
  62900. */
  62901. set: function (value) {
  62902. this._midtonesDensity = value;
  62903. this._dirty = true;
  62904. },
  62905. enumerable: true,
  62906. configurable: true
  62907. });
  62908. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  62909. /**
  62910. * Gets the midtones Saturation value.
  62911. * 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.
  62912. */
  62913. get: function () {
  62914. return this._midtonesSaturation;
  62915. },
  62916. /**
  62917. * Sets the midtones Saturation value.
  62918. * 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.
  62919. */
  62920. set: function (value) {
  62921. this._midtonesSaturation = value;
  62922. this._dirty = true;
  62923. },
  62924. enumerable: true,
  62925. configurable: true
  62926. });
  62927. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  62928. /**
  62929. * Gets the midtones Exposure value.
  62930. * 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.
  62931. */
  62932. get: function () {
  62933. return this._midtonesExposure;
  62934. },
  62935. /**
  62936. * Sets the midtones Exposure value.
  62937. * 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.
  62938. */
  62939. set: function (value) {
  62940. this._midtonesExposure = value;
  62941. this._dirty = true;
  62942. },
  62943. enumerable: true,
  62944. configurable: true
  62945. });
  62946. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  62947. /**
  62948. * Gets the shadows Hue value.
  62949. * 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).
  62950. */
  62951. get: function () {
  62952. return this._shadowsHue;
  62953. },
  62954. /**
  62955. * Sets the shadows Hue value.
  62956. * 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).
  62957. */
  62958. set: function (value) {
  62959. this._shadowsHue = value;
  62960. this._dirty = true;
  62961. },
  62962. enumerable: true,
  62963. configurable: true
  62964. });
  62965. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  62966. /**
  62967. * Gets the shadows Density value.
  62968. * 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.
  62969. * Values less than zero provide a filter of opposite hue.
  62970. */
  62971. get: function () {
  62972. return this._shadowsDensity;
  62973. },
  62974. /**
  62975. * Sets the shadows Density value.
  62976. * 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.
  62977. * Values less than zero provide a filter of opposite hue.
  62978. */
  62979. set: function (value) {
  62980. this._shadowsDensity = value;
  62981. this._dirty = true;
  62982. },
  62983. enumerable: true,
  62984. configurable: true
  62985. });
  62986. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  62987. /**
  62988. * Gets the shadows Saturation value.
  62989. * 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.
  62990. */
  62991. get: function () {
  62992. return this._shadowsSaturation;
  62993. },
  62994. /**
  62995. * Sets the shadows Saturation value.
  62996. * 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.
  62997. */
  62998. set: function (value) {
  62999. this._shadowsSaturation = value;
  63000. this._dirty = true;
  63001. },
  63002. enumerable: true,
  63003. configurable: true
  63004. });
  63005. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  63006. /**
  63007. * Gets the shadows Exposure value.
  63008. * 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.
  63009. */
  63010. get: function () {
  63011. return this._shadowsExposure;
  63012. },
  63013. /**
  63014. * Sets the shadows Exposure value.
  63015. * 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.
  63016. */
  63017. set: function (value) {
  63018. this._shadowsExposure = value;
  63019. this._dirty = true;
  63020. },
  63021. enumerable: true,
  63022. configurable: true
  63023. });
  63024. ColorCurves.prototype.getClassName = function () {
  63025. return "ColorCurves";
  63026. };
  63027. /**
  63028. * Binds the color curves to the shader.
  63029. * @param colorCurves The color curve to bind
  63030. * @param effect The effect to bind to
  63031. */
  63032. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  63033. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  63034. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  63035. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  63036. if (colorCurves._dirty) {
  63037. colorCurves._dirty = false;
  63038. // Fill in global info.
  63039. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  63040. // Compute highlights info.
  63041. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  63042. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  63043. // Compute midtones info.
  63044. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  63045. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  63046. // Compute shadows info.
  63047. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  63048. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  63049. // Compute deltas (neutral is midtones).
  63050. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  63051. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  63052. }
  63053. if (effect) {
  63054. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  63055. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  63056. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  63057. }
  63058. };
  63059. /**
  63060. * Prepare the list of uniforms associated with the ColorCurves effects.
  63061. * @param uniformsList The list of uniforms used in the effect
  63062. */
  63063. ColorCurves.PrepareUniforms = function (uniformsList) {
  63064. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  63065. };
  63066. /**
  63067. * Returns color grading data based on a hue, density, saturation and exposure value.
  63068. * @param filterHue The hue of the color filter.
  63069. * @param filterDensity The density of the color filter.
  63070. * @param saturation The saturation.
  63071. * @param exposure The exposure.
  63072. * @param result The result data container.
  63073. */
  63074. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  63075. if (hue == null) {
  63076. return;
  63077. }
  63078. hue = ColorCurves.clamp(hue, 0, 360);
  63079. density = ColorCurves.clamp(density, -100, 100);
  63080. saturation = ColorCurves.clamp(saturation, -100, 100);
  63081. exposure = ColorCurves.clamp(exposure, -100, 100);
  63082. // Remap the slider/config filter density with non-linear mapping and also scale by half
  63083. // so that the maximum filter density is only 50% control. This provides fine control
  63084. // for small values and reasonable range.
  63085. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  63086. density *= 0.5;
  63087. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  63088. if (density < 0) {
  63089. density *= -1;
  63090. hue = (hue + 180) % 360;
  63091. }
  63092. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  63093. result.scaleToRef(2, result);
  63094. result.a = 1 + 0.01 * saturation;
  63095. };
  63096. /**
  63097. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  63098. * @param value The input slider value in range [-100,100].
  63099. * @returns Adjusted value.
  63100. */
  63101. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  63102. value /= 100;
  63103. var x = Math.abs(value);
  63104. x = Math.pow(x, 2);
  63105. if (value < 0) {
  63106. x *= -1;
  63107. }
  63108. x *= 100;
  63109. return x;
  63110. };
  63111. /**
  63112. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  63113. * @param hue The hue (H) input.
  63114. * @param saturation The saturation (S) input.
  63115. * @param brightness The brightness (B) input.
  63116. * @result An RGBA color represented as Vector4.
  63117. */
  63118. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  63119. var h = ColorCurves.clamp(hue, 0, 360);
  63120. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  63121. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  63122. if (s === 0) {
  63123. result.r = v;
  63124. result.g = v;
  63125. result.b = v;
  63126. }
  63127. else {
  63128. // sector 0 to 5
  63129. h /= 60;
  63130. var i = Math.floor(h);
  63131. // fractional part of h
  63132. var f = h - i;
  63133. var p = v * (1 - s);
  63134. var q = v * (1 - s * f);
  63135. var t = v * (1 - s * (1 - f));
  63136. switch (i) {
  63137. case 0:
  63138. result.r = v;
  63139. result.g = t;
  63140. result.b = p;
  63141. break;
  63142. case 1:
  63143. result.r = q;
  63144. result.g = v;
  63145. result.b = p;
  63146. break;
  63147. case 2:
  63148. result.r = p;
  63149. result.g = v;
  63150. result.b = t;
  63151. break;
  63152. case 3:
  63153. result.r = p;
  63154. result.g = q;
  63155. result.b = v;
  63156. break;
  63157. case 4:
  63158. result.r = t;
  63159. result.g = p;
  63160. result.b = v;
  63161. break;
  63162. default:
  63163. result.r = v;
  63164. result.g = p;
  63165. result.b = q;
  63166. break;
  63167. }
  63168. }
  63169. result.a = 1;
  63170. };
  63171. /**
  63172. * Returns a value clamped between min and max
  63173. * @param value The value to clamp
  63174. * @param min The minimum of value
  63175. * @param max The maximum of value
  63176. * @returns The clamped value.
  63177. */
  63178. ColorCurves.clamp = function (value, min, max) {
  63179. return Math.min(Math.max(value, min), max);
  63180. };
  63181. /**
  63182. * Clones the current color curve instance.
  63183. * @return The cloned curves
  63184. */
  63185. ColorCurves.prototype.clone = function () {
  63186. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  63187. };
  63188. /**
  63189. * Serializes the current color curve instance to a json representation.
  63190. * @return a JSON representation
  63191. */
  63192. ColorCurves.prototype.serialize = function () {
  63193. return BABYLON.SerializationHelper.Serialize(this);
  63194. };
  63195. /**
  63196. * Parses the color curve from a json representation.
  63197. * @param source the JSON source to parse
  63198. * @return The parsed curves
  63199. */
  63200. ColorCurves.Parse = function (source) {
  63201. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  63202. };
  63203. return ColorCurves;
  63204. }());
  63205. __decorate([
  63206. BABYLON.serialize()
  63207. ], ColorCurves.prototype, "_globalHue", void 0);
  63208. __decorate([
  63209. BABYLON.serialize()
  63210. ], ColorCurves.prototype, "_globalDensity", void 0);
  63211. __decorate([
  63212. BABYLON.serialize()
  63213. ], ColorCurves.prototype, "_globalSaturation", void 0);
  63214. __decorate([
  63215. BABYLON.serialize()
  63216. ], ColorCurves.prototype, "_globalExposure", void 0);
  63217. __decorate([
  63218. BABYLON.serialize()
  63219. ], ColorCurves.prototype, "_highlightsHue", void 0);
  63220. __decorate([
  63221. BABYLON.serialize()
  63222. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  63223. __decorate([
  63224. BABYLON.serialize()
  63225. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  63226. __decorate([
  63227. BABYLON.serialize()
  63228. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  63229. __decorate([
  63230. BABYLON.serialize()
  63231. ], ColorCurves.prototype, "_midtonesHue", void 0);
  63232. __decorate([
  63233. BABYLON.serialize()
  63234. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  63235. __decorate([
  63236. BABYLON.serialize()
  63237. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  63238. __decorate([
  63239. BABYLON.serialize()
  63240. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  63241. BABYLON.ColorCurves = ColorCurves;
  63242. })(BABYLON || (BABYLON = {}));
  63243. //# sourceMappingURL=babylon.colorCurves.js.map
  63244. var BABYLON;
  63245. (function (BABYLON) {
  63246. var Octree = (function () {
  63247. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  63248. if (maxDepth === void 0) { maxDepth = 2; }
  63249. this.maxDepth = maxDepth;
  63250. this.dynamicContent = new Array();
  63251. this._maxBlockCapacity = maxBlockCapacity || 64;
  63252. this._selectionContent = new BABYLON.SmartArray(1024);
  63253. this._creationFunc = creationFunc;
  63254. }
  63255. // Methods
  63256. Octree.prototype.update = function (worldMin, worldMax, entries) {
  63257. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  63258. };
  63259. Octree.prototype.addMesh = function (entry) {
  63260. for (var index = 0; index < this.blocks.length; index++) {
  63261. var block = this.blocks[index];
  63262. block.addEntry(entry);
  63263. }
  63264. };
  63265. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  63266. this._selectionContent.reset();
  63267. for (var index = 0; index < this.blocks.length; index++) {
  63268. var block = this.blocks[index];
  63269. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  63270. }
  63271. if (allowDuplicate) {
  63272. this._selectionContent.concat(this.dynamicContent);
  63273. }
  63274. else {
  63275. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63276. }
  63277. return this._selectionContent;
  63278. };
  63279. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  63280. this._selectionContent.reset();
  63281. for (var index = 0; index < this.blocks.length; index++) {
  63282. var block = this.blocks[index];
  63283. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  63284. }
  63285. if (allowDuplicate) {
  63286. this._selectionContent.concat(this.dynamicContent);
  63287. }
  63288. else {
  63289. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63290. }
  63291. return this._selectionContent;
  63292. };
  63293. Octree.prototype.intersectsRay = function (ray) {
  63294. this._selectionContent.reset();
  63295. for (var index = 0; index < this.blocks.length; index++) {
  63296. var block = this.blocks[index];
  63297. block.intersectsRay(ray, this._selectionContent);
  63298. }
  63299. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63300. return this._selectionContent;
  63301. };
  63302. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  63303. target.blocks = new Array();
  63304. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  63305. // Segmenting space
  63306. for (var x = 0; x < 2; x++) {
  63307. for (var y = 0; y < 2; y++) {
  63308. for (var z = 0; z < 2; z++) {
  63309. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  63310. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  63311. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  63312. block.addEntries(entries);
  63313. target.blocks.push(block);
  63314. }
  63315. }
  63316. }
  63317. };
  63318. return Octree;
  63319. }());
  63320. Octree.CreationFuncForMeshes = function (entry, block) {
  63321. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  63322. block.entries.push(entry);
  63323. }
  63324. };
  63325. Octree.CreationFuncForSubMeshes = function (entry, block) {
  63326. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  63327. block.entries.push(entry);
  63328. }
  63329. };
  63330. BABYLON.Octree = Octree;
  63331. })(BABYLON || (BABYLON = {}));
  63332. //# sourceMappingURL=babylon.octree.js.map
  63333. var BABYLON;
  63334. (function (BABYLON) {
  63335. var OctreeBlock = (function () {
  63336. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  63337. this.entries = new Array();
  63338. this._boundingVectors = new Array();
  63339. this._capacity = capacity;
  63340. this._depth = depth;
  63341. this._maxDepth = maxDepth;
  63342. this._creationFunc = creationFunc;
  63343. this._minPoint = minPoint;
  63344. this._maxPoint = maxPoint;
  63345. this._boundingVectors.push(minPoint.clone());
  63346. this._boundingVectors.push(maxPoint.clone());
  63347. this._boundingVectors.push(minPoint.clone());
  63348. this._boundingVectors[2].x = maxPoint.x;
  63349. this._boundingVectors.push(minPoint.clone());
  63350. this._boundingVectors[3].y = maxPoint.y;
  63351. this._boundingVectors.push(minPoint.clone());
  63352. this._boundingVectors[4].z = maxPoint.z;
  63353. this._boundingVectors.push(maxPoint.clone());
  63354. this._boundingVectors[5].z = minPoint.z;
  63355. this._boundingVectors.push(maxPoint.clone());
  63356. this._boundingVectors[6].x = minPoint.x;
  63357. this._boundingVectors.push(maxPoint.clone());
  63358. this._boundingVectors[7].y = minPoint.y;
  63359. }
  63360. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  63361. // Property
  63362. get: function () {
  63363. return this._capacity;
  63364. },
  63365. enumerable: true,
  63366. configurable: true
  63367. });
  63368. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  63369. get: function () {
  63370. return this._minPoint;
  63371. },
  63372. enumerable: true,
  63373. configurable: true
  63374. });
  63375. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  63376. get: function () {
  63377. return this._maxPoint;
  63378. },
  63379. enumerable: true,
  63380. configurable: true
  63381. });
  63382. // Methods
  63383. OctreeBlock.prototype.addEntry = function (entry) {
  63384. if (this.blocks) {
  63385. for (var index = 0; index < this.blocks.length; index++) {
  63386. var block = this.blocks[index];
  63387. block.addEntry(entry);
  63388. }
  63389. return;
  63390. }
  63391. this._creationFunc(entry, this);
  63392. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  63393. this.createInnerBlocks();
  63394. }
  63395. };
  63396. OctreeBlock.prototype.addEntries = function (entries) {
  63397. for (var index = 0; index < entries.length; index++) {
  63398. var mesh = entries[index];
  63399. this.addEntry(mesh);
  63400. }
  63401. };
  63402. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  63403. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  63404. if (this.blocks) {
  63405. for (var index = 0; index < this.blocks.length; index++) {
  63406. var block = this.blocks[index];
  63407. block.select(frustumPlanes, selection, allowDuplicate);
  63408. }
  63409. return;
  63410. }
  63411. if (allowDuplicate) {
  63412. selection.concat(this.entries);
  63413. }
  63414. else {
  63415. selection.concatWithNoDuplicate(this.entries);
  63416. }
  63417. }
  63418. };
  63419. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  63420. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  63421. if (this.blocks) {
  63422. for (var index = 0; index < this.blocks.length; index++) {
  63423. var block = this.blocks[index];
  63424. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  63425. }
  63426. return;
  63427. }
  63428. if (allowDuplicate) {
  63429. selection.concat(this.entries);
  63430. }
  63431. else {
  63432. selection.concatWithNoDuplicate(this.entries);
  63433. }
  63434. }
  63435. };
  63436. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  63437. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  63438. if (this.blocks) {
  63439. for (var index = 0; index < this.blocks.length; index++) {
  63440. var block = this.blocks[index];
  63441. block.intersectsRay(ray, selection);
  63442. }
  63443. return;
  63444. }
  63445. selection.concatWithNoDuplicate(this.entries);
  63446. }
  63447. };
  63448. OctreeBlock.prototype.createInnerBlocks = function () {
  63449. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  63450. };
  63451. return OctreeBlock;
  63452. }());
  63453. BABYLON.OctreeBlock = OctreeBlock;
  63454. })(BABYLON || (BABYLON = {}));
  63455. //# sourceMappingURL=babylon.octreeBlock.js.map
  63456. var BABYLON;
  63457. (function (BABYLON) {
  63458. var SIMDVector3 = (function () {
  63459. function SIMDVector3() {
  63460. }
  63461. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  63462. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  63463. };
  63464. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  63465. var m = transformation.m;
  63466. var m0 = SIMD.Float32x4.load(m, 0);
  63467. var m1 = SIMD.Float32x4.load(m, 4);
  63468. var m2 = SIMD.Float32x4.load(m, 8);
  63469. var m3 = SIMD.Float32x4.load(m, 12);
  63470. 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));
  63471. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  63472. result.x = SIMD.Float32x4.extractLane(r, 0);
  63473. result.y = SIMD.Float32x4.extractLane(r, 1);
  63474. result.z = SIMD.Float32x4.extractLane(r, 2);
  63475. };
  63476. return SIMDVector3;
  63477. }());
  63478. var SIMDMatrix = (function () {
  63479. function SIMDMatrix() {
  63480. }
  63481. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  63482. var tm = this.m;
  63483. var om = other.m;
  63484. var m0 = SIMD.Float32x4.load(om, 0);
  63485. var m1 = SIMD.Float32x4.load(om, 4);
  63486. var m2 = SIMD.Float32x4.load(om, 8);
  63487. var m3 = SIMD.Float32x4.load(om, 12);
  63488. for (var i = 0; i < 16; i += 4) {
  63489. 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)))));
  63490. }
  63491. return this;
  63492. };
  63493. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  63494. var src = this.m;
  63495. var dest = other.m;
  63496. // Load the 4 rows
  63497. var src0 = SIMD.Float32x4.load(src, 0);
  63498. var src1 = SIMD.Float32x4.load(src, 4);
  63499. var src2 = SIMD.Float32x4.load(src, 8);
  63500. var src3 = SIMD.Float32x4.load(src, 12);
  63501. // Transpose the source matrix. Sort of. Not a true transpose operation
  63502. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  63503. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  63504. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  63505. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  63506. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  63507. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  63508. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  63509. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  63510. // This is a true transposition, but it will lead to an incorrect result
  63511. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  63512. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  63513. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  63514. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  63515. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  63516. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  63517. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  63518. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  63519. // ----
  63520. tmp1 = SIMD.Float32x4.mul(row2, row3);
  63521. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63522. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  63523. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  63524. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63525. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  63526. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  63527. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  63528. // ----
  63529. tmp1 = SIMD.Float32x4.mul(row1, row2);
  63530. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63531. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  63532. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  63533. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63534. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  63535. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  63536. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  63537. // ----
  63538. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  63539. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63540. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  63541. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  63542. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  63543. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63544. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  63545. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  63546. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  63547. // ----
  63548. tmp1 = SIMD.Float32x4.mul(row0, row1);
  63549. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63550. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  63551. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  63552. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63553. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  63554. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  63555. // ----
  63556. tmp1 = SIMD.Float32x4.mul(row0, row3);
  63557. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63558. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  63559. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  63560. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63561. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  63562. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  63563. // ----
  63564. tmp1 = SIMD.Float32x4.mul(row0, row2);
  63565. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  63566. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  63567. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  63568. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  63569. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  63570. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  63571. // Compute determinant
  63572. var det = SIMD.Float32x4.mul(row0, minor0);
  63573. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  63574. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  63575. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  63576. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  63577. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  63578. // These shuffles aren't necessary if the faulty transposition is done
  63579. // up at the top of this function.
  63580. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  63581. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  63582. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  63583. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  63584. // Compute final values by multiplying with 1/det
  63585. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  63586. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  63587. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  63588. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  63589. return this;
  63590. };
  63591. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  63592. var out = result.m;
  63593. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  63594. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  63595. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  63596. // cc.kmVec3Subtract(f, pCenter, pEye);
  63597. var f = SIMD.Float32x4.sub(center, eye);
  63598. // cc.kmVec3Normalize(f, f);
  63599. var tmp = SIMD.Float32x4.mul(f, f);
  63600. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63601. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63602. // cc.kmVec3Assign(up, pUp);
  63603. // cc.kmVec3Normalize(up, up);
  63604. tmp = SIMD.Float32x4.mul(up, up);
  63605. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63606. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63607. // cc.kmVec3Cross(s, f, up);
  63608. 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)));
  63609. // cc.kmVec3Normalize(s, s);
  63610. tmp = SIMD.Float32x4.mul(s, s);
  63611. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63612. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63613. // cc.kmVec3Cross(u, s, f);
  63614. 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)));
  63615. // cc.kmVec3Normalize(s, s);
  63616. tmp = SIMD.Float32x4.mul(s, s);
  63617. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  63618. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  63619. var zero = SIMD.Float32x4.splat(0.0);
  63620. s = SIMD.Float32x4.neg(s);
  63621. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  63622. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  63623. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  63624. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  63625. 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);
  63626. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  63627. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  63628. 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)))));
  63629. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  63630. 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)))));
  63631. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  63632. 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)))));
  63633. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  63634. 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)))));
  63635. };
  63636. return SIMDMatrix;
  63637. }());
  63638. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  63639. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  63640. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  63641. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  63642. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  63643. var SIMDHelper = (function () {
  63644. function SIMDHelper() {
  63645. }
  63646. Object.defineProperty(SIMDHelper, "IsEnabled", {
  63647. get: function () {
  63648. return SIMDHelper._isEnabled;
  63649. },
  63650. enumerable: true,
  63651. configurable: true
  63652. });
  63653. SIMDHelper.DisableSIMD = function () {
  63654. // Replace functions
  63655. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  63656. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  63657. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  63658. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  63659. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  63660. SIMDHelper._isEnabled = false;
  63661. };
  63662. SIMDHelper.EnableSIMD = function () {
  63663. if (self.SIMD === undefined) {
  63664. return;
  63665. }
  63666. // check if polyfills needed
  63667. if (!self.Math.fround) {
  63668. self.Math.fround = (function (array) { return function (x) {
  63669. return array[0] = x, array[0];
  63670. }; })(new Float32Array(1));
  63671. }
  63672. if (!self.Math.imul) {
  63673. self.Math.imul = function (a, b) {
  63674. var ah = (a >>> 16) & 0xffff;
  63675. var al = a & 0xffff;
  63676. var bh = (b >>> 16) & 0xffff;
  63677. var bl = b & 0xffff;
  63678. // the shift by 0 fixes the sign on the high part
  63679. // the final |0 converts the unsigned value into a signed value
  63680. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  63681. };
  63682. }
  63683. // Replace functions
  63684. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  63685. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  63686. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  63687. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  63688. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  63689. SIMDHelper._isEnabled = true;
  63690. };
  63691. return SIMDHelper;
  63692. }());
  63693. SIMDHelper._isEnabled = false;
  63694. BABYLON.SIMDHelper = SIMDHelper;
  63695. })(BABYLON || (BABYLON = {}));
  63696. //# sourceMappingURL=babylon.math.SIMD.js.map
  63697. var BABYLON;
  63698. (function (BABYLON) {
  63699. var VRDistortionCorrectionPostProcess = (function (_super) {
  63700. __extends(VRDistortionCorrectionPostProcess, _super);
  63701. //ANY
  63702. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  63703. var _this = _super.call(this, name, "vrDistortionCorrection", [
  63704. 'LensCenter',
  63705. 'Scale',
  63706. 'ScaleIn',
  63707. 'HmdWarpParam'
  63708. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  63709. _this._isRightEye = isRightEye;
  63710. _this._distortionFactors = vrMetrics.distortionK;
  63711. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  63712. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  63713. _this.onSizeChangedObservable.add(function () {
  63714. _this.aspectRatio = _this.width * .5 / _this.height;
  63715. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  63716. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  63717. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  63718. });
  63719. _this.onApplyObservable.add(function (effect) {
  63720. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  63721. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  63722. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  63723. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  63724. });
  63725. return _this;
  63726. }
  63727. return VRDistortionCorrectionPostProcess;
  63728. }(BABYLON.PostProcess));
  63729. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  63730. })(BABYLON || (BABYLON = {}));
  63731. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  63732. var BABYLON;
  63733. (function (BABYLON) {
  63734. var AnaglyphPostProcess = (function (_super) {
  63735. __extends(AnaglyphPostProcess, _super);
  63736. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  63737. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  63738. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63739. _this.onApplyObservable.add(function (effect) {
  63740. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  63741. });
  63742. return _this;
  63743. }
  63744. return AnaglyphPostProcess;
  63745. }(BABYLON.PostProcess));
  63746. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  63747. })(BABYLON || (BABYLON = {}));
  63748. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  63749. var BABYLON;
  63750. (function (BABYLON) {
  63751. var StereoscopicInterlacePostProcess = (function (_super) {
  63752. __extends(StereoscopicInterlacePostProcess, _super);
  63753. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  63754. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  63755. _this._passedProcess = rigCameras[0]._rigPostProcess;
  63756. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63757. _this.onSizeChangedObservable.add(function () {
  63758. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  63759. });
  63760. _this.onApplyObservable.add(function (effect) {
  63761. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  63762. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  63763. });
  63764. return _this;
  63765. }
  63766. return StereoscopicInterlacePostProcess;
  63767. }(BABYLON.PostProcess));
  63768. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  63769. })(BABYLON || (BABYLON = {}));
  63770. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  63771. var BABYLON;
  63772. (function (BABYLON) {
  63773. var FreeCameraDeviceOrientationInput = (function () {
  63774. function FreeCameraDeviceOrientationInput() {
  63775. var _this = this;
  63776. this._screenOrientationAngle = 0;
  63777. this._screenQuaternion = new BABYLON.Quaternion();
  63778. this._alpha = 0;
  63779. this._beta = 0;
  63780. this._gamma = 0;
  63781. this._orientationChanged = function () {
  63782. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  63783. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  63784. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  63785. };
  63786. this._deviceOrientation = function (evt) {
  63787. _this._alpha = evt.alpha;
  63788. _this._beta = evt.beta;
  63789. _this._gamma = evt.gamma;
  63790. };
  63791. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  63792. this._orientationChanged();
  63793. }
  63794. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  63795. get: function () {
  63796. return this._camera;
  63797. },
  63798. set: function (camera) {
  63799. this._camera = camera;
  63800. if (!this._camera.rotationQuaternion)
  63801. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  63802. },
  63803. enumerable: true,
  63804. configurable: true
  63805. });
  63806. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63807. window.addEventListener("orientationchange", this._orientationChanged);
  63808. window.addEventListener("deviceorientation", this._deviceOrientation);
  63809. //In certain cases, the attach control is called AFTER orientation was changed,
  63810. //So this is needed.
  63811. this._orientationChanged();
  63812. };
  63813. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  63814. window.removeEventListener("orientationchange", this._orientationChanged);
  63815. window.removeEventListener("deviceorientation", this._deviceOrientation);
  63816. };
  63817. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  63818. //if no device orientation provided, don't update the rotation.
  63819. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  63820. if (!this._alpha)
  63821. return;
  63822. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  63823. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  63824. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  63825. //Mirror on XY Plane
  63826. this._camera.rotationQuaternion.z *= -1;
  63827. this._camera.rotationQuaternion.w *= -1;
  63828. };
  63829. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  63830. return "FreeCameraDeviceOrientationInput";
  63831. };
  63832. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  63833. return "deviceOrientation";
  63834. };
  63835. return FreeCameraDeviceOrientationInput;
  63836. }());
  63837. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  63838. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  63839. })(BABYLON || (BABYLON = {}));
  63840. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  63841. var BABYLON;
  63842. (function (BABYLON) {
  63843. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  63844. function ArcRotateCameraVRDeviceOrientationInput() {
  63845. this.alphaCorrection = 1;
  63846. this.betaCorrection = 1;
  63847. this.gammaCorrection = 1;
  63848. this._alpha = 0;
  63849. this._beta = 0;
  63850. this._gamma = 0;
  63851. this._dirty = false;
  63852. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  63853. }
  63854. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  63855. this.camera.attachControl(element, noPreventDefault);
  63856. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  63857. };
  63858. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  63859. var camera = this.camera;
  63860. this._alpha = +evt.alpha | 0;
  63861. this._beta = +evt.beta | 0;
  63862. this._gamma = +evt.gamma | 0;
  63863. this._dirty = true;
  63864. };
  63865. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  63866. if (this._dirty) {
  63867. this._dirty = false;
  63868. if (this._gamma < 0) {
  63869. this._gamma = 180 + this._gamma;
  63870. }
  63871. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  63872. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  63873. }
  63874. };
  63875. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  63876. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  63877. };
  63878. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  63879. return "ArcRotateCameraVRDeviceOrientationInput";
  63880. };
  63881. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  63882. return "VRDeviceOrientation";
  63883. };
  63884. return ArcRotateCameraVRDeviceOrientationInput;
  63885. }());
  63886. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  63887. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  63888. })(BABYLON || (BABYLON = {}));
  63889. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  63890. var BABYLON;
  63891. (function (BABYLON) {
  63892. var VRCameraMetrics = (function () {
  63893. function VRCameraMetrics() {
  63894. this.compensateDistortion = true;
  63895. }
  63896. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  63897. get: function () {
  63898. return this.hResolution / (2 * this.vResolution);
  63899. },
  63900. enumerable: true,
  63901. configurable: true
  63902. });
  63903. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  63904. get: function () {
  63905. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  63906. },
  63907. enumerable: true,
  63908. configurable: true
  63909. });
  63910. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  63911. get: function () {
  63912. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63913. var h = (4 * meters) / this.hScreenSize;
  63914. return BABYLON.Matrix.Translation(h, 0, 0);
  63915. },
  63916. enumerable: true,
  63917. configurable: true
  63918. });
  63919. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  63920. get: function () {
  63921. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  63922. var h = (4 * meters) / this.hScreenSize;
  63923. return BABYLON.Matrix.Translation(-h, 0, 0);
  63924. },
  63925. enumerable: true,
  63926. configurable: true
  63927. });
  63928. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  63929. get: function () {
  63930. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  63931. },
  63932. enumerable: true,
  63933. configurable: true
  63934. });
  63935. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  63936. get: function () {
  63937. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  63938. },
  63939. enumerable: true,
  63940. configurable: true
  63941. });
  63942. VRCameraMetrics.GetDefault = function () {
  63943. var result = new VRCameraMetrics();
  63944. result.hResolution = 1280;
  63945. result.vResolution = 800;
  63946. result.hScreenSize = 0.149759993;
  63947. result.vScreenSize = 0.0935999975;
  63948. result.vScreenCenter = 0.0467999987;
  63949. result.eyeToScreenDistance = 0.0410000011;
  63950. result.lensSeparationDistance = 0.0635000020;
  63951. result.interpupillaryDistance = 0.0640000030;
  63952. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  63953. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  63954. result.postProcessScaleFactor = 1.714605507808412;
  63955. result.lensCenterOffset = 0.151976421;
  63956. return result;
  63957. };
  63958. return VRCameraMetrics;
  63959. }());
  63960. BABYLON.VRCameraMetrics = VRCameraMetrics;
  63961. })(BABYLON || (BABYLON = {}));
  63962. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  63963. var BABYLON;
  63964. (function (BABYLON) {
  63965. var WebVRFreeCamera = (function (_super) {
  63966. __extends(WebVRFreeCamera, _super);
  63967. function WebVRFreeCamera(name, position, scene, webVROptions) {
  63968. if (webVROptions === void 0) { webVROptions = {}; }
  63969. var _this = _super.call(this, name, position, scene) || this;
  63970. _this.webVROptions = webVROptions;
  63971. _this._vrDevice = null;
  63972. _this.rawPose = null;
  63973. _this._vrEnabled = false;
  63974. _this._specsVersion = 1.1;
  63975. _this._attached = false;
  63976. _this._positionOffset = BABYLON.Vector3.Zero();
  63977. _this._descendants = [];
  63978. _this.devicePosition = BABYLON.Vector3.Zero();
  63979. _this.deviceScaleFactor = 1;
  63980. _this.controllers = [];
  63981. _this.nonVRControllers = [];
  63982. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  63983. //legacy support - the compensation boolean was removed.
  63984. if (arguments.length === 5) {
  63985. _this.webVROptions = arguments[4];
  63986. }
  63987. // default webVR options
  63988. if (_this.webVROptions.trackPosition == undefined) {
  63989. _this.webVROptions.trackPosition = true;
  63990. }
  63991. if (_this.webVROptions.controllerMeshes == undefined) {
  63992. _this.webVROptions.controllerMeshes = true;
  63993. }
  63994. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  63995. _this.webVROptions.defaultLightningOnControllers = true;
  63996. }
  63997. _this.rotationQuaternion = new BABYLON.Quaternion();
  63998. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63999. if (_this.webVROptions && _this.webVROptions.positionScale) {
  64000. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  64001. }
  64002. //enable VR
  64003. _this.getEngine().initWebVR();
  64004. //check specs version
  64005. if (!window.VRFrameData) {
  64006. _this._specsVersion = 1.0;
  64007. _this._frameData = {};
  64008. }
  64009. else {
  64010. _this._frameData = new VRFrameData();
  64011. }
  64012. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  64013. if (!device) {
  64014. return;
  64015. }
  64016. _this._vrEnabled = true;
  64017. _this._vrDevice = device;
  64018. //reset the rig parameters.
  64019. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  64020. if (_this._attached) {
  64021. _this.getEngine().enableVR(_this._vrDevice);
  64022. }
  64023. });
  64024. // try to attach the controllers, if found.
  64025. _this.initControllers();
  64026. /**
  64027. * The idea behind the following lines:
  64028. * objects that have the camera as parent should actually have the rig cameras as a parent.
  64029. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  64030. * the second will not show it correctly.
  64031. *
  64032. * To solve this - each object that has the camera as parent will be added to a protected array.
  64033. * When the rig camera renders, it will take this array and set all of those to be its children.
  64034. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  64035. * Amazing!
  64036. */
  64037. scene.onBeforeCameraRenderObservable.add(function (camera) {
  64038. if (camera.parent === _this && _this.rigParenting) {
  64039. _this._descendants = _this.getDescendants(true, function (n) {
  64040. // don't take the cameras or the controllers!
  64041. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  64042. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  64043. return !isController && !isRigCamera;
  64044. });
  64045. _this._descendants.forEach(function (node) {
  64046. node.parent = camera;
  64047. });
  64048. }
  64049. });
  64050. scene.onAfterCameraRenderObservable.add(function (camera) {
  64051. if (camera.parent === _this && _this.rigParenting) {
  64052. _this._descendants.forEach(function (node) {
  64053. node.parent = _this;
  64054. });
  64055. }
  64056. });
  64057. return _this;
  64058. }
  64059. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  64060. set: function (callback) {
  64061. this._onControllersAttached = callback;
  64062. // after setting - if the controllers are already set, execute the callback.
  64063. if (this.controllers.length >= 2) {
  64064. callback(this.controllers);
  64065. }
  64066. },
  64067. enumerable: true,
  64068. configurable: true
  64069. });
  64070. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  64071. set: function (callback) {
  64072. this._onNonVRControllerAttached = callback;
  64073. this.nonVRControllers.forEach(function (controller) {
  64074. callback(controller);
  64075. });
  64076. },
  64077. enumerable: true,
  64078. configurable: true
  64079. });
  64080. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  64081. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  64082. var gp = _a[_i];
  64083. if (gp.hand === name) {
  64084. return gp;
  64085. }
  64086. }
  64087. return undefined;
  64088. };
  64089. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  64090. get: function () {
  64091. if (!this._leftController) {
  64092. this._leftController = this.getControllerByName("left");
  64093. }
  64094. return this._leftController;
  64095. },
  64096. enumerable: true,
  64097. configurable: true
  64098. });
  64099. ;
  64100. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  64101. get: function () {
  64102. if (!this._rightController) {
  64103. this._rightController = this.getControllerByName("right");
  64104. }
  64105. return this._rightController;
  64106. },
  64107. enumerable: true,
  64108. configurable: true
  64109. });
  64110. ;
  64111. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  64112. if (length === void 0) { length = 100; }
  64113. if (this.leftCamera) {
  64114. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  64115. }
  64116. else {
  64117. return _super.prototype.getForwardRay.call(this, length);
  64118. }
  64119. };
  64120. WebVRFreeCamera.prototype._checkInputs = function () {
  64121. if (this._vrEnabled) {
  64122. if (this._specsVersion === 1.1) {
  64123. this._vrDevice.getFrameData(this._frameData);
  64124. }
  64125. else {
  64126. //backwards comp
  64127. var pose = this._vrDevice.getPose();
  64128. this._frameData.pose = pose;
  64129. // calculate view and projection matrix
  64130. }
  64131. this.updateFromDevice(this._frameData.pose);
  64132. }
  64133. _super.prototype._checkInputs.call(this);
  64134. };
  64135. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  64136. if (poseData && poseData.orientation) {
  64137. this.rawPose = poseData;
  64138. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  64139. if (this.getScene().useRightHandedSystem) {
  64140. this.deviceRotationQuaternion.z *= -1;
  64141. this.deviceRotationQuaternion.w *= -1;
  64142. }
  64143. if (this.webVROptions.trackPosition && this.rawPose.position) {
  64144. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  64145. if (this.getScene().useRightHandedSystem) {
  64146. this.devicePosition.z *= -1;
  64147. }
  64148. }
  64149. }
  64150. };
  64151. /**
  64152. * WebVR's attach control will start broadcasting frames to the device.
  64153. * Note that in certain browsers (chrome for example) this function must be called
  64154. * within a user-interaction callback. Example:
  64155. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  64156. *
  64157. * @param {HTMLElement} element
  64158. * @param {boolean} [noPreventDefault]
  64159. *
  64160. * @memberOf WebVRFreeCamera
  64161. */
  64162. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  64163. _super.prototype.attachControl.call(this, element, noPreventDefault);
  64164. this._attached = true;
  64165. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  64166. if (this._vrEnabled) {
  64167. this.getEngine().enableVR(this._vrDevice);
  64168. }
  64169. };
  64170. WebVRFreeCamera.prototype.detachControl = function (element) {
  64171. _super.prototype.detachControl.call(this, element);
  64172. this._vrEnabled = false;
  64173. this._attached = false;
  64174. this.getEngine().disableVR();
  64175. };
  64176. WebVRFreeCamera.prototype.getClassName = function () {
  64177. return "WebVRFreeCamera";
  64178. };
  64179. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  64180. //uses the vrDisplay's "resetPose()".
  64181. //pitch and roll won't be affected.
  64182. this._vrDevice.resetPose();
  64183. };
  64184. WebVRFreeCamera.prototype._updateRigCameras = function () {
  64185. var camLeft = this._rigCameras[0];
  64186. var camRight = this._rigCameras[1];
  64187. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64188. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64189. camLeft.position.copyFrom(this.devicePosition);
  64190. camRight.position.copyFrom(this.devicePosition);
  64191. };
  64192. /**
  64193. * This function is called by the two RIG cameras.
  64194. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  64195. */
  64196. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  64197. var _this = this;
  64198. //WebVR 1.0
  64199. if (this._cameraRigParams["specs"] === 1.0) {
  64200. this._updateCameraRotationMatrix();
  64201. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  64202. // Computing target and final matrix
  64203. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  64204. if (this.getScene().useRightHandedSystem) {
  64205. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  64206. }
  64207. else {
  64208. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  64209. }
  64210. //now move the eye in the right direction
  64211. var eyeParams = this._cameraRigParams["eyeParameters"];
  64212. var offset = eyeParams.offset;
  64213. // it will actually always be 0, but just in case
  64214. if (this.getScene().useRightHandedSystem) {
  64215. offset[2] *= -1;
  64216. }
  64217. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  64218. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  64219. }
  64220. else {
  64221. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  64222. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  64223. if (!this.getScene().useRightHandedSystem) {
  64224. [2, 6, 8, 9, 14].forEach(function (num) {
  64225. _this._webvrViewMatrix.m[num] *= -1;
  64226. });
  64227. }
  64228. // update the camera rotation matrix
  64229. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  64230. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  64231. // Computing target and final matrix
  64232. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  64233. }
  64234. var parentCamera = this._cameraRigParams["parentCamera"];
  64235. // should the view matrix be updated with scale and position offset?
  64236. if (parentCamera.deviceScaleFactor !== 1) {
  64237. this._webvrViewMatrix.invert();
  64238. // scale the position, if set
  64239. if (parentCamera.deviceScaleFactor) {
  64240. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  64241. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  64242. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  64243. }
  64244. this._webvrViewMatrix.invert();
  64245. }
  64246. return this._webvrViewMatrix;
  64247. };
  64248. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  64249. var _this = this;
  64250. if (this._cameraRigParams["specs"] === 1.0) {
  64251. var eyeParams = this._cameraRigParams["eyeParameters"];
  64252. // deprecated!!
  64253. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  64254. }
  64255. else {
  64256. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  64257. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  64258. //babylon compatible matrix
  64259. if (!this.getScene().useRightHandedSystem) {
  64260. [8, 9, 10, 11].forEach(function (num) {
  64261. _this._projectionMatrix.m[num] *= -1;
  64262. });
  64263. }
  64264. }
  64265. return this._projectionMatrix;
  64266. };
  64267. WebVRFreeCamera.prototype.initControllers = function () {
  64268. var _this = this;
  64269. this.controllers = [];
  64270. new BABYLON.Gamepads(function (gp) {
  64271. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  64272. var webVrController = gp;
  64273. if (_this.webVROptions.controllerMeshes) {
  64274. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  64275. if (_this.webVROptions.defaultLightningOnControllers) {
  64276. if (!_this._lightOnControllers) {
  64277. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  64278. }
  64279. loadedMesh.getChildren().forEach(function (mesh) {
  64280. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  64281. });
  64282. }
  64283. });
  64284. }
  64285. webVrController.attachToPoseControlledCamera(_this);
  64286. // since this is async - sanity check. Is the controller already stored?
  64287. if (_this.controllers.indexOf(webVrController) === -1) {
  64288. //add to the controllers array
  64289. _this.controllers.push(webVrController);
  64290. //did we find enough controllers? Great! let the developer know.
  64291. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  64292. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  64293. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  64294. // So we're overriding setting left & right manually to be sure
  64295. var firstViveWandDetected = false;
  64296. for (var i = 0; i < _this.controllers.length; i++) {
  64297. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  64298. if (!firstViveWandDetected) {
  64299. firstViveWandDetected = true;
  64300. _this.controllers[i].hand = "left";
  64301. }
  64302. else {
  64303. _this.controllers[i].hand = "right";
  64304. }
  64305. }
  64306. }
  64307. _this._onControllersAttached(_this.controllers);
  64308. }
  64309. }
  64310. }
  64311. else {
  64312. _this.nonVRControllers.push(gp);
  64313. if (_this._onNonVRControllerAttached) {
  64314. _this._onNonVRControllerAttached(gp);
  64315. }
  64316. }
  64317. });
  64318. };
  64319. return WebVRFreeCamera;
  64320. }(BABYLON.FreeCamera));
  64321. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  64322. })(BABYLON || (BABYLON = {}));
  64323. //# sourceMappingURL=babylon.webVRCamera.js.map
  64324. /// <reference path="babylon.freeCamera.ts" />
  64325. var BABYLON;
  64326. (function (BABYLON) {
  64327. // We're mainly based on the logic defined into the FreeCamera code
  64328. var DeviceOrientationCamera = (function (_super) {
  64329. __extends(DeviceOrientationCamera, _super);
  64330. function DeviceOrientationCamera(name, position, scene) {
  64331. var _this = _super.call(this, name, position, scene) || this;
  64332. _this._quaternionCache = new BABYLON.Quaternion();
  64333. _this.inputs.addDeviceOrientation();
  64334. return _this;
  64335. }
  64336. DeviceOrientationCamera.prototype.getClassName = function () {
  64337. return "DeviceOrientationCamera";
  64338. };
  64339. DeviceOrientationCamera.prototype._checkInputs = function () {
  64340. _super.prototype._checkInputs.call(this);
  64341. this._quaternionCache.copyFrom(this.rotationQuaternion);
  64342. if (this._initialQuaternion) {
  64343. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  64344. }
  64345. };
  64346. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  64347. var _this = this;
  64348. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  64349. //can only work if this camera has a rotation quaternion already.
  64350. if (!this.rotationQuaternion)
  64351. return;
  64352. if (!this._initialQuaternion) {
  64353. this._initialQuaternion = new BABYLON.Quaternion();
  64354. }
  64355. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  64356. ['x', 'y', 'z'].forEach(function (axisName) {
  64357. if (!axis[axisName]) {
  64358. _this._initialQuaternion[axisName] = 0;
  64359. }
  64360. else {
  64361. _this._initialQuaternion[axisName] *= -1;
  64362. }
  64363. });
  64364. this._initialQuaternion.normalize();
  64365. //force rotation update
  64366. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  64367. };
  64368. return DeviceOrientationCamera;
  64369. }(BABYLON.FreeCamera));
  64370. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  64371. })(BABYLON || (BABYLON = {}));
  64372. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  64373. var BABYLON;
  64374. (function (BABYLON) {
  64375. var VRDeviceOrientationFreeCamera = (function (_super) {
  64376. __extends(VRDeviceOrientationFreeCamera, _super);
  64377. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  64378. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64379. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64380. var _this = _super.call(this, name, position, scene) || this;
  64381. vrCameraMetrics.compensateDistortion = compensateDistortion;
  64382. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  64383. return _this;
  64384. }
  64385. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  64386. return "VRDeviceOrientationFreeCamera";
  64387. };
  64388. return VRDeviceOrientationFreeCamera;
  64389. }(BABYLON.DeviceOrientationCamera));
  64390. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  64391. var VRDeviceOrientationGamepadCamera = (function (_super) {
  64392. __extends(VRDeviceOrientationGamepadCamera, _super);
  64393. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  64394. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64395. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64396. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  64397. _this.inputs.addGamepad();
  64398. return _this;
  64399. }
  64400. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  64401. return "VRDeviceOrientationGamepadCamera";
  64402. };
  64403. return VRDeviceOrientationGamepadCamera;
  64404. }(VRDeviceOrientationFreeCamera));
  64405. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  64406. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  64407. __extends(VRDeviceOrientationArcRotateCamera, _super);
  64408. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  64409. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64410. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64411. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  64412. vrCameraMetrics.compensateDistortion = compensateDistortion;
  64413. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  64414. _this.inputs.addVRDeviceOrientation();
  64415. return _this;
  64416. }
  64417. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  64418. return "VRDeviceOrientationArcRotateCamera";
  64419. };
  64420. return VRDeviceOrientationArcRotateCamera;
  64421. }(BABYLON.ArcRotateCamera));
  64422. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  64423. })(BABYLON || (BABYLON = {}));
  64424. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  64425. /// <reference path="babylon.freeCamera.ts" />
  64426. /// <reference path="babylon.arcRotateCamera.ts" />
  64427. /// <reference path="babylon.gamepadCamera.ts" />
  64428. /// <reference path="babylon.universalCamera.ts" />
  64429. var BABYLON;
  64430. (function (BABYLON) {
  64431. var AnaglyphFreeCamera = (function (_super) {
  64432. __extends(AnaglyphFreeCamera, _super);
  64433. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  64434. var _this = _super.call(this, name, position, scene) || this;
  64435. _this.interaxialDistance = interaxialDistance;
  64436. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64437. return _this;
  64438. }
  64439. AnaglyphFreeCamera.prototype.getClassName = function () {
  64440. return "AnaglyphFreeCamera";
  64441. };
  64442. return AnaglyphFreeCamera;
  64443. }(BABYLON.FreeCamera));
  64444. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  64445. var AnaglyphArcRotateCamera = (function (_super) {
  64446. __extends(AnaglyphArcRotateCamera, _super);
  64447. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  64448. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  64449. _this.interaxialDistance = interaxialDistance;
  64450. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64451. return _this;
  64452. }
  64453. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  64454. return "AnaglyphArcRotateCamera";
  64455. };
  64456. return AnaglyphArcRotateCamera;
  64457. }(BABYLON.ArcRotateCamera));
  64458. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  64459. var AnaglyphGamepadCamera = (function (_super) {
  64460. __extends(AnaglyphGamepadCamera, _super);
  64461. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  64462. var _this = _super.call(this, name, position, scene) || this;
  64463. _this.interaxialDistance = interaxialDistance;
  64464. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64465. return _this;
  64466. }
  64467. AnaglyphGamepadCamera.prototype.getClassName = function () {
  64468. return "AnaglyphGamepadCamera";
  64469. };
  64470. return AnaglyphGamepadCamera;
  64471. }(BABYLON.GamepadCamera));
  64472. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  64473. var AnaglyphUniversalCamera = (function (_super) {
  64474. __extends(AnaglyphUniversalCamera, _super);
  64475. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  64476. var _this = _super.call(this, name, position, scene) || this;
  64477. _this.interaxialDistance = interaxialDistance;
  64478. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64479. return _this;
  64480. }
  64481. AnaglyphUniversalCamera.prototype.getClassName = function () {
  64482. return "AnaglyphUniversalCamera";
  64483. };
  64484. return AnaglyphUniversalCamera;
  64485. }(BABYLON.UniversalCamera));
  64486. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  64487. var StereoscopicFreeCamera = (function (_super) {
  64488. __extends(StereoscopicFreeCamera, _super);
  64489. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  64490. var _this = _super.call(this, name, position, scene) || this;
  64491. _this.interaxialDistance = interaxialDistance;
  64492. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  64493. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  64494. return _this;
  64495. }
  64496. StereoscopicFreeCamera.prototype.getClassName = function () {
  64497. return "StereoscopicFreeCamera";
  64498. };
  64499. return StereoscopicFreeCamera;
  64500. }(BABYLON.FreeCamera));
  64501. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  64502. var StereoscopicArcRotateCamera = (function (_super) {
  64503. __extends(StereoscopicArcRotateCamera, _super);
  64504. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  64505. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  64506. _this.interaxialDistance = interaxialDistance;
  64507. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  64508. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  64509. return _this;
  64510. }
  64511. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  64512. return "StereoscopicArcRotateCamera";
  64513. };
  64514. return StereoscopicArcRotateCamera;
  64515. }(BABYLON.ArcRotateCamera));
  64516. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  64517. var StereoscopicGamepadCamera = (function (_super) {
  64518. __extends(StereoscopicGamepadCamera, _super);
  64519. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  64520. var _this = _super.call(this, name, position, scene) || this;
  64521. _this.interaxialDistance = interaxialDistance;
  64522. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  64523. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  64524. return _this;
  64525. }
  64526. StereoscopicGamepadCamera.prototype.getClassName = function () {
  64527. return "StereoscopicGamepadCamera";
  64528. };
  64529. return StereoscopicGamepadCamera;
  64530. }(BABYLON.GamepadCamera));
  64531. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  64532. var StereoscopicUniversalCamera = (function (_super) {
  64533. __extends(StereoscopicUniversalCamera, _super);
  64534. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  64535. var _this = _super.call(this, name, position, scene) || this;
  64536. _this.interaxialDistance = interaxialDistance;
  64537. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  64538. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  64539. return _this;
  64540. }
  64541. StereoscopicUniversalCamera.prototype.getClassName = function () {
  64542. return "StereoscopicUniversalCamera";
  64543. };
  64544. return StereoscopicUniversalCamera;
  64545. }(BABYLON.UniversalCamera));
  64546. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  64547. })(BABYLON || (BABYLON = {}));
  64548. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  64549. // Mainly based on these 2 articles :
  64550. // 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
  64551. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  64552. var BABYLON;
  64553. (function (BABYLON) {
  64554. var JoystickAxis;
  64555. (function (JoystickAxis) {
  64556. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  64557. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  64558. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  64559. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  64560. var VirtualJoystick = (function () {
  64561. function VirtualJoystick(leftJoystick) {
  64562. var _this = this;
  64563. if (leftJoystick) {
  64564. this._leftJoystick = true;
  64565. }
  64566. else {
  64567. this._leftJoystick = false;
  64568. }
  64569. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  64570. VirtualJoystick._globalJoystickIndex++;
  64571. // By default left & right arrow keys are moving the X
  64572. // and up & down keys are moving the Y
  64573. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  64574. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  64575. this.reverseLeftRight = false;
  64576. this.reverseUpDown = false;
  64577. // collections of pointers
  64578. this._touches = new BABYLON.StringDictionary();
  64579. this.deltaPosition = BABYLON.Vector3.Zero();
  64580. this._joystickSensibility = 25;
  64581. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  64582. this._rotationSpeed = 25;
  64583. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  64584. this._rotateOnAxisRelativeToMesh = false;
  64585. this._onResize = function (evt) {
  64586. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  64587. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  64588. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  64589. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  64590. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  64591. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  64592. };
  64593. // injecting a canvas element on top of the canvas 3D game
  64594. if (!VirtualJoystick.vjCanvas) {
  64595. window.addEventListener("resize", this._onResize, false);
  64596. VirtualJoystick.vjCanvas = document.createElement("canvas");
  64597. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  64598. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  64599. VirtualJoystick.vjCanvas.width = window.innerWidth;
  64600. VirtualJoystick.vjCanvas.height = window.innerHeight;
  64601. VirtualJoystick.vjCanvas.style.width = "100%";
  64602. VirtualJoystick.vjCanvas.style.height = "100%";
  64603. VirtualJoystick.vjCanvas.style.position = "absolute";
  64604. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  64605. VirtualJoystick.vjCanvas.style.top = "0px";
  64606. VirtualJoystick.vjCanvas.style.left = "0px";
  64607. VirtualJoystick.vjCanvas.style.zIndex = "5";
  64608. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  64609. // Support for jQuery PEP polyfill
  64610. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  64611. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  64612. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  64613. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  64614. document.body.appendChild(VirtualJoystick.vjCanvas);
  64615. }
  64616. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  64617. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  64618. this.pressed = false;
  64619. // default joystick color
  64620. this._joystickColor = "cyan";
  64621. this._joystickPointerID = -1;
  64622. // current joystick position
  64623. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  64624. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  64625. // origin joystick position
  64626. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  64627. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  64628. this._onPointerDownHandlerRef = function (evt) {
  64629. _this._onPointerDown(evt);
  64630. };
  64631. this._onPointerMoveHandlerRef = function (evt) {
  64632. _this._onPointerMove(evt);
  64633. };
  64634. this._onPointerOutHandlerRef = function (evt) {
  64635. _this._onPointerUp(evt);
  64636. };
  64637. this._onPointerUpHandlerRef = function (evt) {
  64638. _this._onPointerUp(evt);
  64639. };
  64640. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  64641. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  64642. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  64643. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  64644. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  64645. evt.preventDefault(); // Disables system menu
  64646. }, false);
  64647. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64648. }
  64649. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  64650. this._joystickSensibility = newJoystickSensibility;
  64651. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  64652. };
  64653. VirtualJoystick.prototype._onPointerDown = function (e) {
  64654. var positionOnScreenCondition;
  64655. e.preventDefault();
  64656. if (this._leftJoystick === true) {
  64657. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  64658. }
  64659. else {
  64660. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  64661. }
  64662. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  64663. // First contact will be dedicated to the virtual joystick
  64664. this._joystickPointerID = e.pointerId;
  64665. this._joystickPointerStartPos.x = e.clientX;
  64666. this._joystickPointerStartPos.y = e.clientY;
  64667. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  64668. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  64669. this._deltaJoystickVector.x = 0;
  64670. this._deltaJoystickVector.y = 0;
  64671. this.pressed = true;
  64672. this._touches.add(e.pointerId.toString(), e);
  64673. }
  64674. else {
  64675. // You can only trigger the action buttons with a joystick declared
  64676. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  64677. this._action();
  64678. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  64679. }
  64680. }
  64681. };
  64682. VirtualJoystick.prototype._onPointerMove = function (e) {
  64683. // If the current pointer is the one associated to the joystick (first touch contact)
  64684. if (this._joystickPointerID == e.pointerId) {
  64685. this._joystickPointerPos.x = e.clientX;
  64686. this._joystickPointerPos.y = e.clientY;
  64687. this._deltaJoystickVector = this._joystickPointerPos.clone();
  64688. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  64689. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  64690. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  64691. switch (this._axisTargetedByLeftAndRight) {
  64692. case JoystickAxis.X:
  64693. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  64694. break;
  64695. case JoystickAxis.Y:
  64696. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  64697. break;
  64698. case JoystickAxis.Z:
  64699. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  64700. break;
  64701. }
  64702. var directionUpDown = this.reverseUpDown ? 1 : -1;
  64703. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  64704. switch (this._axisTargetedByUpAndDown) {
  64705. case JoystickAxis.X:
  64706. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  64707. break;
  64708. case JoystickAxis.Y:
  64709. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  64710. break;
  64711. case JoystickAxis.Z:
  64712. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  64713. break;
  64714. }
  64715. }
  64716. else {
  64717. var data = this._touches.get(e.pointerId.toString());
  64718. if (data) {
  64719. data.x = e.clientX;
  64720. data.y = e.clientY;
  64721. }
  64722. }
  64723. };
  64724. VirtualJoystick.prototype._onPointerUp = function (e) {
  64725. if (this._joystickPointerID == e.pointerId) {
  64726. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  64727. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  64728. this._joystickPointerID = -1;
  64729. this.pressed = false;
  64730. }
  64731. else {
  64732. var touch = this._touches.get(e.pointerId.toString());
  64733. if (touch) {
  64734. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  64735. }
  64736. }
  64737. this._deltaJoystickVector.x = 0;
  64738. this._deltaJoystickVector.y = 0;
  64739. this._touches.remove(e.pointerId.toString());
  64740. };
  64741. /**
  64742. * Change the color of the virtual joystick
  64743. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  64744. */
  64745. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  64746. this._joystickColor = newColor;
  64747. };
  64748. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  64749. this._action = action;
  64750. };
  64751. // Define which axis you'd like to control for left & right
  64752. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  64753. switch (axis) {
  64754. case JoystickAxis.X:
  64755. case JoystickAxis.Y:
  64756. case JoystickAxis.Z:
  64757. this._axisTargetedByLeftAndRight = axis;
  64758. break;
  64759. default:
  64760. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  64761. break;
  64762. }
  64763. };
  64764. // Define which axis you'd like to control for up & down
  64765. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  64766. switch (axis) {
  64767. case JoystickAxis.X:
  64768. case JoystickAxis.Y:
  64769. case JoystickAxis.Z:
  64770. this._axisTargetedByUpAndDown = axis;
  64771. break;
  64772. default:
  64773. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  64774. break;
  64775. }
  64776. };
  64777. VirtualJoystick.prototype._clearCanvas = function () {
  64778. if (this._leftJoystick) {
  64779. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  64780. }
  64781. else {
  64782. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  64783. }
  64784. };
  64785. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  64786. var _this = this;
  64787. if (this.pressed) {
  64788. this._touches.forEach(function (key, touch) {
  64789. if (touch.pointerId === _this._joystickPointerID) {
  64790. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  64791. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  64792. VirtualJoystick.vjCanvasContext.beginPath();
  64793. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  64794. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64795. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  64796. VirtualJoystick.vjCanvasContext.stroke();
  64797. VirtualJoystick.vjCanvasContext.closePath();
  64798. VirtualJoystick.vjCanvasContext.beginPath();
  64799. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64800. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  64801. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  64802. VirtualJoystick.vjCanvasContext.stroke();
  64803. VirtualJoystick.vjCanvasContext.closePath();
  64804. VirtualJoystick.vjCanvasContext.beginPath();
  64805. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  64806. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  64807. VirtualJoystick.vjCanvasContext.stroke();
  64808. VirtualJoystick.vjCanvasContext.closePath();
  64809. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  64810. }
  64811. else {
  64812. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  64813. VirtualJoystick.vjCanvasContext.beginPath();
  64814. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  64815. VirtualJoystick.vjCanvasContext.beginPath();
  64816. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  64817. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  64818. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  64819. VirtualJoystick.vjCanvasContext.stroke();
  64820. VirtualJoystick.vjCanvasContext.closePath();
  64821. touch.prevX = touch.x;
  64822. touch.prevY = touch.y;
  64823. }
  64824. ;
  64825. });
  64826. }
  64827. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  64828. };
  64829. VirtualJoystick.prototype.releaseCanvas = function () {
  64830. if (VirtualJoystick.vjCanvas) {
  64831. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  64832. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  64833. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  64834. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  64835. window.removeEventListener("resize", this._onResize);
  64836. document.body.removeChild(VirtualJoystick.vjCanvas);
  64837. VirtualJoystick.vjCanvas = null;
  64838. }
  64839. };
  64840. return VirtualJoystick;
  64841. }());
  64842. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  64843. VirtualJoystick._globalJoystickIndex = 0;
  64844. BABYLON.VirtualJoystick = VirtualJoystick;
  64845. })(BABYLON || (BABYLON = {}));
  64846. //# sourceMappingURL=babylon.virtualJoystick.js.map
  64847. var BABYLON;
  64848. (function (BABYLON) {
  64849. // We're mainly based on the logic defined into the FreeCamera code
  64850. var VirtualJoysticksCamera = (function (_super) {
  64851. __extends(VirtualJoysticksCamera, _super);
  64852. function VirtualJoysticksCamera(name, position, scene) {
  64853. var _this = _super.call(this, name, position, scene) || this;
  64854. _this.inputs.addVirtualJoystick();
  64855. return _this;
  64856. }
  64857. VirtualJoysticksCamera.prototype.getClassName = function () {
  64858. return "VirtualJoysticksCamera";
  64859. };
  64860. return VirtualJoysticksCamera;
  64861. }(BABYLON.FreeCamera));
  64862. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  64863. })(BABYLON || (BABYLON = {}));
  64864. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  64865. var BABYLON;
  64866. (function (BABYLON) {
  64867. var FreeCameraVirtualJoystickInput = (function () {
  64868. function FreeCameraVirtualJoystickInput() {
  64869. }
  64870. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  64871. return this._leftjoystick;
  64872. };
  64873. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  64874. return this._rightjoystick;
  64875. };
  64876. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  64877. if (this._leftjoystick) {
  64878. var camera = this.camera;
  64879. var speed = camera._computeLocalCameraSpeed() * 50;
  64880. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  64881. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  64882. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  64883. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  64884. if (!this._leftjoystick.pressed) {
  64885. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  64886. }
  64887. if (!this._rightjoystick.pressed) {
  64888. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  64889. }
  64890. }
  64891. };
  64892. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  64893. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  64894. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  64895. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  64896. this._leftjoystick.setJoystickSensibility(0.15);
  64897. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  64898. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  64899. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  64900. this._rightjoystick.reverseUpDown = true;
  64901. this._rightjoystick.setJoystickSensibility(0.05);
  64902. this._rightjoystick.setJoystickColor("yellow");
  64903. };
  64904. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  64905. this._leftjoystick.releaseCanvas();
  64906. this._rightjoystick.releaseCanvas();
  64907. };
  64908. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  64909. return "FreeCameraVirtualJoystickInput";
  64910. };
  64911. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  64912. return "virtualJoystick";
  64913. };
  64914. return FreeCameraVirtualJoystickInput;
  64915. }());
  64916. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  64917. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  64918. })(BABYLON || (BABYLON = {}));
  64919. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  64920. var BABYLON;
  64921. (function (BABYLON) {
  64922. var SimplificationSettings = (function () {
  64923. function SimplificationSettings(quality, distance, optimizeMesh) {
  64924. this.quality = quality;
  64925. this.distance = distance;
  64926. this.optimizeMesh = optimizeMesh;
  64927. }
  64928. return SimplificationSettings;
  64929. }());
  64930. BABYLON.SimplificationSettings = SimplificationSettings;
  64931. var SimplificationQueue = (function () {
  64932. function SimplificationQueue() {
  64933. this.running = false;
  64934. this._simplificationArray = [];
  64935. }
  64936. SimplificationQueue.prototype.addTask = function (task) {
  64937. this._simplificationArray.push(task);
  64938. };
  64939. SimplificationQueue.prototype.executeNext = function () {
  64940. var task = this._simplificationArray.pop();
  64941. if (task) {
  64942. this.running = true;
  64943. this.runSimplification(task);
  64944. }
  64945. else {
  64946. this.running = false;
  64947. }
  64948. };
  64949. SimplificationQueue.prototype.runSimplification = function (task) {
  64950. var _this = this;
  64951. if (task.parallelProcessing) {
  64952. //parallel simplifier
  64953. task.settings.forEach(function (setting) {
  64954. var simplifier = _this.getSimplifier(task);
  64955. simplifier.simplify(setting, function (newMesh) {
  64956. task.mesh.addLODLevel(setting.distance, newMesh);
  64957. newMesh.isVisible = true;
  64958. //check if it is the last
  64959. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  64960. //all done, run the success callback.
  64961. task.successCallback();
  64962. }
  64963. _this.executeNext();
  64964. });
  64965. });
  64966. }
  64967. else {
  64968. //single simplifier.
  64969. var simplifier = this.getSimplifier(task);
  64970. var runDecimation = function (setting, callback) {
  64971. simplifier.simplify(setting, function (newMesh) {
  64972. task.mesh.addLODLevel(setting.distance, newMesh);
  64973. newMesh.isVisible = true;
  64974. //run the next quality level
  64975. callback();
  64976. });
  64977. };
  64978. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  64979. runDecimation(task.settings[loop.index], function () {
  64980. loop.executeNext();
  64981. });
  64982. }, function () {
  64983. //execution ended, run the success callback.
  64984. if (task.successCallback) {
  64985. task.successCallback();
  64986. }
  64987. _this.executeNext();
  64988. });
  64989. }
  64990. };
  64991. SimplificationQueue.prototype.getSimplifier = function (task) {
  64992. switch (task.simplificationType) {
  64993. case SimplificationType.QUADRATIC:
  64994. default:
  64995. return new QuadraticErrorSimplification(task.mesh);
  64996. }
  64997. };
  64998. return SimplificationQueue;
  64999. }());
  65000. BABYLON.SimplificationQueue = SimplificationQueue;
  65001. /**
  65002. * The implemented types of simplification.
  65003. * At the moment only Quadratic Error Decimation is implemented.
  65004. */
  65005. var SimplificationType;
  65006. (function (SimplificationType) {
  65007. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  65008. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  65009. var DecimationTriangle = (function () {
  65010. function DecimationTriangle(vertices) {
  65011. this.vertices = vertices;
  65012. this.error = new Array(4);
  65013. this.deleted = false;
  65014. this.isDirty = false;
  65015. this.deletePending = false;
  65016. this.borderFactor = 0;
  65017. }
  65018. return DecimationTriangle;
  65019. }());
  65020. BABYLON.DecimationTriangle = DecimationTriangle;
  65021. var DecimationVertex = (function () {
  65022. function DecimationVertex(position, id) {
  65023. this.position = position;
  65024. this.id = id;
  65025. this.isBorder = true;
  65026. this.q = new QuadraticMatrix();
  65027. this.triangleCount = 0;
  65028. this.triangleStart = 0;
  65029. this.originalOffsets = [];
  65030. }
  65031. DecimationVertex.prototype.updatePosition = function (newPosition) {
  65032. this.position.copyFrom(newPosition);
  65033. };
  65034. return DecimationVertex;
  65035. }());
  65036. BABYLON.DecimationVertex = DecimationVertex;
  65037. var QuadraticMatrix = (function () {
  65038. function QuadraticMatrix(data) {
  65039. this.data = new Array(10);
  65040. for (var i = 0; i < 10; ++i) {
  65041. if (data && data[i]) {
  65042. this.data[i] = data[i];
  65043. }
  65044. else {
  65045. this.data[i] = 0;
  65046. }
  65047. }
  65048. }
  65049. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  65050. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  65051. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  65052. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  65053. return det;
  65054. };
  65055. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  65056. for (var i = 0; i < 10; ++i) {
  65057. this.data[i] += matrix.data[i];
  65058. }
  65059. };
  65060. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  65061. for (var i = 0; i < 10; ++i) {
  65062. this.data[i] += data[i];
  65063. }
  65064. };
  65065. QuadraticMatrix.prototype.add = function (matrix) {
  65066. var m = new QuadraticMatrix();
  65067. for (var i = 0; i < 10; ++i) {
  65068. m.data[i] = this.data[i] + matrix.data[i];
  65069. }
  65070. return m;
  65071. };
  65072. QuadraticMatrix.FromData = function (a, b, c, d) {
  65073. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  65074. };
  65075. //returning an array to avoid garbage collection
  65076. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  65077. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  65078. };
  65079. return QuadraticMatrix;
  65080. }());
  65081. BABYLON.QuadraticMatrix = QuadraticMatrix;
  65082. var Reference = (function () {
  65083. function Reference(vertexId, triangleId) {
  65084. this.vertexId = vertexId;
  65085. this.triangleId = triangleId;
  65086. }
  65087. return Reference;
  65088. }());
  65089. BABYLON.Reference = Reference;
  65090. /**
  65091. * An implementation of the Quadratic Error simplification algorithm.
  65092. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  65093. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  65094. * @author RaananW
  65095. */
  65096. var QuadraticErrorSimplification = (function () {
  65097. function QuadraticErrorSimplification(_mesh) {
  65098. this._mesh = _mesh;
  65099. this.initialized = false;
  65100. this.syncIterations = 5000;
  65101. this.aggressiveness = 7;
  65102. this.decimationIterations = 100;
  65103. this.boundingBoxEpsilon = BABYLON.Epsilon;
  65104. }
  65105. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  65106. var _this = this;
  65107. this.initDecimatedMesh();
  65108. //iterating through the submeshes array, one after the other.
  65109. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  65110. _this.initWithMesh(loop.index, function () {
  65111. _this.runDecimation(settings, loop.index, function () {
  65112. loop.executeNext();
  65113. });
  65114. }, settings.optimizeMesh);
  65115. }, function () {
  65116. setTimeout(function () {
  65117. successCallback(_this._reconstructedMesh);
  65118. }, 0);
  65119. });
  65120. };
  65121. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  65122. var _this = this;
  65123. var gCount = 0;
  65124. triangle.vertices.forEach(function (vertex) {
  65125. var count = 0;
  65126. var vPos = vertex.position;
  65127. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  65128. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  65129. ++count;
  65130. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  65131. ++count;
  65132. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  65133. ++count;
  65134. if (count > 1) {
  65135. ++gCount;
  65136. }
  65137. ;
  65138. });
  65139. if (gCount > 1) {
  65140. console.log(triangle, gCount);
  65141. }
  65142. return gCount > 1;
  65143. };
  65144. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  65145. var _this = this;
  65146. var targetCount = ~~(this.triangles.length * settings.quality);
  65147. var deletedTriangles = 0;
  65148. var triangleCount = this.triangles.length;
  65149. var iterationFunction = function (iteration, callback) {
  65150. setTimeout(function () {
  65151. if (iteration % 5 === 0) {
  65152. _this.updateMesh(iteration === 0);
  65153. }
  65154. for (var i = 0; i < _this.triangles.length; ++i) {
  65155. _this.triangles[i].isDirty = false;
  65156. }
  65157. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  65158. var trianglesIterator = function (i) {
  65159. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  65160. var t = _this.triangles[tIdx];
  65161. if (!t)
  65162. return;
  65163. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  65164. return;
  65165. }
  65166. for (var j = 0; j < 3; ++j) {
  65167. if (t.error[j] < threshold) {
  65168. var deleted0 = [];
  65169. var deleted1 = [];
  65170. var v0 = t.vertices[j];
  65171. var v1 = t.vertices[(j + 1) % 3];
  65172. if (v0.isBorder || v1.isBorder)
  65173. continue;
  65174. var p = BABYLON.Vector3.Zero();
  65175. var n = BABYLON.Vector3.Zero();
  65176. var uv = BABYLON.Vector2.Zero();
  65177. var color = new BABYLON.Color4(0, 0, 0, 1);
  65178. _this.calculateError(v0, v1, p, n, uv, color);
  65179. var delTr = [];
  65180. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  65181. continue;
  65182. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  65183. continue;
  65184. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  65185. continue;
  65186. var uniqueArray = [];
  65187. delTr.forEach(function (deletedT) {
  65188. if (uniqueArray.indexOf(deletedT) === -1) {
  65189. deletedT.deletePending = true;
  65190. uniqueArray.push(deletedT);
  65191. }
  65192. });
  65193. if (uniqueArray.length % 2 !== 0) {
  65194. continue;
  65195. }
  65196. v0.q = v1.q.add(v0.q);
  65197. v0.updatePosition(p);
  65198. var tStart = _this.references.length;
  65199. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  65200. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  65201. var tCount = _this.references.length - tStart;
  65202. if (tCount <= v0.triangleCount) {
  65203. if (tCount) {
  65204. for (var c = 0; c < tCount; c++) {
  65205. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  65206. }
  65207. }
  65208. }
  65209. else {
  65210. v0.triangleStart = tStart;
  65211. }
  65212. v0.triangleCount = tCount;
  65213. break;
  65214. }
  65215. }
  65216. };
  65217. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  65218. }, 0);
  65219. };
  65220. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  65221. if (triangleCount - deletedTriangles <= targetCount)
  65222. loop.breakLoop();
  65223. else {
  65224. iterationFunction(loop.index, function () {
  65225. loop.executeNext();
  65226. });
  65227. }
  65228. }, function () {
  65229. setTimeout(function () {
  65230. //reconstruct this part of the mesh
  65231. _this.reconstructMesh(submeshIndex);
  65232. successCallback();
  65233. }, 0);
  65234. });
  65235. };
  65236. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  65237. var _this = this;
  65238. this.vertices = [];
  65239. this.triangles = [];
  65240. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65241. var indices = this._mesh.getIndices();
  65242. var submesh = this._mesh.subMeshes[submeshIndex];
  65243. var findInVertices = function (positionToSearch) {
  65244. if (optimizeMesh) {
  65245. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  65246. if (_this.vertices[ii].position.equals(positionToSearch)) {
  65247. return _this.vertices[ii];
  65248. }
  65249. }
  65250. }
  65251. return null;
  65252. };
  65253. var vertexReferences = [];
  65254. var vertexInit = function (i) {
  65255. var offset = i + submesh.verticesStart;
  65256. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  65257. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  65258. vertex.originalOffsets.push(offset);
  65259. if (vertex.id === _this.vertices.length) {
  65260. _this.vertices.push(vertex);
  65261. }
  65262. vertexReferences.push(vertex.id);
  65263. };
  65264. //var totalVertices = mesh.getTotalVertices();
  65265. var totalVertices = submesh.verticesCount;
  65266. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  65267. var indicesInit = function (i) {
  65268. var offset = (submesh.indexStart / 3) + i;
  65269. var pos = (offset * 3);
  65270. var i0 = indices[pos + 0];
  65271. var i1 = indices[pos + 1];
  65272. var i2 = indices[pos + 2];
  65273. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  65274. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  65275. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  65276. var triangle = new DecimationTriangle([v0, v1, v2]);
  65277. triangle.originalOffset = pos;
  65278. _this.triangles.push(triangle);
  65279. };
  65280. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  65281. _this.init(callback);
  65282. });
  65283. });
  65284. };
  65285. QuadraticErrorSimplification.prototype.init = function (callback) {
  65286. var _this = this;
  65287. var triangleInit1 = function (i) {
  65288. var t = _this.triangles[i];
  65289. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  65290. for (var j = 0; j < 3; j++) {
  65291. 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))));
  65292. }
  65293. };
  65294. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  65295. var triangleInit2 = function (i) {
  65296. var t = _this.triangles[i];
  65297. for (var j = 0; j < 3; ++j) {
  65298. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  65299. }
  65300. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  65301. };
  65302. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  65303. _this.initialized = true;
  65304. callback();
  65305. });
  65306. });
  65307. };
  65308. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  65309. var newTriangles = [];
  65310. var i;
  65311. for (i = 0; i < this.vertices.length; ++i) {
  65312. this.vertices[i].triangleCount = 0;
  65313. }
  65314. var t;
  65315. var j;
  65316. for (i = 0; i < this.triangles.length; ++i) {
  65317. if (!this.triangles[i].deleted) {
  65318. t = this.triangles[i];
  65319. for (j = 0; j < 3; ++j) {
  65320. t.vertices[j].triangleCount = 1;
  65321. }
  65322. newTriangles.push(t);
  65323. }
  65324. }
  65325. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  65326. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  65327. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  65328. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  65329. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65330. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65331. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65332. var vertexCount = 0;
  65333. for (i = 0; i < this.vertices.length; ++i) {
  65334. var vertex = this.vertices[i];
  65335. vertex.id = vertexCount;
  65336. if (vertex.triangleCount) {
  65337. vertex.originalOffsets.forEach(function (originalOffset) {
  65338. newPositionData.push(vertex.position.x);
  65339. newPositionData.push(vertex.position.y);
  65340. newPositionData.push(vertex.position.z);
  65341. newNormalData.push(normalData[originalOffset * 3]);
  65342. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  65343. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  65344. if (uvs && uvs.length) {
  65345. newUVsData.push(uvs[(originalOffset * 2)]);
  65346. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  65347. }
  65348. else if (colorsData && colorsData.length) {
  65349. newColorsData.push(colorsData[(originalOffset * 4)]);
  65350. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  65351. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  65352. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  65353. }
  65354. ++vertexCount;
  65355. });
  65356. }
  65357. }
  65358. var startingIndex = this._reconstructedMesh.getTotalIndices();
  65359. var startingVertex = this._reconstructedMesh.getTotalVertices();
  65360. var submeshesArray = this._reconstructedMesh.subMeshes;
  65361. this._reconstructedMesh.subMeshes = [];
  65362. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  65363. var originalIndices = this._mesh.getIndices();
  65364. for (i = 0; i < newTriangles.length; ++i) {
  65365. t = newTriangles[i]; //now get the new referencing point for each vertex
  65366. [0, 1, 2].forEach(function (idx) {
  65367. var id = originalIndices[t.originalOffset + idx];
  65368. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  65369. if (offset < 0)
  65370. offset = 0;
  65371. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  65372. });
  65373. }
  65374. //overwriting the old vertex buffers and indices.
  65375. this._reconstructedMesh.setIndices(newIndicesArray);
  65376. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  65377. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  65378. if (newUVsData.length > 0)
  65379. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  65380. if (newColorsData.length > 0)
  65381. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  65382. //create submesh
  65383. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  65384. if (submeshIndex > 0) {
  65385. this._reconstructedMesh.subMeshes = [];
  65386. submeshesArray.forEach(function (submesh) {
  65387. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  65388. });
  65389. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  65390. }
  65391. };
  65392. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  65393. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  65394. this._reconstructedMesh.material = this._mesh.material;
  65395. this._reconstructedMesh.parent = this._mesh.parent;
  65396. this._reconstructedMesh.isVisible = false;
  65397. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  65398. };
  65399. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  65400. for (var i = 0; i < vertex1.triangleCount; ++i) {
  65401. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  65402. if (t.deleted)
  65403. continue;
  65404. var s = this.references[vertex1.triangleStart + i].vertexId;
  65405. var v1 = t.vertices[(s + 1) % 3];
  65406. var v2 = t.vertices[(s + 2) % 3];
  65407. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  65408. deletedArray[i] = true;
  65409. delTr.push(t);
  65410. continue;
  65411. }
  65412. var d1 = v1.position.subtract(point);
  65413. d1 = d1.normalize();
  65414. var d2 = v2.position.subtract(point);
  65415. d2 = d2.normalize();
  65416. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  65417. return true;
  65418. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  65419. deletedArray[i] = false;
  65420. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  65421. return true;
  65422. }
  65423. return false;
  65424. };
  65425. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  65426. var newDeleted = deletedTriangles;
  65427. for (var i = 0; i < vertex.triangleCount; ++i) {
  65428. var ref = this.references[vertex.triangleStart + i];
  65429. var t = this.triangles[ref.triangleId];
  65430. if (t.deleted)
  65431. continue;
  65432. if (deletedArray[i] && t.deletePending) {
  65433. t.deleted = true;
  65434. newDeleted++;
  65435. continue;
  65436. }
  65437. t.vertices[ref.vertexId] = origVertex;
  65438. t.isDirty = true;
  65439. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  65440. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  65441. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  65442. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  65443. this.references.push(ref);
  65444. }
  65445. return newDeleted;
  65446. };
  65447. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  65448. for (var i = 0; i < this.vertices.length; ++i) {
  65449. var vCount = [];
  65450. var vId = [];
  65451. var v = this.vertices[i];
  65452. var j;
  65453. for (j = 0; j < v.triangleCount; ++j) {
  65454. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  65455. for (var ii = 0; ii < 3; ii++) {
  65456. var ofs = 0;
  65457. var vv = triangle.vertices[ii];
  65458. while (ofs < vCount.length) {
  65459. if (vId[ofs] === vv.id)
  65460. break;
  65461. ++ofs;
  65462. }
  65463. if (ofs === vCount.length) {
  65464. vCount.push(1);
  65465. vId.push(vv.id);
  65466. }
  65467. else {
  65468. vCount[ofs]++;
  65469. }
  65470. }
  65471. }
  65472. for (j = 0; j < vCount.length; ++j) {
  65473. if (vCount[j] === 1) {
  65474. this.vertices[vId[j]].isBorder = true;
  65475. }
  65476. else {
  65477. this.vertices[vId[j]].isBorder = false;
  65478. }
  65479. }
  65480. }
  65481. };
  65482. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  65483. if (identifyBorders === void 0) { identifyBorders = false; }
  65484. var i;
  65485. if (!identifyBorders) {
  65486. var newTrianglesVector = [];
  65487. for (i = 0; i < this.triangles.length; ++i) {
  65488. if (!this.triangles[i].deleted) {
  65489. newTrianglesVector.push(this.triangles[i]);
  65490. }
  65491. }
  65492. this.triangles = newTrianglesVector;
  65493. }
  65494. for (i = 0; i < this.vertices.length; ++i) {
  65495. this.vertices[i].triangleCount = 0;
  65496. this.vertices[i].triangleStart = 0;
  65497. }
  65498. var t;
  65499. var j;
  65500. var v;
  65501. for (i = 0; i < this.triangles.length; ++i) {
  65502. t = this.triangles[i];
  65503. for (j = 0; j < 3; ++j) {
  65504. v = t.vertices[j];
  65505. v.triangleCount++;
  65506. }
  65507. }
  65508. var tStart = 0;
  65509. for (i = 0; i < this.vertices.length; ++i) {
  65510. this.vertices[i].triangleStart = tStart;
  65511. tStart += this.vertices[i].triangleCount;
  65512. this.vertices[i].triangleCount = 0;
  65513. }
  65514. var newReferences = new Array(this.triangles.length * 3);
  65515. for (i = 0; i < this.triangles.length; ++i) {
  65516. t = this.triangles[i];
  65517. for (j = 0; j < 3; ++j) {
  65518. v = t.vertices[j];
  65519. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  65520. v.triangleCount++;
  65521. }
  65522. }
  65523. this.references = newReferences;
  65524. if (identifyBorders) {
  65525. this.identifyBorder();
  65526. }
  65527. };
  65528. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  65529. var x = point.x;
  65530. var y = point.y;
  65531. var z = point.z;
  65532. 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
  65533. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  65534. };
  65535. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  65536. var q = vertex1.q.add(vertex2.q);
  65537. var border = vertex1.isBorder && vertex2.isBorder;
  65538. var error = 0;
  65539. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  65540. if (qDet !== 0 && !border) {
  65541. if (!pointResult) {
  65542. pointResult = BABYLON.Vector3.Zero();
  65543. }
  65544. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  65545. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  65546. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  65547. error = this.vertexError(q, pointResult);
  65548. }
  65549. else {
  65550. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  65551. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  65552. var error1 = this.vertexError(q, vertex1.position);
  65553. var error2 = this.vertexError(q, vertex2.position);
  65554. var error3 = this.vertexError(q, p3);
  65555. error = Math.min(error1, error2, error3);
  65556. if (error === error1) {
  65557. if (pointResult) {
  65558. pointResult.copyFrom(vertex1.position);
  65559. }
  65560. }
  65561. else if (error === error2) {
  65562. if (pointResult) {
  65563. pointResult.copyFrom(vertex2.position);
  65564. }
  65565. }
  65566. else {
  65567. if (pointResult) {
  65568. pointResult.copyFrom(p3);
  65569. }
  65570. }
  65571. }
  65572. return error;
  65573. };
  65574. return QuadraticErrorSimplification;
  65575. }());
  65576. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  65577. })(BABYLON || (BABYLON = {}));
  65578. //# sourceMappingURL=babylon.meshSimplification.js.map
  65579. var BABYLON;
  65580. (function (BABYLON) {
  65581. var Internals;
  65582. (function (Internals) {
  65583. var MeshLODLevel = (function () {
  65584. function MeshLODLevel(distance, mesh) {
  65585. this.distance = distance;
  65586. this.mesh = mesh;
  65587. }
  65588. return MeshLODLevel;
  65589. }());
  65590. Internals.MeshLODLevel = MeshLODLevel;
  65591. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65592. })(BABYLON || (BABYLON = {}));
  65593. //# sourceMappingURL=babylon.meshLODLevel.js.map
  65594. var BABYLON;
  65595. (function (BABYLON) {
  65596. // Standard optimizations
  65597. var SceneOptimization = (function () {
  65598. function SceneOptimization(priority) {
  65599. if (priority === void 0) { priority = 0; }
  65600. this.priority = priority;
  65601. this.apply = function (scene) {
  65602. return true; // Return true if everything that can be done was applied
  65603. };
  65604. }
  65605. return SceneOptimization;
  65606. }());
  65607. BABYLON.SceneOptimization = SceneOptimization;
  65608. var TextureOptimization = (function (_super) {
  65609. __extends(TextureOptimization, _super);
  65610. function TextureOptimization(priority, maximumSize) {
  65611. if (priority === void 0) { priority = 0; }
  65612. if (maximumSize === void 0) { maximumSize = 1024; }
  65613. var _this = _super.call(this, priority) || this;
  65614. _this.priority = priority;
  65615. _this.maximumSize = maximumSize;
  65616. _this.apply = function (scene) {
  65617. var allDone = true;
  65618. for (var index = 0; index < scene.textures.length; index++) {
  65619. var texture = scene.textures[index];
  65620. if (!texture.canRescale || texture.getContext) {
  65621. continue;
  65622. }
  65623. var currentSize = texture.getSize();
  65624. var maxDimension = Math.max(currentSize.width, currentSize.height);
  65625. if (maxDimension > _this.maximumSize) {
  65626. texture.scale(0.5);
  65627. allDone = false;
  65628. }
  65629. }
  65630. return allDone;
  65631. };
  65632. return _this;
  65633. }
  65634. return TextureOptimization;
  65635. }(SceneOptimization));
  65636. BABYLON.TextureOptimization = TextureOptimization;
  65637. var HardwareScalingOptimization = (function (_super) {
  65638. __extends(HardwareScalingOptimization, _super);
  65639. function HardwareScalingOptimization(priority, maximumScale) {
  65640. if (priority === void 0) { priority = 0; }
  65641. if (maximumScale === void 0) { maximumScale = 2; }
  65642. var _this = _super.call(this, priority) || this;
  65643. _this.priority = priority;
  65644. _this.maximumScale = maximumScale;
  65645. _this._currentScale = 1;
  65646. _this.apply = function (scene) {
  65647. _this._currentScale++;
  65648. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  65649. return _this._currentScale >= _this.maximumScale;
  65650. };
  65651. return _this;
  65652. }
  65653. return HardwareScalingOptimization;
  65654. }(SceneOptimization));
  65655. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  65656. var ShadowsOptimization = (function (_super) {
  65657. __extends(ShadowsOptimization, _super);
  65658. function ShadowsOptimization() {
  65659. var _this = _super !== null && _super.apply(this, arguments) || this;
  65660. _this.apply = function (scene) {
  65661. scene.shadowsEnabled = false;
  65662. return true;
  65663. };
  65664. return _this;
  65665. }
  65666. return ShadowsOptimization;
  65667. }(SceneOptimization));
  65668. BABYLON.ShadowsOptimization = ShadowsOptimization;
  65669. var PostProcessesOptimization = (function (_super) {
  65670. __extends(PostProcessesOptimization, _super);
  65671. function PostProcessesOptimization() {
  65672. var _this = _super !== null && _super.apply(this, arguments) || this;
  65673. _this.apply = function (scene) {
  65674. scene.postProcessesEnabled = false;
  65675. return true;
  65676. };
  65677. return _this;
  65678. }
  65679. return PostProcessesOptimization;
  65680. }(SceneOptimization));
  65681. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  65682. var LensFlaresOptimization = (function (_super) {
  65683. __extends(LensFlaresOptimization, _super);
  65684. function LensFlaresOptimization() {
  65685. var _this = _super !== null && _super.apply(this, arguments) || this;
  65686. _this.apply = function (scene) {
  65687. scene.lensFlaresEnabled = false;
  65688. return true;
  65689. };
  65690. return _this;
  65691. }
  65692. return LensFlaresOptimization;
  65693. }(SceneOptimization));
  65694. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  65695. var ParticlesOptimization = (function (_super) {
  65696. __extends(ParticlesOptimization, _super);
  65697. function ParticlesOptimization() {
  65698. var _this = _super !== null && _super.apply(this, arguments) || this;
  65699. _this.apply = function (scene) {
  65700. scene.particlesEnabled = false;
  65701. return true;
  65702. };
  65703. return _this;
  65704. }
  65705. return ParticlesOptimization;
  65706. }(SceneOptimization));
  65707. BABYLON.ParticlesOptimization = ParticlesOptimization;
  65708. var RenderTargetsOptimization = (function (_super) {
  65709. __extends(RenderTargetsOptimization, _super);
  65710. function RenderTargetsOptimization() {
  65711. var _this = _super !== null && _super.apply(this, arguments) || this;
  65712. _this.apply = function (scene) {
  65713. scene.renderTargetsEnabled = false;
  65714. return true;
  65715. };
  65716. return _this;
  65717. }
  65718. return RenderTargetsOptimization;
  65719. }(SceneOptimization));
  65720. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  65721. var MergeMeshesOptimization = (function (_super) {
  65722. __extends(MergeMeshesOptimization, _super);
  65723. function MergeMeshesOptimization() {
  65724. var _this = _super !== null && _super.apply(this, arguments) || this;
  65725. _this._canBeMerged = function (abstractMesh) {
  65726. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  65727. return false;
  65728. }
  65729. var mesh = abstractMesh;
  65730. if (!mesh.isVisible || !mesh.isEnabled()) {
  65731. return false;
  65732. }
  65733. if (mesh.instances.length > 0) {
  65734. return false;
  65735. }
  65736. if (mesh.skeleton || mesh.hasLODLevels) {
  65737. return false;
  65738. }
  65739. if (mesh.parent) {
  65740. return false;
  65741. }
  65742. return true;
  65743. };
  65744. _this.apply = function (scene, updateSelectionTree) {
  65745. var globalPool = scene.meshes.slice(0);
  65746. var globalLength = globalPool.length;
  65747. for (var index = 0; index < globalLength; index++) {
  65748. var currentPool = new Array();
  65749. var current = globalPool[index];
  65750. // Checks
  65751. if (!_this._canBeMerged(current)) {
  65752. continue;
  65753. }
  65754. currentPool.push(current);
  65755. // Find compatible meshes
  65756. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  65757. var otherMesh = globalPool[subIndex];
  65758. if (!_this._canBeMerged(otherMesh)) {
  65759. continue;
  65760. }
  65761. if (otherMesh.material !== current.material) {
  65762. continue;
  65763. }
  65764. if (otherMesh.checkCollisions !== current.checkCollisions) {
  65765. continue;
  65766. }
  65767. currentPool.push(otherMesh);
  65768. globalLength--;
  65769. globalPool.splice(subIndex, 1);
  65770. subIndex--;
  65771. }
  65772. if (currentPool.length < 2) {
  65773. continue;
  65774. }
  65775. // Merge meshes
  65776. BABYLON.Mesh.MergeMeshes(currentPool);
  65777. }
  65778. if (updateSelectionTree != undefined) {
  65779. if (updateSelectionTree) {
  65780. scene.createOrUpdateSelectionOctree();
  65781. }
  65782. }
  65783. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  65784. scene.createOrUpdateSelectionOctree();
  65785. }
  65786. return true;
  65787. };
  65788. return _this;
  65789. }
  65790. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  65791. get: function () {
  65792. return MergeMeshesOptimization._UpdateSelectionTree;
  65793. },
  65794. set: function (value) {
  65795. MergeMeshesOptimization._UpdateSelectionTree = value;
  65796. },
  65797. enumerable: true,
  65798. configurable: true
  65799. });
  65800. return MergeMeshesOptimization;
  65801. }(SceneOptimization));
  65802. MergeMeshesOptimization._UpdateSelectionTree = false;
  65803. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  65804. // Options
  65805. var SceneOptimizerOptions = (function () {
  65806. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  65807. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  65808. if (trackerDuration === void 0) { trackerDuration = 2000; }
  65809. this.targetFrameRate = targetFrameRate;
  65810. this.trackerDuration = trackerDuration;
  65811. this.optimizations = new Array();
  65812. }
  65813. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  65814. var result = new SceneOptimizerOptions(targetFrameRate);
  65815. var priority = 0;
  65816. result.optimizations.push(new MergeMeshesOptimization(priority));
  65817. result.optimizations.push(new ShadowsOptimization(priority));
  65818. result.optimizations.push(new LensFlaresOptimization(priority));
  65819. // Next priority
  65820. priority++;
  65821. result.optimizations.push(new PostProcessesOptimization(priority));
  65822. result.optimizations.push(new ParticlesOptimization(priority));
  65823. // Next priority
  65824. priority++;
  65825. result.optimizations.push(new TextureOptimization(priority, 1024));
  65826. return result;
  65827. };
  65828. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  65829. var result = new SceneOptimizerOptions(targetFrameRate);
  65830. var priority = 0;
  65831. result.optimizations.push(new MergeMeshesOptimization(priority));
  65832. result.optimizations.push(new ShadowsOptimization(priority));
  65833. result.optimizations.push(new LensFlaresOptimization(priority));
  65834. // Next priority
  65835. priority++;
  65836. result.optimizations.push(new PostProcessesOptimization(priority));
  65837. result.optimizations.push(new ParticlesOptimization(priority));
  65838. // Next priority
  65839. priority++;
  65840. result.optimizations.push(new TextureOptimization(priority, 512));
  65841. // Next priority
  65842. priority++;
  65843. result.optimizations.push(new RenderTargetsOptimization(priority));
  65844. // Next priority
  65845. priority++;
  65846. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  65847. return result;
  65848. };
  65849. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  65850. var result = new SceneOptimizerOptions(targetFrameRate);
  65851. var priority = 0;
  65852. result.optimizations.push(new MergeMeshesOptimization(priority));
  65853. result.optimizations.push(new ShadowsOptimization(priority));
  65854. result.optimizations.push(new LensFlaresOptimization(priority));
  65855. // Next priority
  65856. priority++;
  65857. result.optimizations.push(new PostProcessesOptimization(priority));
  65858. result.optimizations.push(new ParticlesOptimization(priority));
  65859. // Next priority
  65860. priority++;
  65861. result.optimizations.push(new TextureOptimization(priority, 256));
  65862. // Next priority
  65863. priority++;
  65864. result.optimizations.push(new RenderTargetsOptimization(priority));
  65865. // Next priority
  65866. priority++;
  65867. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  65868. return result;
  65869. };
  65870. return SceneOptimizerOptions;
  65871. }());
  65872. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  65873. // Scene optimizer tool
  65874. var SceneOptimizer = (function () {
  65875. function SceneOptimizer() {
  65876. }
  65877. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  65878. // TODO: add an epsilon
  65879. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  65880. if (onSuccess) {
  65881. onSuccess();
  65882. }
  65883. return;
  65884. }
  65885. // Apply current level of optimizations
  65886. var allDone = true;
  65887. var noOptimizationApplied = true;
  65888. for (var index = 0; index < options.optimizations.length; index++) {
  65889. var optimization = options.optimizations[index];
  65890. if (optimization.priority === currentPriorityLevel) {
  65891. noOptimizationApplied = false;
  65892. allDone = allDone && optimization.apply(scene);
  65893. }
  65894. }
  65895. // If no optimization was applied, this is a failure :(
  65896. if (noOptimizationApplied) {
  65897. if (onFailure) {
  65898. onFailure();
  65899. }
  65900. return;
  65901. }
  65902. // If all optimizations were done, move to next level
  65903. if (allDone) {
  65904. currentPriorityLevel++;
  65905. }
  65906. // Let's the system running for a specific amount of time before checking FPS
  65907. scene.executeWhenReady(function () {
  65908. setTimeout(function () {
  65909. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  65910. }, options.trackerDuration);
  65911. });
  65912. };
  65913. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  65914. if (!options) {
  65915. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  65916. }
  65917. // Let's the system running for a specific amount of time before checking FPS
  65918. scene.executeWhenReady(function () {
  65919. setTimeout(function () {
  65920. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  65921. }, options.trackerDuration);
  65922. });
  65923. };
  65924. return SceneOptimizer;
  65925. }());
  65926. BABYLON.SceneOptimizer = SceneOptimizer;
  65927. })(BABYLON || (BABYLON = {}));
  65928. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  65929. var BABYLON;
  65930. (function (BABYLON) {
  65931. var OutlineRenderer = (function () {
  65932. function OutlineRenderer(scene) {
  65933. this.zOffset = 1;
  65934. this._scene = scene;
  65935. }
  65936. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  65937. var _this = this;
  65938. if (useOverlay === void 0) { useOverlay = false; }
  65939. var scene = this._scene;
  65940. var engine = this._scene.getEngine();
  65941. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65942. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  65943. return;
  65944. }
  65945. var mesh = subMesh.getRenderingMesh();
  65946. var material = subMesh.getMaterial();
  65947. engine.enableEffect(this._effect);
  65948. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  65949. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  65950. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65951. // Bones
  65952. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65953. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65954. }
  65955. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65956. // Alpha test
  65957. if (material && material.needAlphaTesting()) {
  65958. var alphaTexture = material.getAlphaTestTexture();
  65959. this._effect.setTexture("diffuseSampler", alphaTexture);
  65960. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65961. }
  65962. engine.setZOffset(-this.zOffset);
  65963. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  65964. engine.setZOffset(0);
  65965. };
  65966. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  65967. var defines = [];
  65968. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  65969. var mesh = subMesh.getMesh();
  65970. var material = subMesh.getMaterial();
  65971. // Alpha test
  65972. if (material && material.needAlphaTesting()) {
  65973. defines.push("#define ALPHATEST");
  65974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65975. attribs.push(BABYLON.VertexBuffer.UVKind);
  65976. defines.push("#define UV1");
  65977. }
  65978. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65979. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65980. defines.push("#define UV2");
  65981. }
  65982. }
  65983. // Bones
  65984. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65985. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65986. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65987. if (mesh.numBoneInfluencers > 4) {
  65988. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65989. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65990. }
  65991. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65992. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65993. }
  65994. else {
  65995. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65996. }
  65997. // Instances
  65998. if (useInstances) {
  65999. defines.push("#define INSTANCES");
  66000. attribs.push("world0");
  66001. attribs.push("world1");
  66002. attribs.push("world2");
  66003. attribs.push("world3");
  66004. }
  66005. // Get correct effect
  66006. var join = defines.join("\n");
  66007. if (this._cachedDefines !== join) {
  66008. this._cachedDefines = join;
  66009. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  66010. }
  66011. return this._effect.isReady();
  66012. };
  66013. return OutlineRenderer;
  66014. }());
  66015. BABYLON.OutlineRenderer = OutlineRenderer;
  66016. })(BABYLON || (BABYLON = {}));
  66017. //# sourceMappingURL=babylon.outlineRenderer.js.map
  66018. var BABYLON;
  66019. (function (BABYLON) {
  66020. var FaceAdjacencies = (function () {
  66021. function FaceAdjacencies() {
  66022. this.edges = new Array();
  66023. this.edgesConnectedCount = 0;
  66024. }
  66025. return FaceAdjacencies;
  66026. }());
  66027. var EdgesRenderer = (function () {
  66028. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  66029. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  66030. if (epsilon === void 0) { epsilon = 0.95; }
  66031. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  66032. this.edgesWidthScalerForOrthographic = 1000.0;
  66033. this.edgesWidthScalerForPerspective = 50.0;
  66034. this._linesPositions = new Array();
  66035. this._linesNormals = new Array();
  66036. this._linesIndices = new Array();
  66037. this._buffers = {};
  66038. this._checkVerticesInsteadOfIndices = false;
  66039. this._source = source;
  66040. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  66041. this._epsilon = epsilon;
  66042. this._prepareRessources();
  66043. this._generateEdgesLines();
  66044. }
  66045. EdgesRenderer.prototype._prepareRessources = function () {
  66046. if (this._lineShader) {
  66047. return;
  66048. }
  66049. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  66050. attributes: ["position", "normal"],
  66051. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  66052. });
  66053. this._lineShader.disableDepthWrite = true;
  66054. this._lineShader.backFaceCulling = false;
  66055. };
  66056. EdgesRenderer.prototype.dispose = function () {
  66057. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  66058. if (buffer) {
  66059. buffer.dispose();
  66060. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  66061. }
  66062. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  66063. if (buffer) {
  66064. buffer.dispose();
  66065. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  66066. }
  66067. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  66068. this._lineShader.dispose();
  66069. };
  66070. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  66071. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  66072. return 0;
  66073. }
  66074. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  66075. return 1;
  66076. }
  66077. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  66078. return 2;
  66079. }
  66080. return -1;
  66081. };
  66082. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  66083. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  66084. return 0;
  66085. }
  66086. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  66087. return 1;
  66088. }
  66089. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  66090. return 2;
  66091. }
  66092. return -1;
  66093. };
  66094. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  66095. var needToCreateLine;
  66096. if (edge === undefined) {
  66097. needToCreateLine = true;
  66098. }
  66099. else {
  66100. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  66101. needToCreateLine = dotProduct < this._epsilon;
  66102. }
  66103. if (needToCreateLine) {
  66104. var offset = this._linesPositions.length / 3;
  66105. var normal = p0.subtract(p1);
  66106. normal.normalize();
  66107. // Positions
  66108. this._linesPositions.push(p0.x);
  66109. this._linesPositions.push(p0.y);
  66110. this._linesPositions.push(p0.z);
  66111. this._linesPositions.push(p0.x);
  66112. this._linesPositions.push(p0.y);
  66113. this._linesPositions.push(p0.z);
  66114. this._linesPositions.push(p1.x);
  66115. this._linesPositions.push(p1.y);
  66116. this._linesPositions.push(p1.z);
  66117. this._linesPositions.push(p1.x);
  66118. this._linesPositions.push(p1.y);
  66119. this._linesPositions.push(p1.z);
  66120. // Normals
  66121. this._linesNormals.push(p1.x);
  66122. this._linesNormals.push(p1.y);
  66123. this._linesNormals.push(p1.z);
  66124. this._linesNormals.push(-1);
  66125. this._linesNormals.push(p1.x);
  66126. this._linesNormals.push(p1.y);
  66127. this._linesNormals.push(p1.z);
  66128. this._linesNormals.push(1);
  66129. this._linesNormals.push(p0.x);
  66130. this._linesNormals.push(p0.y);
  66131. this._linesNormals.push(p0.z);
  66132. this._linesNormals.push(-1);
  66133. this._linesNormals.push(p0.x);
  66134. this._linesNormals.push(p0.y);
  66135. this._linesNormals.push(p0.z);
  66136. this._linesNormals.push(1);
  66137. // Indices
  66138. this._linesIndices.push(offset);
  66139. this._linesIndices.push(offset + 1);
  66140. this._linesIndices.push(offset + 2);
  66141. this._linesIndices.push(offset);
  66142. this._linesIndices.push(offset + 2);
  66143. this._linesIndices.push(offset + 3);
  66144. }
  66145. };
  66146. EdgesRenderer.prototype._generateEdgesLines = function () {
  66147. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66148. var indices = this._source.getIndices();
  66149. // First let's find adjacencies
  66150. var adjacencies = new Array();
  66151. var faceNormals = new Array();
  66152. var index;
  66153. var faceAdjacencies;
  66154. // Prepare faces
  66155. for (index = 0; index < indices.length; index += 3) {
  66156. faceAdjacencies = new FaceAdjacencies();
  66157. var p0Index = indices[index];
  66158. var p1Index = indices[index + 1];
  66159. var p2Index = indices[index + 2];
  66160. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  66161. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  66162. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  66163. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  66164. faceNormal.normalize();
  66165. faceNormals.push(faceNormal);
  66166. adjacencies.push(faceAdjacencies);
  66167. }
  66168. // Scan
  66169. for (index = 0; index < adjacencies.length; index++) {
  66170. faceAdjacencies = adjacencies[index];
  66171. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  66172. var otherFaceAdjacencies = adjacencies[otherIndex];
  66173. if (faceAdjacencies.edgesConnectedCount === 3) {
  66174. break;
  66175. }
  66176. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  66177. continue;
  66178. }
  66179. var otherP0 = indices[otherIndex * 3];
  66180. var otherP1 = indices[otherIndex * 3 + 1];
  66181. var otherP2 = indices[otherIndex * 3 + 2];
  66182. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  66183. var otherEdgeIndex;
  66184. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  66185. continue;
  66186. }
  66187. switch (edgeIndex) {
  66188. case 0:
  66189. if (this._checkVerticesInsteadOfIndices) {
  66190. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66191. }
  66192. else {
  66193. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  66194. }
  66195. break;
  66196. case 1:
  66197. if (this._checkVerticesInsteadOfIndices) {
  66198. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66199. }
  66200. else {
  66201. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  66202. }
  66203. break;
  66204. case 2:
  66205. if (this._checkVerticesInsteadOfIndices) {
  66206. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66207. }
  66208. else {
  66209. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  66210. }
  66211. break;
  66212. }
  66213. if (otherEdgeIndex === -1) {
  66214. continue;
  66215. }
  66216. faceAdjacencies.edges[edgeIndex] = otherIndex;
  66217. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  66218. faceAdjacencies.edgesConnectedCount++;
  66219. otherFaceAdjacencies.edgesConnectedCount++;
  66220. if (faceAdjacencies.edgesConnectedCount === 3) {
  66221. break;
  66222. }
  66223. }
  66224. }
  66225. }
  66226. // Create lines
  66227. for (index = 0; index < adjacencies.length; index++) {
  66228. // 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
  66229. var current = adjacencies[index];
  66230. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  66231. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  66232. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  66233. }
  66234. // Merge into a single mesh
  66235. var engine = this._source.getScene().getEngine();
  66236. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  66237. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  66238. this._ib = engine.createIndexBuffer(this._linesIndices);
  66239. this._indicesCount = this._linesIndices.length;
  66240. };
  66241. EdgesRenderer.prototype.render = function () {
  66242. if (!this._lineShader.isReady()) {
  66243. return;
  66244. }
  66245. var scene = this._source.getScene();
  66246. var engine = scene.getEngine();
  66247. this._lineShader._preBind();
  66248. // VBOs
  66249. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  66250. scene.resetCachedMaterial();
  66251. this._lineShader.setColor4("color", this._source.edgesColor);
  66252. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  66253. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  66254. }
  66255. else {
  66256. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  66257. }
  66258. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  66259. this._lineShader.bind(this._source.getWorldMatrix());
  66260. // Draw order
  66261. engine.draw(true, 0, this._indicesCount);
  66262. this._lineShader.unbind();
  66263. engine.setDepthWrite(true);
  66264. };
  66265. return EdgesRenderer;
  66266. }());
  66267. BABYLON.EdgesRenderer = EdgesRenderer;
  66268. })(BABYLON || (BABYLON = {}));
  66269. //# sourceMappingURL=babylon.edgesRenderer.js.map
  66270. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  66271. /// <reference path="..\Math\babylon.math.ts" />
  66272. var BABYLON;
  66273. (function (BABYLON) {
  66274. /**
  66275. * Special Glow Blur post process only blurring the alpha channel
  66276. * It enforces keeping the most luminous color in the color channel.
  66277. */
  66278. var GlowBlurPostProcess = (function (_super) {
  66279. __extends(GlowBlurPostProcess, _super);
  66280. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  66281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66282. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  66283. _this.direction = direction;
  66284. _this.kernel = kernel;
  66285. _this.onApplyObservable.add(function (effect) {
  66286. effect.setFloat2("screenSize", _this.width, _this.height);
  66287. effect.setVector2("direction", _this.direction);
  66288. effect.setFloat("blurWidth", _this.kernel);
  66289. });
  66290. return _this;
  66291. }
  66292. return GlowBlurPostProcess;
  66293. }(BABYLON.PostProcess));
  66294. /**
  66295. * The highlight layer Helps adding a glow effect around a mesh.
  66296. *
  66297. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  66298. * glowy meshes to your scene.
  66299. *
  66300. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  66301. */
  66302. var HighlightLayer = (function () {
  66303. /**
  66304. * Instantiates a new highlight Layer and references it to the scene..
  66305. * @param name The name of the layer
  66306. * @param scene The scene to use the layer in
  66307. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  66308. */
  66309. function HighlightLayer(name, scene, options) {
  66310. this.name = name;
  66311. this._vertexBuffers = {};
  66312. this._mainTextureDesiredSize = { width: 0, height: 0 };
  66313. this._meshes = {};
  66314. this._maxSize = 0;
  66315. this._shouldRender = false;
  66316. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  66317. this._excludedMeshes = {};
  66318. /**
  66319. * Specifies whether or not the inner glow is ACTIVE in the layer.
  66320. */
  66321. this.innerGlow = true;
  66322. /**
  66323. * Specifies whether or not the outer glow is ACTIVE in the layer.
  66324. */
  66325. this.outerGlow = true;
  66326. /**
  66327. * Specifies wether the highlight layer is enabled or not.
  66328. */
  66329. this.isEnabled = true;
  66330. /**
  66331. * An event triggered when the highlight layer has been disposed.
  66332. * @type {BABYLON.Observable}
  66333. */
  66334. this.onDisposeObservable = new BABYLON.Observable();
  66335. /**
  66336. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  66337. * @type {BABYLON.Observable}
  66338. */
  66339. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  66340. /**
  66341. * An event triggered when the highlight layer is being blurred.
  66342. * @type {BABYLON.Observable}
  66343. */
  66344. this.onBeforeBlurObservable = new BABYLON.Observable();
  66345. /**
  66346. * An event triggered when the highlight layer has been blurred.
  66347. * @type {BABYLON.Observable}
  66348. */
  66349. this.onAfterBlurObservable = new BABYLON.Observable();
  66350. /**
  66351. * An event triggered when the glowing blurred texture is being merged in the scene.
  66352. * @type {BABYLON.Observable}
  66353. */
  66354. this.onBeforeComposeObservable = new BABYLON.Observable();
  66355. /**
  66356. * An event triggered when the glowing blurred texture has been merged in the scene.
  66357. * @type {BABYLON.Observable}
  66358. */
  66359. this.onAfterComposeObservable = new BABYLON.Observable();
  66360. /**
  66361. * An event triggered when the highlight layer changes its size.
  66362. * @type {BABYLON.Observable}
  66363. */
  66364. this.onSizeChangedObservable = new BABYLON.Observable();
  66365. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66366. var engine = scene.getEngine();
  66367. this._engine = engine;
  66368. this._maxSize = this._engine.getCaps().maxTextureSize;
  66369. this._scene.highlightLayers.push(this);
  66370. // Warn on stencil.
  66371. if (!this._engine.isStencilEnable) {
  66372. 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 }");
  66373. }
  66374. // Adapt options
  66375. this._options = options || {
  66376. mainTextureRatio: 0.5,
  66377. blurTextureSizeRatio: 0.5,
  66378. blurHorizontalSize: 1.0,
  66379. blurVerticalSize: 1.0,
  66380. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  66381. };
  66382. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  66383. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  66384. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  66385. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  66386. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  66387. // VBO
  66388. var vertices = [];
  66389. vertices.push(1, 1);
  66390. vertices.push(-1, 1);
  66391. vertices.push(-1, -1);
  66392. vertices.push(1, -1);
  66393. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66394. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  66395. // Indices
  66396. var indices = [];
  66397. indices.push(0);
  66398. indices.push(1);
  66399. indices.push(2);
  66400. indices.push(0);
  66401. indices.push(2);
  66402. indices.push(3);
  66403. this._indexBuffer = engine.createIndexBuffer(indices);
  66404. // Effect
  66405. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  66406. // Render target
  66407. this.setMainTextureSize();
  66408. // Create Textures and post processes
  66409. this.createTextureAndPostProcesses();
  66410. }
  66411. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  66412. /**
  66413. * Gets the horizontal size of the blur.
  66414. */
  66415. get: function () {
  66416. return this._horizontalBlurPostprocess.kernel;
  66417. },
  66418. /**
  66419. * Specifies the horizontal size of the blur.
  66420. */
  66421. set: function (value) {
  66422. this._horizontalBlurPostprocess.kernel = value;
  66423. },
  66424. enumerable: true,
  66425. configurable: true
  66426. });
  66427. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  66428. /**
  66429. * Gets the vertical size of the blur.
  66430. */
  66431. get: function () {
  66432. return this._verticalBlurPostprocess.kernel;
  66433. },
  66434. /**
  66435. * Specifies the vertical size of the blur.
  66436. */
  66437. set: function (value) {
  66438. this._verticalBlurPostprocess.kernel = value;
  66439. },
  66440. enumerable: true,
  66441. configurable: true
  66442. });
  66443. Object.defineProperty(HighlightLayer.prototype, "camera", {
  66444. /**
  66445. * Gets the camera attached to the layer.
  66446. */
  66447. get: function () {
  66448. return this._options.camera;
  66449. },
  66450. enumerable: true,
  66451. configurable: true
  66452. });
  66453. /**
  66454. * Creates the render target textures and post processes used in the highlight layer.
  66455. */
  66456. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  66457. var _this = this;
  66458. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  66459. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  66460. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  66461. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  66462. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  66463. width: this._mainTextureDesiredSize.width,
  66464. height: this._mainTextureDesiredSize.height
  66465. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66466. this._mainTexture.activeCamera = this._options.camera;
  66467. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66468. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66469. this._mainTexture.anisotropicFilteringLevel = 1;
  66470. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66471. this._mainTexture.renderParticles = false;
  66472. this._mainTexture.renderList = null;
  66473. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  66474. width: blurTextureWidth,
  66475. height: blurTextureHeight
  66476. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66477. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66478. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66479. this._blurTexture.anisotropicFilteringLevel = 16;
  66480. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66481. this._blurTexture.renderParticles = false;
  66482. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66483. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  66484. effect.setTexture("textureSampler", _this._mainTexture);
  66485. });
  66486. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  66487. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66488. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  66489. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  66490. });
  66491. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66492. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  66493. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  66494. });
  66495. }
  66496. else {
  66497. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66498. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  66499. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  66500. });
  66501. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  66502. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  66503. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  66504. });
  66505. }
  66506. this._mainTexture.onAfterUnbindObservable.add(function () {
  66507. _this.onBeforeBlurObservable.notifyObservers(_this);
  66508. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  66509. _this.onAfterBlurObservable.notifyObservers(_this);
  66510. });
  66511. // Custom render function
  66512. var renderSubMesh = function (subMesh) {
  66513. var mesh = subMesh.getRenderingMesh();
  66514. var scene = _this._scene;
  66515. var engine = scene.getEngine();
  66516. // Culling
  66517. engine.setState(subMesh.getMaterial().backFaceCulling);
  66518. // Managing instances
  66519. var batch = mesh._getInstancesRenderList(subMesh._id);
  66520. if (batch.mustReturn) {
  66521. return;
  66522. }
  66523. // Excluded Mesh
  66524. if (_this._excludedMeshes[mesh.uniqueId]) {
  66525. return;
  66526. }
  66527. ;
  66528. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66529. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  66530. var material = subMesh.getMaterial();
  66531. var emissiveTexture = null;
  66532. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  66533. emissiveTexture = material.emissiveTexture;
  66534. }
  66535. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  66536. engine.enableEffect(_this._glowMapGenerationEffect);
  66537. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  66538. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  66539. if (highlightLayerMesh) {
  66540. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  66541. }
  66542. else {
  66543. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  66544. }
  66545. // Alpha test
  66546. if (material && material.needAlphaTesting()) {
  66547. var alphaTexture = material.getAlphaTestTexture();
  66548. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  66549. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66550. }
  66551. // Glow emissive only
  66552. if (emissiveTexture) {
  66553. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  66554. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  66555. }
  66556. // Bones
  66557. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66558. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66559. }
  66560. // Draw
  66561. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  66562. }
  66563. else {
  66564. // Need to reset refresh rate of the shadowMap
  66565. _this._mainTexture.resetRefreshCounter();
  66566. }
  66567. };
  66568. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  66569. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  66570. var index;
  66571. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66572. renderSubMesh(opaqueSubMeshes.data[index]);
  66573. }
  66574. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66575. renderSubMesh(alphaTestSubMeshes.data[index]);
  66576. }
  66577. for (index = 0; index < transparentSubMeshes.length; index++) {
  66578. renderSubMesh(transparentSubMeshes.data[index]);
  66579. }
  66580. };
  66581. this._mainTexture.onClearObservable.add(function (engine) {
  66582. engine.clear(HighlightLayer.neutralColor, true, true, true);
  66583. });
  66584. };
  66585. /**
  66586. * Checks for the readiness of the element composing the layer.
  66587. * @param subMesh the mesh to check for
  66588. * @param useInstances specify wether or not to use instances to render the mesh
  66589. * @param emissiveTexture the associated emissive texture used to generate the glow
  66590. * @return true if ready otherwise, false
  66591. */
  66592. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  66593. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  66594. return false;
  66595. }
  66596. var defines = [];
  66597. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66598. var mesh = subMesh.getMesh();
  66599. var material = subMesh.getMaterial();
  66600. var uv1 = false;
  66601. var uv2 = false;
  66602. // Alpha test
  66603. if (material && material.needAlphaTesting()) {
  66604. var alphaTexture = material.getAlphaTestTexture();
  66605. if (alphaTexture) {
  66606. defines.push("#define ALPHATEST");
  66607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  66608. alphaTexture.coordinatesIndex === 1) {
  66609. defines.push("#define DIFFUSEUV2");
  66610. uv2 = true;
  66611. }
  66612. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66613. defines.push("#define DIFFUSEUV1");
  66614. uv1 = true;
  66615. }
  66616. }
  66617. }
  66618. // Emissive
  66619. if (emissiveTexture) {
  66620. defines.push("#define EMISSIVE");
  66621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  66622. emissiveTexture.coordinatesIndex === 1) {
  66623. defines.push("#define EMISSIVEUV2");
  66624. uv2 = true;
  66625. }
  66626. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66627. defines.push("#define EMISSIVEUV1");
  66628. uv1 = true;
  66629. }
  66630. }
  66631. if (uv1) {
  66632. attribs.push(BABYLON.VertexBuffer.UVKind);
  66633. defines.push("#define UV1");
  66634. }
  66635. if (uv2) {
  66636. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66637. defines.push("#define UV2");
  66638. }
  66639. // Bones
  66640. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66641. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66642. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66643. if (mesh.numBoneInfluencers > 4) {
  66644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66646. }
  66647. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66648. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66649. }
  66650. else {
  66651. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66652. }
  66653. // Instances
  66654. if (useInstances) {
  66655. defines.push("#define INSTANCES");
  66656. attribs.push("world0");
  66657. attribs.push("world1");
  66658. attribs.push("world2");
  66659. attribs.push("world3");
  66660. }
  66661. // Get correct effect
  66662. var join = defines.join("\n");
  66663. if (this._cachedDefines !== join) {
  66664. this._cachedDefines = join;
  66665. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  66666. }
  66667. return this._glowMapGenerationEffect.isReady();
  66668. };
  66669. /**
  66670. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  66671. */
  66672. HighlightLayer.prototype.render = function () {
  66673. var currentEffect = this._glowMapMergeEffect;
  66674. // Check
  66675. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  66676. return;
  66677. var engine = this._scene.getEngine();
  66678. this.onBeforeComposeObservable.notifyObservers(this);
  66679. // Render
  66680. engine.enableEffect(currentEffect);
  66681. engine.setState(false);
  66682. // Cache
  66683. var previousStencilBuffer = engine.getStencilBuffer();
  66684. var previousStencilFunction = engine.getStencilFunction();
  66685. var previousStencilMask = engine.getStencilMask();
  66686. var previousStencilOperationPass = engine.getStencilOperationPass();
  66687. var previousStencilOperationFail = engine.getStencilOperationFail();
  66688. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  66689. var previousAlphaMode = engine.getAlphaMode();
  66690. // Texture
  66691. currentEffect.setTexture("textureSampler", this._blurTexture);
  66692. // VBOs
  66693. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  66694. // Stencil operations
  66695. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  66696. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  66697. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  66698. // Draw order
  66699. engine.setAlphaMode(this._options.alphaBlendingMode);
  66700. engine.setStencilMask(0x00);
  66701. engine.setStencilBuffer(true);
  66702. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  66703. if (this.outerGlow) {
  66704. currentEffect.setFloat("offset", 0);
  66705. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  66706. engine.draw(true, 0, 6);
  66707. }
  66708. if (this.innerGlow) {
  66709. currentEffect.setFloat("offset", 1);
  66710. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  66711. engine.draw(true, 0, 6);
  66712. }
  66713. // Restore Cache
  66714. engine.setStencilFunction(previousStencilFunction);
  66715. engine.setStencilMask(previousStencilMask);
  66716. engine.setAlphaMode(previousAlphaMode);
  66717. engine.setStencilBuffer(previousStencilBuffer);
  66718. engine.setStencilOperationPass(previousStencilOperationPass);
  66719. engine.setStencilOperationFail(previousStencilOperationFail);
  66720. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  66721. engine._stencilState.reset();
  66722. this.onAfterComposeObservable.notifyObservers(this);
  66723. // Handle size changes.
  66724. var size = this._mainTexture.getSize();
  66725. this.setMainTextureSize();
  66726. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  66727. // Recreate RTT and post processes on size change.
  66728. this.onSizeChangedObservable.notifyObservers(this);
  66729. this.disposeTextureAndPostProcesses();
  66730. this.createTextureAndPostProcesses();
  66731. }
  66732. };
  66733. /**
  66734. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  66735. * @param mesh The mesh to exclude from the highlight layer
  66736. */
  66737. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  66738. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  66739. if (!meshExcluded) {
  66740. this._excludedMeshes[mesh.uniqueId] = {
  66741. mesh: mesh,
  66742. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  66743. mesh.getEngine().setStencilBuffer(false);
  66744. }),
  66745. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  66746. mesh.getEngine().setStencilBuffer(true);
  66747. }),
  66748. };
  66749. }
  66750. };
  66751. /**
  66752. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  66753. * @param mesh The mesh to highlight
  66754. */
  66755. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  66756. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  66757. if (meshExcluded) {
  66758. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  66759. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  66760. }
  66761. this._excludedMeshes[mesh.uniqueId] = undefined;
  66762. };
  66763. /**
  66764. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  66765. * @param mesh The mesh to highlight
  66766. * @param color The color of the highlight
  66767. * @param glowEmissiveOnly Extract the glow from the emissive texture
  66768. */
  66769. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  66770. var _this = this;
  66771. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  66772. var meshHighlight = this._meshes[mesh.uniqueId];
  66773. if (meshHighlight) {
  66774. meshHighlight.color = color;
  66775. }
  66776. else {
  66777. this._meshes[mesh.uniqueId] = {
  66778. mesh: mesh,
  66779. color: color,
  66780. // Lambda required for capture due to Observable this context
  66781. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  66782. if (_this._excludedMeshes[mesh.uniqueId]) {
  66783. _this.defaultStencilReference(mesh);
  66784. }
  66785. else {
  66786. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  66787. }
  66788. }),
  66789. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  66790. glowEmissiveOnly: glowEmissiveOnly
  66791. };
  66792. }
  66793. this._shouldRender = true;
  66794. };
  66795. /**
  66796. * Remove a mesh from the highlight layer in order to make it stop glowing.
  66797. * @param mesh The mesh to highlight
  66798. */
  66799. HighlightLayer.prototype.removeMesh = function (mesh) {
  66800. var meshHighlight = this._meshes[mesh.uniqueId];
  66801. if (meshHighlight) {
  66802. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66803. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66804. }
  66805. this._meshes[mesh.uniqueId] = undefined;
  66806. this._shouldRender = false;
  66807. for (var meshHighlightToCheck in this._meshes) {
  66808. if (meshHighlightToCheck) {
  66809. this._shouldRender = true;
  66810. break;
  66811. }
  66812. }
  66813. };
  66814. /**
  66815. * Returns true if the layer contains information to display, otherwise false.
  66816. */
  66817. HighlightLayer.prototype.shouldRender = function () {
  66818. return this.isEnabled && this._shouldRender;
  66819. };
  66820. /**
  66821. * Sets the main texture desired size which is the closest power of two
  66822. * of the engine canvas size.
  66823. */
  66824. HighlightLayer.prototype.setMainTextureSize = function () {
  66825. if (this._options.mainTextureFixedSize) {
  66826. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  66827. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  66828. }
  66829. else {
  66830. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  66831. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  66832. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  66833. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  66834. }
  66835. };
  66836. /**
  66837. * Force the stencil to the normal expected value for none glowing parts
  66838. */
  66839. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  66840. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  66841. };
  66842. /**
  66843. * Dispose only the render target textures and post process.
  66844. */
  66845. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  66846. this._blurTexture.dispose();
  66847. this._mainTexture.dispose();
  66848. this._downSamplePostprocess.dispose();
  66849. this._horizontalBlurPostprocess.dispose();
  66850. this._verticalBlurPostprocess.dispose();
  66851. };
  66852. /**
  66853. * Dispose the highlight layer and free resources.
  66854. */
  66855. HighlightLayer.prototype.dispose = function () {
  66856. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66857. if (vertexBuffer) {
  66858. vertexBuffer.dispose();
  66859. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66860. }
  66861. if (this._indexBuffer) {
  66862. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66863. this._indexBuffer = null;
  66864. }
  66865. // Clean textures and post processes
  66866. this.disposeTextureAndPostProcesses();
  66867. // Clean mesh references
  66868. for (var id in this._meshes) {
  66869. var meshHighlight = this._meshes[id];
  66870. if (meshHighlight && meshHighlight.mesh) {
  66871. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  66872. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  66873. }
  66874. }
  66875. this._meshes = null;
  66876. for (var id in this._excludedMeshes) {
  66877. var meshHighlight = this._excludedMeshes[id];
  66878. if (meshHighlight) {
  66879. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  66880. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  66881. }
  66882. }
  66883. this._excludedMeshes = null;
  66884. // Remove from scene
  66885. var index = this._scene.highlightLayers.indexOf(this, 0);
  66886. if (index > -1) {
  66887. this._scene.highlightLayers.splice(index, 1);
  66888. }
  66889. // Callback
  66890. this.onDisposeObservable.notifyObservers(this);
  66891. this.onDisposeObservable.clear();
  66892. this.onBeforeRenderMainTextureObservable.clear();
  66893. this.onBeforeBlurObservable.clear();
  66894. this.onBeforeComposeObservable.clear();
  66895. this.onAfterComposeObservable.clear();
  66896. this.onSizeChangedObservable.clear();
  66897. };
  66898. return HighlightLayer;
  66899. }());
  66900. /**
  66901. * The neutral color used during the preparation of the glow effect.
  66902. * This is black by default as the blend operation is a blend operation.
  66903. */
  66904. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  66905. /**
  66906. * Stencil value used for glowing meshes.
  66907. */
  66908. HighlightLayer.glowingMeshStencilReference = 0x02;
  66909. /**
  66910. * Stencil value used for the other meshes in the scene.
  66911. */
  66912. HighlightLayer.normalMeshStencilReference = 0x01;
  66913. BABYLON.HighlightLayer = HighlightLayer;
  66914. })(BABYLON || (BABYLON = {}));
  66915. //# sourceMappingURL=babylon.highlightlayer.js.map
  66916. var BABYLON;
  66917. (function (BABYLON) {
  66918. var MeshAssetTask = (function () {
  66919. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  66920. this.name = name;
  66921. this.meshesNames = meshesNames;
  66922. this.rootUrl = rootUrl;
  66923. this.sceneFilename = sceneFilename;
  66924. this.isCompleted = false;
  66925. }
  66926. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66927. var _this = this;
  66928. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  66929. _this.loadedMeshes = meshes;
  66930. _this.loadedParticleSystems = particleSystems;
  66931. _this.loadedSkeletons = skeletons;
  66932. _this.isCompleted = true;
  66933. if (_this.onSuccess) {
  66934. _this.onSuccess(_this);
  66935. }
  66936. onSuccess();
  66937. }, null, function () {
  66938. if (_this.onError) {
  66939. _this.onError(_this);
  66940. }
  66941. onError();
  66942. });
  66943. };
  66944. return MeshAssetTask;
  66945. }());
  66946. BABYLON.MeshAssetTask = MeshAssetTask;
  66947. var TextFileAssetTask = (function () {
  66948. function TextFileAssetTask(name, url) {
  66949. this.name = name;
  66950. this.url = url;
  66951. this.isCompleted = false;
  66952. }
  66953. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66954. var _this = this;
  66955. BABYLON.Tools.LoadFile(this.url, function (data) {
  66956. _this.text = data;
  66957. _this.isCompleted = true;
  66958. if (_this.onSuccess) {
  66959. _this.onSuccess(_this);
  66960. }
  66961. onSuccess();
  66962. }, null, scene.database, false, function () {
  66963. if (_this.onError) {
  66964. _this.onError(_this);
  66965. }
  66966. onError();
  66967. });
  66968. };
  66969. return TextFileAssetTask;
  66970. }());
  66971. BABYLON.TextFileAssetTask = TextFileAssetTask;
  66972. var BinaryFileAssetTask = (function () {
  66973. function BinaryFileAssetTask(name, url) {
  66974. this.name = name;
  66975. this.url = url;
  66976. this.isCompleted = false;
  66977. }
  66978. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  66979. var _this = this;
  66980. BABYLON.Tools.LoadFile(this.url, function (data) {
  66981. _this.data = data;
  66982. _this.isCompleted = true;
  66983. if (_this.onSuccess) {
  66984. _this.onSuccess(_this);
  66985. }
  66986. onSuccess();
  66987. }, null, scene.database, true, function () {
  66988. if (_this.onError) {
  66989. _this.onError(_this);
  66990. }
  66991. onError();
  66992. });
  66993. };
  66994. return BinaryFileAssetTask;
  66995. }());
  66996. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  66997. var ImageAssetTask = (function () {
  66998. function ImageAssetTask(name, url) {
  66999. this.name = name;
  67000. this.url = url;
  67001. this.isCompleted = false;
  67002. }
  67003. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67004. var _this = this;
  67005. var img = new Image();
  67006. BABYLON.Tools.SetCorsBehavior(this.url, img);
  67007. img.onload = function () {
  67008. _this.image = img;
  67009. _this.isCompleted = true;
  67010. if (_this.onSuccess) {
  67011. _this.onSuccess(_this);
  67012. }
  67013. onSuccess();
  67014. };
  67015. img.onerror = function () {
  67016. if (_this.onError) {
  67017. _this.onError(_this);
  67018. }
  67019. onError();
  67020. };
  67021. img.src = this.url;
  67022. };
  67023. return ImageAssetTask;
  67024. }());
  67025. BABYLON.ImageAssetTask = ImageAssetTask;
  67026. var TextureAssetTask = (function () {
  67027. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  67028. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67029. this.name = name;
  67030. this.url = url;
  67031. this.noMipmap = noMipmap;
  67032. this.invertY = invertY;
  67033. this.samplingMode = samplingMode;
  67034. this.isCompleted = false;
  67035. }
  67036. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67037. var _this = this;
  67038. var onload = function () {
  67039. _this.isCompleted = true;
  67040. if (_this.onSuccess) {
  67041. _this.onSuccess(_this);
  67042. }
  67043. onSuccess();
  67044. };
  67045. var onerror = function () {
  67046. if (_this.onError) {
  67047. _this.onError(_this);
  67048. }
  67049. onError();
  67050. };
  67051. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  67052. };
  67053. return TextureAssetTask;
  67054. }());
  67055. BABYLON.TextureAssetTask = TextureAssetTask;
  67056. var CubeTextureAssetTask = (function () {
  67057. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  67058. this.name = name;
  67059. this.url = url;
  67060. this.extensions = extensions;
  67061. this.noMipmap = noMipmap;
  67062. this.files = files;
  67063. this.isCompleted = false;
  67064. }
  67065. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67066. var _this = this;
  67067. var onload = function () {
  67068. _this.isCompleted = true;
  67069. if (_this.onSuccess) {
  67070. _this.onSuccess(_this);
  67071. }
  67072. onSuccess();
  67073. };
  67074. var onerror = function () {
  67075. if (_this.onError) {
  67076. _this.onError(_this);
  67077. }
  67078. onError();
  67079. };
  67080. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  67081. };
  67082. return CubeTextureAssetTask;
  67083. }());
  67084. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  67085. var HDRCubeTextureAssetTask = (function () {
  67086. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  67087. if (noMipmap === void 0) { noMipmap = false; }
  67088. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67089. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67090. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67091. this.name = name;
  67092. this.url = url;
  67093. this.size = size;
  67094. this.noMipmap = noMipmap;
  67095. this.generateHarmonics = generateHarmonics;
  67096. this.useInGammaSpace = useInGammaSpace;
  67097. this.usePMREMGenerator = usePMREMGenerator;
  67098. this.isCompleted = false;
  67099. }
  67100. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67101. var _this = this;
  67102. var onload = function () {
  67103. _this.isCompleted = true;
  67104. if (_this.onSuccess) {
  67105. _this.onSuccess(_this);
  67106. }
  67107. onSuccess();
  67108. };
  67109. var onerror = function () {
  67110. if (_this.onError) {
  67111. _this.onError(_this);
  67112. }
  67113. onError();
  67114. };
  67115. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  67116. };
  67117. return HDRCubeTextureAssetTask;
  67118. }());
  67119. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  67120. var AssetsManager = (function () {
  67121. function AssetsManager(scene) {
  67122. this.tasks = new Array();
  67123. this.waitingTasksCount = 0;
  67124. this.useDefaultLoadingScreen = true;
  67125. this._scene = scene;
  67126. }
  67127. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  67128. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  67129. this.tasks.push(task);
  67130. return task;
  67131. };
  67132. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  67133. var task = new TextFileAssetTask(taskName, url);
  67134. this.tasks.push(task);
  67135. return task;
  67136. };
  67137. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  67138. var task = new BinaryFileAssetTask(taskName, url);
  67139. this.tasks.push(task);
  67140. return task;
  67141. };
  67142. AssetsManager.prototype.addImageTask = function (taskName, url) {
  67143. var task = new ImageAssetTask(taskName, url);
  67144. this.tasks.push(task);
  67145. return task;
  67146. };
  67147. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  67148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67149. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  67150. this.tasks.push(task);
  67151. return task;
  67152. };
  67153. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  67154. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  67155. this.tasks.push(task);
  67156. return task;
  67157. };
  67158. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  67159. if (noMipmap === void 0) { noMipmap = false; }
  67160. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67161. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67162. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67163. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  67164. this.tasks.push(task);
  67165. return task;
  67166. };
  67167. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  67168. this.waitingTasksCount--;
  67169. if (this.waitingTasksCount === 0) {
  67170. if (this.onFinish) {
  67171. this.onFinish(this.tasks);
  67172. }
  67173. this._scene.getEngine().hideLoadingUI();
  67174. }
  67175. };
  67176. AssetsManager.prototype._runTask = function (task) {
  67177. var _this = this;
  67178. task.run(this._scene, function () {
  67179. if (_this.onTaskSuccess) {
  67180. _this.onTaskSuccess(task);
  67181. }
  67182. _this._decreaseWaitingTasksCount();
  67183. }, function () {
  67184. if (_this.onTaskError) {
  67185. _this.onTaskError(task);
  67186. }
  67187. _this._decreaseWaitingTasksCount();
  67188. });
  67189. };
  67190. AssetsManager.prototype.reset = function () {
  67191. this.tasks = new Array();
  67192. return this;
  67193. };
  67194. AssetsManager.prototype.load = function () {
  67195. this.waitingTasksCount = this.tasks.length;
  67196. if (this.waitingTasksCount === 0) {
  67197. if (this.onFinish) {
  67198. this.onFinish(this.tasks);
  67199. }
  67200. return this;
  67201. }
  67202. if (this.useDefaultLoadingScreen) {
  67203. this._scene.getEngine().displayLoadingUI();
  67204. }
  67205. for (var index = 0; index < this.tasks.length; index++) {
  67206. var task = this.tasks[index];
  67207. this._runTask(task);
  67208. }
  67209. return this;
  67210. };
  67211. return AssetsManager;
  67212. }());
  67213. BABYLON.AssetsManager = AssetsManager;
  67214. })(BABYLON || (BABYLON = {}));
  67215. //# sourceMappingURL=babylon.assetsManager.js.map
  67216. var BABYLON;
  67217. (function (BABYLON) {
  67218. var MapTexture = (function (_super) {
  67219. __extends(MapTexture, _super);
  67220. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  67221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67222. if (useMipMap === void 0) { useMipMap = false; }
  67223. if (margin === void 0) { margin = 0; }
  67224. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  67225. _this.name = name;
  67226. _this._size = size;
  67227. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67228. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67229. // Create the rectPackMap that will allocate portion of the texture
  67230. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  67231. // Create the texture that will store the content
  67232. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  67233. return _this;
  67234. }
  67235. /**
  67236. * Allocate a rectangle of a given size in the texture map
  67237. * @param size the size of the rectangle to allocation
  67238. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  67239. */
  67240. MapTexture.prototype.allocateRect = function (size) {
  67241. return this._rectPackingMap.addRect(size);
  67242. };
  67243. /**
  67244. * Free a given rectangle from the texture map
  67245. * @param rectInfo the instance corresponding to the rect to free.
  67246. */
  67247. MapTexture.prototype.freeRect = function (rectInfo) {
  67248. if (rectInfo) {
  67249. rectInfo.freeContent();
  67250. }
  67251. };
  67252. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  67253. /**
  67254. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  67255. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  67256. * @returns {}
  67257. */
  67258. get: function () {
  67259. return this._rectPackingMap.freeSpace;
  67260. },
  67261. enumerable: true,
  67262. configurable: true
  67263. });
  67264. /**
  67265. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  67266. * 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.
  67267. * Don't forget to call unbindTexture when you're done rendering
  67268. * @param rect the zone to render to
  67269. * @param clear true to clear the portion's color/depth data
  67270. */
  67271. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  67272. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  67273. };
  67274. /**
  67275. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  67276. * 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.
  67277. * Don't forget to call unbindTexture when you're done rendering
  67278. * @param pos the position into the texture
  67279. * @param size the portion to fit the clip space to
  67280. * @param clear true to clear the portion's color/depth data
  67281. */
  67282. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  67283. var engine = this.getScene().getEngine();
  67284. engine.bindFramebuffer(this._texture);
  67285. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  67286. if (clear) {
  67287. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  67288. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  67289. }
  67290. };
  67291. /**
  67292. * Unbind the texture map from the rendering engine.
  67293. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  67294. * @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.
  67295. */
  67296. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  67297. // Dump ?
  67298. if (dumpForDebug) {
  67299. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  67300. }
  67301. var engine = this.getScene().getEngine();
  67302. if (this._replacedViewport) {
  67303. engine.setViewport(this._replacedViewport);
  67304. this._replacedViewport = null;
  67305. }
  67306. engine.unBindFramebuffer(this._texture);
  67307. };
  67308. Object.defineProperty(MapTexture.prototype, "canRescale", {
  67309. get: function () {
  67310. return false;
  67311. },
  67312. enumerable: true,
  67313. configurable: true
  67314. });
  67315. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  67316. // Anyway, there's not much point to use this method for this kind of texture I guess
  67317. MapTexture.prototype.clone = function () {
  67318. return null;
  67319. };
  67320. return MapTexture;
  67321. }(BABYLON.Texture));
  67322. BABYLON.MapTexture = MapTexture;
  67323. })(BABYLON || (BABYLON = {}));
  67324. //# sourceMappingURL=babylon.mapTexture.js.map
  67325. var BABYLON;
  67326. (function (BABYLON) {
  67327. /**
  67328. * This class describe a rectangle that were added to the map.
  67329. * You have access to its coordinates either in pixel or normalized (UV)
  67330. */
  67331. var PackedRect = (function () {
  67332. function PackedRect(root, parent, pos, size) {
  67333. this._pos = pos;
  67334. this._size = size;
  67335. this._root = root;
  67336. this._parent = parent;
  67337. this._contentSize = null;
  67338. this._bottomNode = null;
  67339. this._leftNode = null;
  67340. this._initialSize = null;
  67341. this._rightNode = null;
  67342. }
  67343. Object.defineProperty(PackedRect.prototype, "pos", {
  67344. /**
  67345. * @returns the position of this node into the map
  67346. */
  67347. get: function () {
  67348. return this._pos;
  67349. },
  67350. enumerable: true,
  67351. configurable: true
  67352. });
  67353. Object.defineProperty(PackedRect.prototype, "contentSize", {
  67354. /**
  67355. * @returns the size of the rectangle this node handles
  67356. */
  67357. get: function () {
  67358. return this._contentSize;
  67359. },
  67360. enumerable: true,
  67361. configurable: true
  67362. });
  67363. /**
  67364. * Retrieve the inner position (considering the margin) and stores it into the res object
  67365. * @param res must be a valid Vector2 that will contain the inner position after this call
  67366. */
  67367. PackedRect.prototype.getInnerPosToRef = function (res) {
  67368. var m = this._root._margin;
  67369. res.x = this._pos.x + m;
  67370. res.y = this._pos.y + m;
  67371. };
  67372. /**
  67373. * Retrieve the inner size (considering the margin) and stores it into the res object
  67374. * @param res must be a valid Size that will contain the inner size after this call
  67375. */
  67376. PackedRect.prototype.getInnerSizeToRef = function (res) {
  67377. var m = this._root._margin;
  67378. res.width = this._contentSize.width - (m * 2);
  67379. res.height = this._contentSize.height - (m * 2);
  67380. };
  67381. Object.defineProperty(PackedRect.prototype, "UVs", {
  67382. /**
  67383. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  67384. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  67385. */
  67386. get: function () {
  67387. if (!this._contentSize) {
  67388. throw new Error("Can't compute UVs for this object because it's nor allocated");
  67389. }
  67390. return this.getUVsForCustomSize(this._contentSize);
  67391. },
  67392. enumerable: true,
  67393. configurable: true
  67394. });
  67395. /**
  67396. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  67397. * and then using only a part of the PackRect.
  67398. * This method will return the UVs for this part by given the custom size of what you really use
  67399. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  67400. */
  67401. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  67402. var mainWidth = this._root._size.width;
  67403. var mainHeight = this._root._size.height;
  67404. var margin = this._root._margin;
  67405. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  67406. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  67407. var uvs = new Array();
  67408. uvs.push(topLeft);
  67409. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  67410. uvs.push(rightBottom);
  67411. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  67412. return uvs;
  67413. };
  67414. /**
  67415. * Free this rectangle from the map.
  67416. * Call this method when you no longer need the rectangle to be in the map.
  67417. */
  67418. PackedRect.prototype.freeContent = function () {
  67419. if (!this.contentSize) {
  67420. return;
  67421. }
  67422. this._contentSize = null;
  67423. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  67424. this.attemptDefrag();
  67425. };
  67426. Object.defineProperty(PackedRect.prototype, "isUsed", {
  67427. get: function () {
  67428. return this._contentSize != null || this._leftNode != null;
  67429. },
  67430. enumerable: true,
  67431. configurable: true
  67432. });
  67433. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  67434. var node = this.findNode(contentSize);
  67435. // Not enough space...
  67436. if (!node) {
  67437. return null;
  67438. }
  67439. node.splitNode(contentSize);
  67440. return node;
  67441. };
  67442. PackedRect.prototype.findNode = function (size) {
  67443. var resNode = null;
  67444. var margin = this._root._margin * 2;
  67445. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  67446. if (this.isUsed) {
  67447. if (this._leftNode) {
  67448. resNode = this._leftNode.findNode(size);
  67449. }
  67450. if (!resNode && this._rightNode) {
  67451. resNode = this._rightNode.findNode(size);
  67452. }
  67453. if (!resNode && this._bottomNode) {
  67454. resNode = this._bottomNode.findNode(size);
  67455. }
  67456. }
  67457. else if (this._initialSize) {
  67458. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  67459. resNode = this;
  67460. }
  67461. else {
  67462. return null;
  67463. }
  67464. }
  67465. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  67466. resNode = this;
  67467. }
  67468. return resNode;
  67469. };
  67470. PackedRect.prototype.splitNode = function (contentSize) {
  67471. var cs = PackedRect.TpsSize;
  67472. var margin = this._root._margin * 2;
  67473. cs.copyFrom(contentSize);
  67474. cs.width += margin;
  67475. cs.height += margin;
  67476. // 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)
  67477. if (!this._contentSize && this._initialSize) {
  67478. this._contentSize = cs.clone();
  67479. 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));
  67480. return this._leftNode.splitNode(contentSize);
  67481. }
  67482. else {
  67483. this._contentSize = cs.clone();
  67484. this._initialSize = cs.clone();
  67485. if (cs.width !== this._size.width) {
  67486. 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));
  67487. }
  67488. if (cs.height !== this._size.height) {
  67489. 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));
  67490. }
  67491. return this;
  67492. }
  67493. };
  67494. PackedRect.prototype.attemptDefrag = function () {
  67495. if (!this.isUsed && this.isRecursiveFree) {
  67496. this.clearNode();
  67497. if (this._parent) {
  67498. this._parent.attemptDefrag();
  67499. }
  67500. }
  67501. };
  67502. PackedRect.prototype.clearNode = function () {
  67503. this._initialSize = null;
  67504. this._rightNode = null;
  67505. this._bottomNode = null;
  67506. };
  67507. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  67508. get: function () {
  67509. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  67510. },
  67511. enumerable: true,
  67512. configurable: true
  67513. });
  67514. PackedRect.prototype.evalFreeSize = function (size) {
  67515. var levelSize = 0;
  67516. if (!this.isUsed) {
  67517. var margin = this._root._margin;
  67518. var is = this._initialSize;
  67519. if (is) {
  67520. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  67521. }
  67522. else {
  67523. var size_1 = this._size;
  67524. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  67525. }
  67526. }
  67527. if (this._rightNode) {
  67528. levelSize += this._rightNode.evalFreeSize(0);
  67529. }
  67530. if (this._bottomNode) {
  67531. levelSize += this._bottomNode.evalFreeSize(0);
  67532. }
  67533. return levelSize + size;
  67534. };
  67535. return PackedRect;
  67536. }());
  67537. PackedRect.TpsSize = BABYLON.Size.Zero();
  67538. BABYLON.PackedRect = PackedRect;
  67539. /**
  67540. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  67541. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  67542. * 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.
  67543. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  67544. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  67545. */
  67546. var RectPackingMap = (function (_super) {
  67547. __extends(RectPackingMap, _super);
  67548. /**
  67549. * Create an instance of the object with a dimension using the given size
  67550. * @param size The dimension of the rectangle that will contain all the sub ones.
  67551. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  67552. */
  67553. function RectPackingMap(size, margin) {
  67554. if (margin === void 0) { margin = 0; }
  67555. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  67556. _this._margin = margin;
  67557. _this._root = _this;
  67558. return _this;
  67559. }
  67560. /**
  67561. * Add a rectangle, finding the best location to store it into the map
  67562. * @param size the dimension of the rectangle to store
  67563. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  67564. */
  67565. RectPackingMap.prototype.addRect = function (size) {
  67566. var node = this.findAndSplitNode(size);
  67567. return node;
  67568. };
  67569. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  67570. /**
  67571. * Return the current space free normalized between [0;1]
  67572. * @returns {}
  67573. */
  67574. get: function () {
  67575. var freeSize = 0;
  67576. freeSize = this.evalFreeSize(freeSize);
  67577. return freeSize / (this._size.width * this._size.height);
  67578. },
  67579. enumerable: true,
  67580. configurable: true
  67581. });
  67582. return RectPackingMap;
  67583. }(PackedRect));
  67584. BABYLON.RectPackingMap = RectPackingMap;
  67585. })(BABYLON || (BABYLON = {}));
  67586. //# sourceMappingURL=babylon.rectPackingMap.js.map
  67587. var BABYLON;
  67588. (function (BABYLON) {
  67589. /**
  67590. * This groups together the common properties used for image processing either in direct forward pass
  67591. * or through post processing effect depending on the use of the image processing pipeline in your scene
  67592. * or not.
  67593. */
  67594. var ImageProcessingConfiguration = (function () {
  67595. function ImageProcessingConfiguration() {
  67596. /**
  67597. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  67598. */
  67599. this.colorCurves = new BABYLON.ColorCurves();
  67600. this._colorCurvesEnabled = false;
  67601. this._colorGradingEnabled = false;
  67602. this._colorGradingWithGreenDepth = false;
  67603. this._colorGradingBGR = false;
  67604. this._exposure = 1.0;
  67605. this._toneMappingEnabled = false;
  67606. this._contrast = 1.0;
  67607. /**
  67608. * Vignette stretch size.
  67609. */
  67610. this.vignetteStretch = 0;
  67611. /**
  67612. * Vignette centre X Offset.
  67613. */
  67614. this.vignetteCentreX = 0;
  67615. /**
  67616. * Vignette centre Y Offset.
  67617. */
  67618. this.vignetteCentreY = 0;
  67619. /**
  67620. * Vignette weight or intensity of the vignette effect.
  67621. */
  67622. this.vignetteWeight = 1.5;
  67623. /**
  67624. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67625. * if vignetteEnabled is set to true.
  67626. */
  67627. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  67628. /**
  67629. * Camera field of view used by the Vignette effect.
  67630. */
  67631. this.vignetteCameraFov = 0.5;
  67632. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  67633. this._vignetteEnabled = false;
  67634. this._applyByPostProcess = false;
  67635. /**
  67636. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  67637. * @type {BABYLON.Observable}
  67638. */
  67639. this.onUpdateParameters = new BABYLON.Observable();
  67640. }
  67641. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  67642. /**
  67643. * Gets wether the color curves effect is enabled.
  67644. */
  67645. get: function () {
  67646. return this._colorCurvesEnabled;
  67647. },
  67648. /**
  67649. * Sets wether the color curves effect is enabled.
  67650. */
  67651. set: function (value) {
  67652. if (this._colorCurvesEnabled === value) {
  67653. return;
  67654. }
  67655. this._colorCurvesEnabled = value;
  67656. this._updateParameters();
  67657. },
  67658. enumerable: true,
  67659. configurable: true
  67660. });
  67661. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  67662. /**
  67663. * Gets wether the color grading effect is enabled.
  67664. */
  67665. get: function () {
  67666. return this._colorGradingEnabled;
  67667. },
  67668. /**
  67669. * Sets wether the color grading effect is enabled.
  67670. */
  67671. set: function (value) {
  67672. if (this._colorGradingEnabled === value) {
  67673. return;
  67674. }
  67675. this._colorGradingEnabled = value;
  67676. this._updateParameters();
  67677. },
  67678. enumerable: true,
  67679. configurable: true
  67680. });
  67681. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  67682. /**
  67683. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  67684. */
  67685. get: function () {
  67686. return this._colorGradingWithGreenDepth;
  67687. },
  67688. /**
  67689. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  67690. */
  67691. set: function (value) {
  67692. if (this._colorGradingWithGreenDepth === value) {
  67693. return;
  67694. }
  67695. this._colorGradingWithGreenDepth = value;
  67696. this._updateParameters();
  67697. },
  67698. enumerable: true,
  67699. configurable: true
  67700. });
  67701. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  67702. /**
  67703. * Gets wether the color grading texture contains BGR values.
  67704. */
  67705. get: function () {
  67706. return this._colorGradingBGR;
  67707. },
  67708. /**
  67709. * Sets wether the color grading texture contains BGR values.
  67710. */
  67711. set: function (value) {
  67712. if (this._colorGradingBGR === value) {
  67713. return;
  67714. }
  67715. this._colorGradingBGR = value;
  67716. this._updateParameters();
  67717. },
  67718. enumerable: true,
  67719. configurable: true
  67720. });
  67721. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  67722. /**
  67723. * Gets the Exposure used in the effect.
  67724. */
  67725. get: function () {
  67726. return this._exposure;
  67727. },
  67728. /**
  67729. * Sets the Exposure used in the effect.
  67730. */
  67731. set: function (value) {
  67732. if (this._exposure === value) {
  67733. return;
  67734. }
  67735. this._exposure = value;
  67736. this._updateParameters();
  67737. },
  67738. enumerable: true,
  67739. configurable: true
  67740. });
  67741. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  67742. /**
  67743. * Gets wether the tone mapping effect is enabled.
  67744. */
  67745. get: function () {
  67746. return this._toneMappingEnabled;
  67747. },
  67748. /**
  67749. * Sets wether the tone mapping effect is enabled.
  67750. */
  67751. set: function (value) {
  67752. if (this._toneMappingEnabled === value) {
  67753. return;
  67754. }
  67755. this._toneMappingEnabled = value;
  67756. this._updateParameters();
  67757. },
  67758. enumerable: true,
  67759. configurable: true
  67760. });
  67761. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  67762. /**
  67763. * Gets the contrast used in the effect.
  67764. */
  67765. get: function () {
  67766. return this._contrast;
  67767. },
  67768. /**
  67769. * Sets the contrast used in the effect.
  67770. */
  67771. set: function (value) {
  67772. if (this._contrast === value) {
  67773. return;
  67774. }
  67775. this._contrast = value;
  67776. this._updateParameters();
  67777. },
  67778. enumerable: true,
  67779. configurable: true
  67780. });
  67781. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  67782. /**
  67783. * Gets the vignette blend mode allowing different kind of effect.
  67784. */
  67785. get: function () {
  67786. return this._vignetteBlendMode;
  67787. },
  67788. /**
  67789. * Sets the vignette blend mode allowing different kind of effect.
  67790. */
  67791. set: function (value) {
  67792. if (this._vignetteBlendMode === value) {
  67793. return;
  67794. }
  67795. this._vignetteBlendMode = value;
  67796. this._updateParameters();
  67797. },
  67798. enumerable: true,
  67799. configurable: true
  67800. });
  67801. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  67802. /**
  67803. * Gets wether the vignette effect is enabled.
  67804. */
  67805. get: function () {
  67806. return this._vignetteEnabled;
  67807. },
  67808. /**
  67809. * Sets wether the vignette effect is enabled.
  67810. */
  67811. set: function (value) {
  67812. if (this._vignetteEnabled === value) {
  67813. return;
  67814. }
  67815. this._vignetteEnabled = value;
  67816. this._updateParameters();
  67817. },
  67818. enumerable: true,
  67819. configurable: true
  67820. });
  67821. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  67822. /**
  67823. * Gets wether the image processing is applied through a post process or not.
  67824. */
  67825. get: function () {
  67826. return this._applyByPostProcess;
  67827. },
  67828. /**
  67829. * Sets wether the image processing is applied through a post process or not.
  67830. */
  67831. set: function (value) {
  67832. if (this._applyByPostProcess === value) {
  67833. return;
  67834. }
  67835. this._applyByPostProcess = value;
  67836. this._updateParameters();
  67837. },
  67838. enumerable: true,
  67839. configurable: true
  67840. });
  67841. /**
  67842. * Method called each time the image processing information changes requires to recompile the effect.
  67843. */
  67844. ImageProcessingConfiguration.prototype._updateParameters = function () {
  67845. this.onUpdateParameters.notifyObservers(this);
  67846. };
  67847. ImageProcessingConfiguration.prototype.getClassName = function () {
  67848. return "ImageProcessingConfiguration";
  67849. };
  67850. /**
  67851. * Prepare the list of uniforms associated with the Image Processing effects.
  67852. * @param uniformsList The list of uniforms used in the effect
  67853. * @param defines the list of defines currently in use
  67854. */
  67855. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  67856. if (defines.EXPOSURE) {
  67857. uniforms.push("exposureLinear");
  67858. }
  67859. if (defines.CONTRAST) {
  67860. uniforms.push("contrast");
  67861. }
  67862. if (defines.COLORGRADING) {
  67863. uniforms.push("colorTransformSettings");
  67864. }
  67865. if (defines.VIGNETTE) {
  67866. uniforms.push("vInverseScreenSize");
  67867. uniforms.push("vignetteSettings1");
  67868. uniforms.push("vignetteSettings2");
  67869. }
  67870. if (defines.COLORCURVES) {
  67871. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  67872. }
  67873. };
  67874. /**
  67875. * Prepare the list of samplers associated with the Image Processing effects.
  67876. * @param uniformsList The list of uniforms used in the effect
  67877. * @param defines the list of defines currently in use
  67878. */
  67879. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  67880. if (defines.COLORGRADING) {
  67881. samplersList.push("txColorTransform");
  67882. }
  67883. };
  67884. /**
  67885. * Prepare the list of defines associated to the shader.
  67886. * @param defines the list of defines to complete
  67887. */
  67888. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  67889. defines.VIGNETTE = this.vignetteEnabled;
  67890. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  67891. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  67892. defines.TONEMAPPING = this.toneMappingEnabled;
  67893. defines.CONTRAST = (this.contrast !== 1.0);
  67894. defines.EXPOSURE = (this.exposure !== 1.0);
  67895. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  67896. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  67897. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  67898. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  67899. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  67900. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  67901. };
  67902. /**
  67903. * Returns true if all the image processing information are ready.
  67904. */
  67905. ImageProcessingConfiguration.prototype.isReady = function () {
  67906. // Color Grading texure can not be none blocking.
  67907. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  67908. };
  67909. /**
  67910. * Binds the image processing to the shader.
  67911. * @param effect The effect to bind to
  67912. */
  67913. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  67914. if (aspectRatio === void 0) { aspectRatio = 1; }
  67915. // Color Curves
  67916. if (this._colorCurvesEnabled) {
  67917. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  67918. }
  67919. // Vignette
  67920. if (this._vignetteEnabled) {
  67921. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  67922. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  67923. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  67924. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  67925. var vignetteScaleX = vignetteScaleY * aspectRatio;
  67926. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  67927. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  67928. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  67929. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  67930. var vignettePower = -2.0 * this.vignetteWeight;
  67931. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  67932. }
  67933. // Exposure
  67934. effect.setFloat("exposureLinear", this.exposure);
  67935. // Contrast
  67936. effect.setFloat("contrast", this.contrast);
  67937. // Color transform settings
  67938. if (this.colorGradingTexture) {
  67939. effect.setTexture("txColorTransform", this.colorGradingTexture);
  67940. var textureSize = this.colorGradingTexture.getSize().height;
  67941. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  67942. 0.5 / textureSize, // textureOffset
  67943. textureSize, // textureSize
  67944. this.colorGradingTexture.level // weight
  67945. );
  67946. }
  67947. };
  67948. /**
  67949. * Clones the current image processing instance.
  67950. * @return The cloned image processing
  67951. */
  67952. ImageProcessingConfiguration.prototype.clone = function () {
  67953. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  67954. };
  67955. /**
  67956. * Serializes the current image processing instance to a json representation.
  67957. * @return a JSON representation
  67958. */
  67959. ImageProcessingConfiguration.prototype.serialize = function () {
  67960. return BABYLON.SerializationHelper.Serialize(this);
  67961. };
  67962. /**
  67963. * Parses the image processing from a json representation.
  67964. * @param source the JSON source to parse
  67965. * @return The parsed image processing
  67966. */
  67967. ImageProcessingConfiguration.Parse = function (source) {
  67968. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  67969. };
  67970. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  67971. /**
  67972. * Used to apply the vignette as a mix with the pixel color.
  67973. */
  67974. get: function () {
  67975. return this._VIGNETTEMODE_MULTIPLY;
  67976. },
  67977. enumerable: true,
  67978. configurable: true
  67979. });
  67980. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  67981. /**
  67982. * Used to apply the vignette as a replacement of the pixel color.
  67983. */
  67984. get: function () {
  67985. return this._VIGNETTEMODE_OPAQUE;
  67986. },
  67987. enumerable: true,
  67988. configurable: true
  67989. });
  67990. return ImageProcessingConfiguration;
  67991. }());
  67992. // Static constants associated to the image processing.
  67993. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  67994. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  67995. __decorate([
  67996. BABYLON.serializeAsColorCurves()
  67997. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  67998. __decorate([
  67999. BABYLON.serialize()
  68000. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  68001. __decorate([
  68002. BABYLON.serializeAsTexture()
  68003. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  68004. __decorate([
  68005. BABYLON.serialize()
  68006. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  68007. __decorate([
  68008. BABYLON.serialize()
  68009. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  68010. __decorate([
  68011. BABYLON.serialize()
  68012. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  68013. __decorate([
  68014. BABYLON.serialize()
  68015. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  68016. __decorate([
  68017. BABYLON.serialize()
  68018. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  68019. __decorate([
  68020. BABYLON.serialize()
  68021. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  68022. __decorate([
  68023. BABYLON.serialize()
  68024. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  68025. __decorate([
  68026. BABYLON.serialize()
  68027. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  68028. __decorate([
  68029. BABYLON.serialize()
  68030. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  68031. __decorate([
  68032. BABYLON.serialize()
  68033. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  68034. __decorate([
  68035. BABYLON.serializeAsColor4()
  68036. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  68037. __decorate([
  68038. BABYLON.serialize()
  68039. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  68040. __decorate([
  68041. BABYLON.serialize()
  68042. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  68043. __decorate([
  68044. BABYLON.serialize()
  68045. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  68046. __decorate([
  68047. BABYLON.serialize()
  68048. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  68049. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  68050. })(BABYLON || (BABYLON = {}));
  68051. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  68052. var BABYLON;
  68053. (function (BABYLON) {
  68054. var serializedGeometries = [];
  68055. var serializeGeometry = function (geometry, serializationGeometries) {
  68056. if (serializedGeometries[geometry.id]) {
  68057. return;
  68058. }
  68059. if (geometry.doNotSerialize) {
  68060. return;
  68061. }
  68062. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  68063. serializationGeometries.boxes.push(geometry.serialize());
  68064. }
  68065. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  68066. serializationGeometries.spheres.push(geometry.serialize());
  68067. }
  68068. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  68069. serializationGeometries.cylinders.push(geometry.serialize());
  68070. }
  68071. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  68072. serializationGeometries.toruses.push(geometry.serialize());
  68073. }
  68074. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  68075. serializationGeometries.grounds.push(geometry.serialize());
  68076. }
  68077. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  68078. serializationGeometries.planes.push(geometry.serialize());
  68079. }
  68080. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  68081. serializationGeometries.torusKnots.push(geometry.serialize());
  68082. }
  68083. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  68084. throw new Error("Unknown primitive type");
  68085. }
  68086. else {
  68087. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  68088. }
  68089. serializedGeometries[geometry.id] = true;
  68090. };
  68091. var serializeMesh = function (mesh, serializationScene) {
  68092. var serializationObject = {};
  68093. // Geometry
  68094. var geometry = mesh._geometry;
  68095. if (geometry) {
  68096. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  68097. // 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
  68098. serializeGeometry(geometry, serializationScene.geometries);
  68099. }
  68100. }
  68101. // Custom
  68102. if (mesh.serialize) {
  68103. mesh.serialize(serializationObject);
  68104. }
  68105. return serializationObject;
  68106. };
  68107. var finalizeSingleMesh = function (mesh, serializationObject) {
  68108. //only works if the mesh is already loaded
  68109. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  68110. //serialize material
  68111. if (mesh.material) {
  68112. if (mesh.material instanceof BABYLON.StandardMaterial) {
  68113. serializationObject.materials = serializationObject.materials || [];
  68114. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  68115. serializationObject.materials.push(mesh.material.serialize());
  68116. }
  68117. }
  68118. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  68119. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  68120. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  68121. serializationObject.multiMaterials.push(mesh.material.serialize());
  68122. }
  68123. }
  68124. }
  68125. //serialize geometry
  68126. var geometry = mesh._geometry;
  68127. if (geometry) {
  68128. if (!serializationObject.geometries) {
  68129. serializationObject.geometries = {};
  68130. serializationObject.geometries.boxes = [];
  68131. serializationObject.geometries.spheres = [];
  68132. serializationObject.geometries.cylinders = [];
  68133. serializationObject.geometries.toruses = [];
  68134. serializationObject.geometries.grounds = [];
  68135. serializationObject.geometries.planes = [];
  68136. serializationObject.geometries.torusKnots = [];
  68137. serializationObject.geometries.vertexData = [];
  68138. }
  68139. serializeGeometry(geometry, serializationObject.geometries);
  68140. }
  68141. // Skeletons
  68142. if (mesh.skeleton) {
  68143. serializationObject.skeletons = serializationObject.skeletons || [];
  68144. serializationObject.skeletons.push(mesh.skeleton.serialize());
  68145. }
  68146. //serialize the actual mesh
  68147. serializationObject.meshes = serializationObject.meshes || [];
  68148. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  68149. }
  68150. };
  68151. var SceneSerializer = (function () {
  68152. function SceneSerializer() {
  68153. }
  68154. SceneSerializer.ClearCache = function () {
  68155. serializedGeometries = [];
  68156. };
  68157. SceneSerializer.Serialize = function (scene) {
  68158. var serializationObject = {};
  68159. SceneSerializer.ClearCache();
  68160. // Scene
  68161. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  68162. serializationObject.autoClear = scene.autoClear;
  68163. serializationObject.clearColor = scene.clearColor.asArray();
  68164. serializationObject.ambientColor = scene.ambientColor.asArray();
  68165. serializationObject.gravity = scene.gravity.asArray();
  68166. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  68167. serializationObject.workerCollisions = scene.workerCollisions;
  68168. // Fog
  68169. if (scene.fogMode && scene.fogMode !== 0) {
  68170. serializationObject.fogMode = scene.fogMode;
  68171. serializationObject.fogColor = scene.fogColor.asArray();
  68172. serializationObject.fogStart = scene.fogStart;
  68173. serializationObject.fogEnd = scene.fogEnd;
  68174. serializationObject.fogDensity = scene.fogDensity;
  68175. }
  68176. //Physics
  68177. if (scene.isPhysicsEnabled()) {
  68178. serializationObject.physicsEnabled = true;
  68179. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  68180. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  68181. }
  68182. // Metadata
  68183. if (scene.metadata) {
  68184. serializationObject.metadata = scene.metadata;
  68185. }
  68186. // Morph targets
  68187. serializationObject.morphTargetManagers = [];
  68188. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  68189. var abstractMesh = _a[_i];
  68190. var manager = abstractMesh.morphTargetManager;
  68191. if (manager) {
  68192. serializationObject.morphTargetManagers.push(manager.serialize());
  68193. }
  68194. }
  68195. // Lights
  68196. serializationObject.lights = [];
  68197. var index;
  68198. var light;
  68199. for (index = 0; index < scene.lights.length; index++) {
  68200. light = scene.lights[index];
  68201. if (!light.doNotSerialize) {
  68202. serializationObject.lights.push(light.serialize());
  68203. }
  68204. }
  68205. // Cameras
  68206. serializationObject.cameras = [];
  68207. for (index = 0; index < scene.cameras.length; index++) {
  68208. var camera = scene.cameras[index];
  68209. if (!camera.doNotSerialize) {
  68210. serializationObject.cameras.push(camera.serialize());
  68211. }
  68212. }
  68213. if (scene.activeCamera) {
  68214. serializationObject.activeCameraID = scene.activeCamera.id;
  68215. }
  68216. // Animations
  68217. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  68218. // Materials
  68219. serializationObject.materials = [];
  68220. serializationObject.multiMaterials = [];
  68221. var material;
  68222. for (index = 0; index < scene.materials.length; index++) {
  68223. material = scene.materials[index];
  68224. if (!material.doNotSerialize) {
  68225. serializationObject.materials.push(material.serialize());
  68226. }
  68227. }
  68228. // MultiMaterials
  68229. serializationObject.multiMaterials = [];
  68230. for (index = 0; index < scene.multiMaterials.length; index++) {
  68231. var multiMaterial = scene.multiMaterials[index];
  68232. serializationObject.multiMaterials.push(multiMaterial.serialize());
  68233. }
  68234. // Skeletons
  68235. serializationObject.skeletons = [];
  68236. for (index = 0; index < scene.skeletons.length; index++) {
  68237. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  68238. }
  68239. // Geometries
  68240. serializationObject.geometries = {};
  68241. serializationObject.geometries.boxes = [];
  68242. serializationObject.geometries.spheres = [];
  68243. serializationObject.geometries.cylinders = [];
  68244. serializationObject.geometries.toruses = [];
  68245. serializationObject.geometries.grounds = [];
  68246. serializationObject.geometries.planes = [];
  68247. serializationObject.geometries.torusKnots = [];
  68248. serializationObject.geometries.vertexData = [];
  68249. serializedGeometries = [];
  68250. var geometries = scene.getGeometries();
  68251. for (index = 0; index < geometries.length; index++) {
  68252. var geometry = geometries[index];
  68253. if (geometry.isReady()) {
  68254. serializeGeometry(geometry, serializationObject.geometries);
  68255. }
  68256. }
  68257. // Meshes
  68258. serializationObject.meshes = [];
  68259. for (index = 0; index < scene.meshes.length; index++) {
  68260. var abstractMesh = scene.meshes[index];
  68261. if (abstractMesh instanceof BABYLON.Mesh) {
  68262. var mesh = abstractMesh;
  68263. if (!mesh.doNotSerialize) {
  68264. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  68265. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  68266. }
  68267. }
  68268. }
  68269. }
  68270. // Particles Systems
  68271. serializationObject.particleSystems = [];
  68272. for (index = 0; index < scene.particleSystems.length; index++) {
  68273. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  68274. }
  68275. // Lens flares
  68276. serializationObject.lensFlareSystems = [];
  68277. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  68278. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  68279. }
  68280. // Shadows
  68281. serializationObject.shadowGenerators = [];
  68282. for (index = 0; index < scene.lights.length; index++) {
  68283. light = scene.lights[index];
  68284. var shadowGenerator = light.getShadowGenerator();
  68285. if (shadowGenerator) {
  68286. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  68287. }
  68288. }
  68289. // Action Manager
  68290. if (scene.actionManager) {
  68291. serializationObject.actions = scene.actionManager.serialize("scene");
  68292. }
  68293. // Audio
  68294. serializationObject.sounds = [];
  68295. for (index = 0; index < scene.soundTracks.length; index++) {
  68296. var soundtrack = scene.soundTracks[index];
  68297. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  68298. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  68299. }
  68300. }
  68301. return serializationObject;
  68302. };
  68303. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  68304. if (withParents === void 0) { withParents = false; }
  68305. if (withChildren === void 0) { withChildren = false; }
  68306. var serializationObject = {};
  68307. SceneSerializer.ClearCache();
  68308. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  68309. if (withParents || withChildren) {
  68310. //deliberate for loop! not for each, appended should be processed as well.
  68311. for (var i = 0; i < toSerialize.length; ++i) {
  68312. if (withChildren) {
  68313. toSerialize[i].getDescendants().forEach(function (node) {
  68314. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  68315. toSerialize.push(node);
  68316. }
  68317. });
  68318. }
  68319. //make sure the array doesn't contain the object already
  68320. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  68321. toSerialize.push(toSerialize[i].parent);
  68322. }
  68323. }
  68324. }
  68325. toSerialize.forEach(function (mesh) {
  68326. finalizeSingleMesh(mesh, serializationObject);
  68327. });
  68328. return serializationObject;
  68329. };
  68330. return SceneSerializer;
  68331. }());
  68332. BABYLON.SceneSerializer = SceneSerializer;
  68333. })(BABYLON || (BABYLON = {}));
  68334. //# sourceMappingURL=babylon.sceneSerializer.js.map
  68335. var BABYLON;
  68336. (function (BABYLON) {
  68337. var ReflectionProbe = (function () {
  68338. function ReflectionProbe(name, size, scene, generateMipMaps) {
  68339. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68340. var _this = this;
  68341. this.name = name;
  68342. this._viewMatrix = BABYLON.Matrix.Identity();
  68343. this._target = BABYLON.Vector3.Zero();
  68344. this._add = BABYLON.Vector3.Zero();
  68345. this.invertYAxis = false;
  68346. this.position = BABYLON.Vector3.Zero();
  68347. this._scene = scene;
  68348. this._scene.reflectionProbes.push(this);
  68349. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  68350. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  68351. switch (faceIndex) {
  68352. case 0:
  68353. _this._add.copyFromFloats(1, 0, 0);
  68354. break;
  68355. case 1:
  68356. _this._add.copyFromFloats(-1, 0, 0);
  68357. break;
  68358. case 2:
  68359. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  68360. break;
  68361. case 3:
  68362. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  68363. break;
  68364. case 4:
  68365. _this._add.copyFromFloats(0, 0, 1);
  68366. break;
  68367. case 5:
  68368. _this._add.copyFromFloats(0, 0, -1);
  68369. break;
  68370. }
  68371. if (_this._attachedMesh) {
  68372. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  68373. }
  68374. _this.position.addToRef(_this._add, _this._target);
  68375. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  68376. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  68377. });
  68378. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  68379. scene.updateTransformMatrix(true);
  68380. });
  68381. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68382. }
  68383. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  68384. get: function () {
  68385. return this._renderTargetTexture.samples;
  68386. },
  68387. set: function (value) {
  68388. this._renderTargetTexture.samples = value;
  68389. },
  68390. enumerable: true,
  68391. configurable: true
  68392. });
  68393. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  68394. get: function () {
  68395. return this._renderTargetTexture.refreshRate;
  68396. },
  68397. set: function (value) {
  68398. this._renderTargetTexture.refreshRate = value;
  68399. },
  68400. enumerable: true,
  68401. configurable: true
  68402. });
  68403. ReflectionProbe.prototype.getScene = function () {
  68404. return this._scene;
  68405. };
  68406. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  68407. get: function () {
  68408. return this._renderTargetTexture;
  68409. },
  68410. enumerable: true,
  68411. configurable: true
  68412. });
  68413. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  68414. get: function () {
  68415. return this._renderTargetTexture.renderList;
  68416. },
  68417. enumerable: true,
  68418. configurable: true
  68419. });
  68420. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  68421. this._attachedMesh = mesh;
  68422. };
  68423. /**
  68424. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  68425. *
  68426. * @param renderingGroupId The rendering group id corresponding to its index
  68427. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  68428. */
  68429. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  68430. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  68431. };
  68432. ReflectionProbe.prototype.dispose = function () {
  68433. var index = this._scene.reflectionProbes.indexOf(this);
  68434. if (index !== -1) {
  68435. // Remove from the scene if found
  68436. this._scene.reflectionProbes.splice(index, 1);
  68437. }
  68438. if (this._renderTargetTexture) {
  68439. this._renderTargetTexture.dispose();
  68440. this._renderTargetTexture = null;
  68441. }
  68442. };
  68443. return ReflectionProbe;
  68444. }());
  68445. BABYLON.ReflectionProbe = ReflectionProbe;
  68446. })(BABYLON || (BABYLON = {}));
  68447. //# sourceMappingURL=babylon.reflectionProbe.js.map
  68448. var BABYLON;
  68449. (function (BABYLON) {
  68450. var Layer = (function () {
  68451. function Layer(name, imgUrl, scene, isBackground, color) {
  68452. this.name = name;
  68453. this.scale = new BABYLON.Vector2(1, 1);
  68454. this.offset = new BABYLON.Vector2(0, 0);
  68455. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  68456. this.layerMask = 0x0FFFFFFF;
  68457. this._vertexBuffers = {};
  68458. // Events
  68459. /**
  68460. * An event triggered when the layer is disposed.
  68461. * @type {BABYLON.Observable}
  68462. */
  68463. this.onDisposeObservable = new BABYLON.Observable();
  68464. /**
  68465. * An event triggered before rendering the scene
  68466. * @type {BABYLON.Observable}
  68467. */
  68468. this.onBeforeRenderObservable = new BABYLON.Observable();
  68469. /**
  68470. * An event triggered after rendering the scene
  68471. * @type {BABYLON.Observable}
  68472. */
  68473. this.onAfterRenderObservable = new BABYLON.Observable();
  68474. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  68475. this.isBackground = isBackground === undefined ? true : isBackground;
  68476. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  68477. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68478. this._scene.layers.push(this);
  68479. var engine = this._scene.getEngine();
  68480. // VBO
  68481. var vertices = [];
  68482. vertices.push(1, 1);
  68483. vertices.push(-1, 1);
  68484. vertices.push(-1, -1);
  68485. vertices.push(1, -1);
  68486. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  68488. // Indices
  68489. var indices = [];
  68490. indices.push(0);
  68491. indices.push(1);
  68492. indices.push(2);
  68493. indices.push(0);
  68494. indices.push(2);
  68495. indices.push(3);
  68496. this._indexBuffer = engine.createIndexBuffer(indices);
  68497. // Effects
  68498. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  68499. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  68500. }
  68501. Object.defineProperty(Layer.prototype, "onDispose", {
  68502. set: function (callback) {
  68503. if (this._onDisposeObserver) {
  68504. this.onDisposeObservable.remove(this._onDisposeObserver);
  68505. }
  68506. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  68507. },
  68508. enumerable: true,
  68509. configurable: true
  68510. });
  68511. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  68512. set: function (callback) {
  68513. if (this._onBeforeRenderObserver) {
  68514. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68515. }
  68516. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68517. },
  68518. enumerable: true,
  68519. configurable: true
  68520. });
  68521. Object.defineProperty(Layer.prototype, "onAfterRender", {
  68522. set: function (callback) {
  68523. if (this._onAfterRenderObserver) {
  68524. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68525. }
  68526. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68527. },
  68528. enumerable: true,
  68529. configurable: true
  68530. });
  68531. Layer.prototype.render = function () {
  68532. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  68533. // Check
  68534. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  68535. return;
  68536. var engine = this._scene.getEngine();
  68537. this.onBeforeRenderObservable.notifyObservers(this);
  68538. // Render
  68539. engine.enableEffect(currentEffect);
  68540. engine.setState(false);
  68541. // Texture
  68542. currentEffect.setTexture("textureSampler", this.texture);
  68543. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  68544. // Color
  68545. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  68546. // Scale / offset
  68547. currentEffect.setVector2("offset", this.offset);
  68548. currentEffect.setVector2("scale", this.scale);
  68549. // VBOs
  68550. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  68551. // Draw order
  68552. if (!this.alphaTest) {
  68553. engine.setAlphaMode(this.alphaBlendingMode);
  68554. engine.draw(true, 0, 6);
  68555. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68556. }
  68557. else {
  68558. engine.draw(true, 0, 6);
  68559. }
  68560. this.onAfterRenderObservable.notifyObservers(this);
  68561. };
  68562. Layer.prototype.dispose = function () {
  68563. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68564. if (vertexBuffer) {
  68565. vertexBuffer.dispose();
  68566. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68567. }
  68568. if (this._indexBuffer) {
  68569. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68570. this._indexBuffer = null;
  68571. }
  68572. if (this.texture) {
  68573. this.texture.dispose();
  68574. this.texture = null;
  68575. }
  68576. // Remove from scene
  68577. var index = this._scene.layers.indexOf(this);
  68578. this._scene.layers.splice(index, 1);
  68579. // Callback
  68580. this.onDisposeObservable.notifyObservers(this);
  68581. this.onDisposeObservable.clear();
  68582. this.onAfterRenderObservable.clear();
  68583. this.onBeforeRenderObservable.clear();
  68584. };
  68585. return Layer;
  68586. }());
  68587. BABYLON.Layer = Layer;
  68588. })(BABYLON || (BABYLON = {}));
  68589. //# sourceMappingURL=babylon.layer.js.map
  68590. var BABYLON;
  68591. (function (BABYLON) {
  68592. var TextureTools = (function () {
  68593. function TextureTools() {
  68594. }
  68595. /**
  68596. * Uses the GPU to create a copy texture rescaled at a given size
  68597. * @param texture Texture to copy from
  68598. * @param width Desired width
  68599. * @param height Desired height
  68600. * @return Generated texture
  68601. */
  68602. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  68603. if (useBilinearMode === void 0) { useBilinearMode = true; }
  68604. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  68605. var scene = texture.getScene();
  68606. var engine = scene.getEngine();
  68607. rtt.wrapU = texture.wrapU;
  68608. rtt.wrapV = texture.wrapV;
  68609. rtt.uOffset = texture.uOffset;
  68610. rtt.vOffset = texture.vOffset;
  68611. rtt.uScale = texture.uScale;
  68612. rtt.vScale = texture.vScale;
  68613. rtt.uAng = texture.uAng;
  68614. rtt.vAng = texture.vAng;
  68615. rtt.wAng = texture.wAng;
  68616. rtt.coordinatesIndex = texture.coordinatesIndex;
  68617. rtt.level = texture.level;
  68618. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  68619. rtt._texture.isReady = false;
  68620. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68621. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68622. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68623. passPostProcess.getEffect().executeWhenCompiled(function () {
  68624. passPostProcess.onApply = function (effect) {
  68625. effect.setTexture("textureSampler", texture);
  68626. };
  68627. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  68628. engine.unBindFramebuffer(rtt.getInternalTexture());
  68629. rtt.disposeFramebufferObjects();
  68630. passPostProcess.dispose();
  68631. rtt._texture.isReady = true;
  68632. });
  68633. return rtt;
  68634. };
  68635. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  68636. if (!scene._environmentBRDFTexture) {
  68637. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68638. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68639. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68640. scene._environmentBRDFTexture = texture;
  68641. }
  68642. return scene._environmentBRDFTexture;
  68643. };
  68644. return TextureTools;
  68645. }());
  68646. 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=";
  68647. BABYLON.TextureTools = TextureTools;
  68648. })(BABYLON || (BABYLON = {}));
  68649. //# sourceMappingURL=babylon.textureTools.js.map
  68650. 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}"};
  68651. 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};"};
  68652. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  68653. module.exports = BABYLON;
  68654. };