babylon.max.js 3.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var Color3 = (function () {
  23. /**
  24. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  25. */
  26. function Color3(r, g, b) {
  27. if (r === void 0) { r = 0; }
  28. if (g === void 0) { g = 0; }
  29. if (b === void 0) { b = 0; }
  30. this.r = r;
  31. this.g = g;
  32. this.b = b;
  33. }
  34. /**
  35. * Returns a string with the Color3 current values.
  36. */
  37. Color3.prototype.toString = function () {
  38. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  39. };
  40. /**
  41. * Returns the string "Color3".
  42. */
  43. Color3.prototype.getClassName = function () {
  44. return "Color3";
  45. };
  46. /**
  47. * Returns the Color3 hash code.
  48. */
  49. Color3.prototype.getHashCode = function () {
  50. var hash = this.r || 0;
  51. hash = (hash * 397) ^ (this.g || 0);
  52. hash = (hash * 397) ^ (this.b || 0);
  53. return hash;
  54. };
  55. // Operators
  56. /**
  57. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  58. * Returns the Color3.
  59. */
  60. Color3.prototype.toArray = function (array, index) {
  61. if (index === undefined) {
  62. index = 0;
  63. }
  64. array[index] = this.r;
  65. array[index + 1] = this.g;
  66. array[index + 2] = this.b;
  67. return this;
  68. };
  69. /**
  70. * Returns a new Color4 object from the current Color3 and the passed alpha.
  71. */
  72. Color3.prototype.toColor4 = function (alpha) {
  73. if (alpha === void 0) { alpha = 1; }
  74. return new Color4(this.r, this.g, this.b, alpha);
  75. };
  76. /**
  77. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  78. */
  79. Color3.prototype.asArray = function () {
  80. var result = [];
  81. this.toArray(result, 0);
  82. return result;
  83. };
  84. /**
  85. * Returns the luminance value (float).
  86. */
  87. Color3.prototype.toLuminance = function () {
  88. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  89. };
  90. /**
  91. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  92. * Returns this new object.
  93. */
  94. Color3.prototype.multiply = function (otherColor) {
  95. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  96. };
  97. /**
  98. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  99. * Returns the current Color3.
  100. */
  101. Color3.prototype.multiplyToRef = function (otherColor, result) {
  102. result.r = this.r * otherColor.r;
  103. result.g = this.g * otherColor.g;
  104. result.b = this.b * otherColor.b;
  105. return this;
  106. };
  107. /**
  108. * Boolean : True if the rgb values are equal to the passed ones.
  109. */
  110. Color3.prototype.equals = function (otherColor) {
  111. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  112. };
  113. /**
  114. * Boolean : True if the rgb values are equal to the passed ones.
  115. */
  116. Color3.prototype.equalsFloats = function (r, g, b) {
  117. return this.r === r && this.g === g && this.b === b;
  118. };
  119. /**
  120. * Multiplies in place each rgb value by scale.
  121. * Returns the updated Color3.
  122. */
  123. Color3.prototype.scale = function (scale) {
  124. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  125. };
  126. /**
  127. * Multiplies the rgb values by scale and stores the result into "result".
  128. * Returns the unmodified current Color3.
  129. */
  130. Color3.prototype.scaleToRef = function (scale, result) {
  131. result.r = this.r * scale;
  132. result.g = this.g * scale;
  133. result.b = this.b * scale;
  134. return this;
  135. };
  136. /**
  137. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  138. */
  139. Color3.prototype.add = function (otherColor) {
  140. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  141. };
  142. /**
  143. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  144. * Returns the unmodified current Color3.
  145. */
  146. Color3.prototype.addToRef = function (otherColor, result) {
  147. result.r = this.r + otherColor.r;
  148. result.g = this.g + otherColor.g;
  149. result.b = this.b + otherColor.b;
  150. return this;
  151. };
  152. /**
  153. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  154. */
  155. Color3.prototype.subtract = function (otherColor) {
  156. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  157. };
  158. /**
  159. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  160. * Returns the unmodified current Color3.
  161. */
  162. Color3.prototype.subtractToRef = function (otherColor, result) {
  163. result.r = this.r - otherColor.r;
  164. result.g = this.g - otherColor.g;
  165. result.b = this.b - otherColor.b;
  166. return this;
  167. };
  168. /**
  169. * Returns a new Color3 copied the current one.
  170. */
  171. Color3.prototype.clone = function () {
  172. return new Color3(this.r, this.g, this.b);
  173. };
  174. /**
  175. * Copies the rgb values from the source in the current Color3.
  176. * Returns the updated Color3.
  177. */
  178. Color3.prototype.copyFrom = function (source) {
  179. this.r = source.r;
  180. this.g = source.g;
  181. this.b = source.b;
  182. return this;
  183. };
  184. /**
  185. * Updates the Color3 rgb values from the passed floats.
  186. * Returns the Color3.
  187. */
  188. Color3.prototype.copyFromFloats = function (r, g, b) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. };
  194. /**
  195. * Updates the Color3 rgb values from the passed floats.
  196. * Returns the Color3.
  197. */
  198. Color3.prototype.set = function (r, g, b) {
  199. return this.copyFromFloats(r, g, b);
  200. };
  201. /**
  202. * Returns the Color3 hexadecimal code as a string.
  203. */
  204. Color3.prototype.toHexString = function () {
  205. var intR = (this.r * 255) | 0;
  206. var intG = (this.g * 255) | 0;
  207. var intB = (this.b * 255) | 0;
  208. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  209. };
  210. /**
  211. * Returns a new Color3 converted to linear space.
  212. */
  213. Color3.prototype.toLinearSpace = function () {
  214. var convertedColor = new Color3();
  215. this.toLinearSpaceToRef(convertedColor);
  216. return convertedColor;
  217. };
  218. /**
  219. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  220. * Returns the unmodified Color3.
  221. */
  222. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  223. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  224. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  225. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  226. return this;
  227. };
  228. /**
  229. * Returns a new Color3 converted to gamma space.
  230. */
  231. Color3.prototype.toGammaSpace = function () {
  232. var convertedColor = new Color3();
  233. this.toGammaSpaceToRef(convertedColor);
  234. return convertedColor;
  235. };
  236. /**
  237. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  238. * Returns the unmodified Color3.
  239. */
  240. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  241. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  242. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  243. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  244. return this;
  245. };
  246. // Statics
  247. /**
  248. * Creates a new Color3 from the string containing valid hexadecimal values.
  249. */
  250. Color3.FromHexString = function (hex) {
  251. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  252. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  253. return new Color3(0, 0, 0);
  254. }
  255. var r = parseInt(hex.substring(1, 3), 16);
  256. var g = parseInt(hex.substring(3, 5), 16);
  257. var b = parseInt(hex.substring(5, 7), 16);
  258. return Color3.FromInts(r, g, b);
  259. };
  260. /**
  261. * Creates a new Vector3 from the startind index of the passed array.
  262. */
  263. Color3.FromArray = function (array, offset) {
  264. if (offset === void 0) { offset = 0; }
  265. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  266. };
  267. /**
  268. * Creates a new Color3 from integer values ( < 256).
  269. */
  270. Color3.FromInts = function (r, g, b) {
  271. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  272. };
  273. /**
  274. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  275. */
  276. Color3.Lerp = function (start, end, amount) {
  277. var r = start.r + ((end.r - start.r) * amount);
  278. var g = start.g + ((end.g - start.g) * amount);
  279. var b = start.b + ((end.b - start.b) * amount);
  280. return new Color3(r, g, b);
  281. };
  282. Color3.Red = function () { return new Color3(1, 0, 0); };
  283. Color3.Green = function () { return new Color3(0, 1, 0); };
  284. Color3.Blue = function () { return new Color3(0, 0, 1); };
  285. Color3.Black = function () { return new Color3(0, 0, 0); };
  286. Color3.White = function () { return new Color3(1, 1, 1); };
  287. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  288. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  289. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  290. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  291. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  292. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  293. return Color3;
  294. }());
  295. BABYLON.Color3 = Color3;
  296. var Color4 = (function () {
  297. /**
  298. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  299. */
  300. function Color4(r, g, b, a) {
  301. if (r === void 0) { r = 0; }
  302. if (g === void 0) { g = 0; }
  303. if (b === void 0) { b = 0; }
  304. if (a === void 0) { a = 1; }
  305. this.r = r;
  306. this.g = g;
  307. this.b = b;
  308. this.a = a;
  309. }
  310. // Operators
  311. /**
  312. * Adds in place the passed Color4 values to the current Color4.
  313. * Returns the updated Color4.
  314. */
  315. Color4.prototype.addInPlace = function (right) {
  316. this.r += right.r;
  317. this.g += right.g;
  318. this.b += right.b;
  319. this.a += right.a;
  320. return this;
  321. };
  322. /**
  323. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  324. */
  325. Color4.prototype.asArray = function () {
  326. var result = [];
  327. this.toArray(result, 0);
  328. return result;
  329. };
  330. /**
  331. * Stores from the starting index in the passed array the Color4 successive values.
  332. * Returns the Color4.
  333. */
  334. Color4.prototype.toArray = function (array, index) {
  335. if (index === undefined) {
  336. index = 0;
  337. }
  338. array[index] = this.r;
  339. array[index + 1] = this.g;
  340. array[index + 2] = this.b;
  341. array[index + 3] = this.a;
  342. return this;
  343. };
  344. /**
  345. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  346. */
  347. Color4.prototype.add = function (right) {
  348. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  349. };
  350. /**
  351. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  352. */
  353. Color4.prototype.subtract = function (right) {
  354. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  355. };
  356. /**
  357. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  358. * Returns the Color4.
  359. */
  360. Color4.prototype.subtractToRef = function (right, result) {
  361. result.r = this.r - right.r;
  362. result.g = this.g - right.g;
  363. result.b = this.b - right.b;
  364. result.a = this.a - right.a;
  365. return this;
  366. };
  367. /**
  368. * Creates a new Color4 with the current Color4 values multiplied by scale.
  369. */
  370. Color4.prototype.scale = function (scale) {
  371. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  372. };
  373. /**
  374. * Multiplies the current Color4 values by scale and stores the result in "result".
  375. * Returns the Color4.
  376. */
  377. Color4.prototype.scaleToRef = function (scale, result) {
  378. result.r = this.r * scale;
  379. result.g = this.g * scale;
  380. result.b = this.b * scale;
  381. result.a = this.a * scale;
  382. return this;
  383. };
  384. /**
  385. * Multipy an RGBA Color4 value by another and return a new Color4 object
  386. * @param color The Color4 (RGBA) value to multiply by
  387. * @returns A new Color4.
  388. */
  389. Color4.prototype.multiply = function (color) {
  390. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  391. };
  392. /**
  393. * Multipy an RGBA Color4 value by another and push the result in a reference value
  394. * @param color The Color4 (RGBA) value to multiply by
  395. * @param result The Color4 (RGBA) to fill the result in
  396. * @returns the result Color4.
  397. */
  398. Color4.prototype.multiplyToRef = function (color, result) {
  399. result.r = this.r * color.r;
  400. result.g = this.g * color.g;
  401. result.b = this.b * color.b;
  402. result.a = this.a * color.a;
  403. return result;
  404. };
  405. /**
  406. * Returns a string with the Color4 values.
  407. */
  408. Color4.prototype.toString = function () {
  409. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  410. };
  411. /**
  412. * Returns the string "Color4"
  413. */
  414. Color4.prototype.getClassName = function () {
  415. return "Color4";
  416. };
  417. /**
  418. * Return the Color4 hash code as a number.
  419. */
  420. Color4.prototype.getHashCode = function () {
  421. var hash = this.r || 0;
  422. hash = (hash * 397) ^ (this.g || 0);
  423. hash = (hash * 397) ^ (this.b || 0);
  424. hash = (hash * 397) ^ (this.a || 0);
  425. return hash;
  426. };
  427. /**
  428. * Creates a new Color4 copied from the current one.
  429. */
  430. Color4.prototype.clone = function () {
  431. return new Color4(this.r, this.g, this.b, this.a);
  432. };
  433. /**
  434. * Copies the passed Color4 values into the current one.
  435. * Returns the updated Color4.
  436. */
  437. Color4.prototype.copyFrom = function (source) {
  438. this.r = source.r;
  439. this.g = source.g;
  440. this.b = source.b;
  441. this.a = source.a;
  442. return this;
  443. };
  444. /**
  445. * Copies the passed float values into the current one.
  446. * Returns the updated Color4.
  447. */
  448. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  449. this.r = r;
  450. this.g = g;
  451. this.b = b;
  452. this.a = a;
  453. return this;
  454. };
  455. /**
  456. * Copies the passed float values into the current one.
  457. * Returns the updated Color4.
  458. */
  459. Color4.prototype.set = function (r, g, b, a) {
  460. return this.copyFromFloats(r, g, b, a);
  461. };
  462. /**
  463. * Returns a string containing the hexadecimal Color4 code.
  464. */
  465. Color4.prototype.toHexString = function () {
  466. var intR = (this.r * 255) | 0;
  467. var intG = (this.g * 255) | 0;
  468. var intB = (this.b * 255) | 0;
  469. var intA = (this.a * 255) | 0;
  470. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  471. };
  472. /**
  473. * Returns a new Color4 converted to linear space.
  474. */
  475. Color4.prototype.toLinearSpace = function () {
  476. var convertedColor = new Color4();
  477. this.toLinearSpaceToRef(convertedColor);
  478. return convertedColor;
  479. };
  480. /**
  481. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  482. * Returns the unmodified Color4.
  483. */
  484. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  485. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  486. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  487. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  488. convertedColor.a = this.a;
  489. return this;
  490. };
  491. /**
  492. * Returns a new Color4 converted to gamma space.
  493. */
  494. Color4.prototype.toGammaSpace = function () {
  495. var convertedColor = new Color4();
  496. this.toGammaSpaceToRef(convertedColor);
  497. return convertedColor;
  498. };
  499. /**
  500. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  501. * Returns the unmodified Color4.
  502. */
  503. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  504. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  505. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  506. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  507. convertedColor.a = this.a;
  508. return this;
  509. };
  510. // Statics
  511. /**
  512. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  513. */
  514. Color4.FromHexString = function (hex) {
  515. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  516. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  517. return new Color4(0.0, 0.0, 0.0, 0.0);
  518. }
  519. var r = parseInt(hex.substring(1, 3), 16);
  520. var g = parseInt(hex.substring(3, 5), 16);
  521. var b = parseInt(hex.substring(5, 7), 16);
  522. var a = parseInt(hex.substring(7, 9), 16);
  523. return Color4.FromInts(r, g, b, a);
  524. };
  525. /**
  526. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  527. */
  528. Color4.Lerp = function (left, right, amount) {
  529. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  530. Color4.LerpToRef(left, right, amount, result);
  531. return result;
  532. };
  533. /**
  534. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  535. */
  536. Color4.LerpToRef = function (left, right, amount, result) {
  537. result.r = left.r + (right.r - left.r) * amount;
  538. result.g = left.g + (right.g - left.g) * amount;
  539. result.b = left.b + (right.b - left.b) * amount;
  540. result.a = left.a + (right.a - left.a) * amount;
  541. };
  542. /**
  543. * Creates a new Color4 from the starting index element of the passed array.
  544. */
  545. Color4.FromArray = function (array, offset) {
  546. if (offset === void 0) { offset = 0; }
  547. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  548. };
  549. /**
  550. * Creates a new Color4 from the passed integers ( < 256 ).
  551. */
  552. Color4.FromInts = function (r, g, b, a) {
  553. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  554. };
  555. Color4.CheckColors4 = function (colors, count) {
  556. // Check if color3 was used
  557. if (colors.length === count * 3) {
  558. var colors4 = [];
  559. for (var index = 0; index < colors.length; index += 3) {
  560. var newIndex = (index / 3) * 4;
  561. colors4[newIndex] = colors[index];
  562. colors4[newIndex + 1] = colors[index + 1];
  563. colors4[newIndex + 2] = colors[index + 2];
  564. colors4[newIndex + 3] = 1.0;
  565. }
  566. return colors4;
  567. }
  568. return colors;
  569. };
  570. return Color4;
  571. }());
  572. BABYLON.Color4 = Color4;
  573. var Vector2 = (function () {
  574. /**
  575. * Creates a new Vector2 from the passed x and y coordinates.
  576. */
  577. function Vector2(x, y) {
  578. this.x = x;
  579. this.y = y;
  580. }
  581. /**
  582. * Returns a string with the Vector2 coordinates.
  583. */
  584. Vector2.prototype.toString = function () {
  585. return "{X: " + this.x + " Y:" + this.y + "}";
  586. };
  587. /**
  588. * Returns the string "Vector2"
  589. */
  590. Vector2.prototype.getClassName = function () {
  591. return "Vector2";
  592. };
  593. /**
  594. * Returns the Vector2 hash code as a number.
  595. */
  596. Vector2.prototype.getHashCode = function () {
  597. var hash = this.x || 0;
  598. hash = (hash * 397) ^ (this.y || 0);
  599. return hash;
  600. };
  601. // Operators
  602. /**
  603. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  604. * Returns the Vector2.
  605. */
  606. Vector2.prototype.toArray = function (array, index) {
  607. if (index === void 0) { index = 0; }
  608. array[index] = this.x;
  609. array[index + 1] = this.y;
  610. return this;
  611. };
  612. /**
  613. * Returns a new array with 2 elements : the Vector2 coordinates.
  614. */
  615. Vector2.prototype.asArray = function () {
  616. var result = [];
  617. this.toArray(result, 0);
  618. return result;
  619. };
  620. /**
  621. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  622. * Returns the updated Vector2.
  623. */
  624. Vector2.prototype.copyFrom = function (source) {
  625. this.x = source.x;
  626. this.y = source.y;
  627. return this;
  628. };
  629. /**
  630. * Sets the Vector2 coordinates with the passed floats.
  631. * Returns the updated Vector2.
  632. */
  633. Vector2.prototype.copyFromFloats = function (x, y) {
  634. this.x = x;
  635. this.y = y;
  636. return this;
  637. };
  638. /**
  639. * Sets the Vector2 coordinates with the passed floats.
  640. * Returns the updated Vector2.
  641. */
  642. Vector2.prototype.set = function (x, y) {
  643. return this.copyFromFloats(x, y);
  644. };
  645. /**
  646. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  647. */
  648. Vector2.prototype.add = function (otherVector) {
  649. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  650. };
  651. /**
  652. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  653. * Returns the Vector2.
  654. */
  655. Vector2.prototype.addToRef = function (otherVector, result) {
  656. result.x = this.x + otherVector.x;
  657. result.y = this.y + otherVector.y;
  658. return this;
  659. };
  660. /**
  661. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.addInPlace = function (otherVector) {
  665. this.x += otherVector.x;
  666. this.y += otherVector.y;
  667. return this;
  668. };
  669. /**
  670. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  671. */
  672. Vector2.prototype.addVector3 = function (otherVector) {
  673. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  674. };
  675. /**
  676. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  677. */
  678. Vector2.prototype.subtract = function (otherVector) {
  679. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  680. };
  681. /**
  682. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  683. * Returns the Vector2.
  684. */
  685. Vector2.prototype.subtractToRef = function (otherVector, result) {
  686. result.x = this.x - otherVector.x;
  687. result.y = this.y - otherVector.y;
  688. return this;
  689. };
  690. /**
  691. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  692. * Returns the updated Vector2.
  693. */
  694. Vector2.prototype.subtractInPlace = function (otherVector) {
  695. this.x -= otherVector.x;
  696. this.y -= otherVector.y;
  697. return this;
  698. };
  699. /**
  700. * Multiplies in place the current Vector2 coordinates by the passed ones.
  701. * Returns the updated Vector2.
  702. */
  703. Vector2.prototype.multiplyInPlace = function (otherVector) {
  704. this.x *= otherVector.x;
  705. this.y *= otherVector.y;
  706. return this;
  707. };
  708. /**
  709. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  710. */
  711. Vector2.prototype.multiply = function (otherVector) {
  712. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  713. };
  714. /**
  715. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  716. * Returns the Vector2.
  717. */
  718. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  719. result.x = this.x * otherVector.x;
  720. result.y = this.y * otherVector.y;
  721. return this;
  722. };
  723. /**
  724. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  725. */
  726. Vector2.prototype.multiplyByFloats = function (x, y) {
  727. return new Vector2(this.x * x, this.y * y);
  728. };
  729. /**
  730. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  731. */
  732. Vector2.prototype.divide = function (otherVector) {
  733. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  734. };
  735. /**
  736. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  737. * Returns the Vector2.
  738. */
  739. Vector2.prototype.divideToRef = function (otherVector, result) {
  740. result.x = this.x / otherVector.x;
  741. result.y = this.y / otherVector.y;
  742. return this;
  743. };
  744. /**
  745. * Returns a new Vector2 with current Vector2 negated coordinates.
  746. */
  747. Vector2.prototype.negate = function () {
  748. return new Vector2(-this.x, -this.y);
  749. };
  750. /**
  751. * Multiply the Vector2 coordinates by scale.
  752. * Returns the updated Vector2.
  753. */
  754. Vector2.prototype.scaleInPlace = function (scale) {
  755. this.x *= scale;
  756. this.y *= scale;
  757. return this;
  758. };
  759. /**
  760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  761. */
  762. Vector2.prototype.scale = function (scale) {
  763. return new Vector2(this.x * scale, this.y * scale);
  764. };
  765. /**
  766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  767. */
  768. Vector2.prototype.equals = function (otherVector) {
  769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  770. };
  771. /**
  772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  773. */
  774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  777. };
  778. // Properties
  779. /**
  780. * Returns the vector length (float).
  781. */
  782. Vector2.prototype.length = function () {
  783. return Math.sqrt(this.x * this.x + this.y * this.y);
  784. };
  785. /**
  786. * Returns the vector squared length (float);
  787. */
  788. Vector2.prototype.lengthSquared = function () {
  789. return (this.x * this.x + this.y * this.y);
  790. };
  791. // Methods
  792. /**
  793. * Normalize the vector.
  794. * Returns the updated Vector2.
  795. */
  796. Vector2.prototype.normalize = function () {
  797. var len = this.length();
  798. if (len === 0)
  799. return this;
  800. var num = 1.0 / len;
  801. this.x *= num;
  802. this.y *= num;
  803. return this;
  804. };
  805. /**
  806. * Returns a new Vector2 copied from the Vector2.
  807. */
  808. Vector2.prototype.clone = function () {
  809. return new Vector2(this.x, this.y);
  810. };
  811. // Statics
  812. /**
  813. * Returns a new Vector2(0, 0)
  814. */
  815. Vector2.Zero = function () {
  816. return new Vector2(0, 0);
  817. };
  818. /**
  819. * Returns a new Vector2(1, 1)
  820. */
  821. Vector2.One = function () {
  822. return new Vector2(1, 1);
  823. };
  824. /**
  825. * Returns a new Vector2 set from the passed index element of the passed array.
  826. */
  827. Vector2.FromArray = function (array, offset) {
  828. if (offset === void 0) { offset = 0; }
  829. return new Vector2(array[offset], array[offset + 1]);
  830. };
  831. /**
  832. * Sets "result" from the passed index element of the passed array.
  833. */
  834. Vector2.FromArrayToRef = function (array, offset, result) {
  835. result.x = array[offset];
  836. result.y = array[offset + 1];
  837. };
  838. /**
  839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  840. */
  841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  842. var squared = amount * amount;
  843. var cubed = amount * squared;
  844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  850. return new Vector2(x, y);
  851. };
  852. /**
  853. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  856. */
  857. Vector2.Clamp = function (value, min, max) {
  858. var x = value.x;
  859. x = (x > max.x) ? max.x : x;
  860. x = (x < min.x) ? min.x : x;
  861. var y = value.y;
  862. y = (y > max.y) ? max.y : y;
  863. y = (y < min.y) ? min.y : y;
  864. return new Vector2(x, y);
  865. };
  866. /**
  867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  868. */
  869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  870. var squared = amount * amount;
  871. var cubed = amount * squared;
  872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  874. var part3 = (cubed - (2.0 * squared)) + amount;
  875. var part4 = cubed - squared;
  876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  882. */
  883. Vector2.Lerp = function (start, end, amount) {
  884. var x = start.x + ((end.x - start.x) * amount);
  885. var y = start.y + ((end.y - start.y) * amount);
  886. return new Vector2(x, y);
  887. };
  888. /**
  889. * Returns the dot product (float) of the vector "left" and the vector "right".
  890. */
  891. Vector2.Dot = function (left, right) {
  892. return left.x * right.x + left.y * right.y;
  893. };
  894. /**
  895. * Returns a new Vector2 equal to the normalized passed vector.
  896. */
  897. Vector2.Normalize = function (vector) {
  898. var newVector = vector.clone();
  899. newVector.normalize();
  900. return newVector;
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Minimize = function (left, right) {
  906. var x = (left.x < right.x) ? left.x : right.x;
  907. var y = (left.y < right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  912. */
  913. Vector2.Maximize = function (left, right) {
  914. var x = (left.x > right.x) ? left.x : right.x;
  915. var y = (left.y > right.y) ? left.y : right.y;
  916. return new Vector2(x, y);
  917. };
  918. /**
  919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  920. */
  921. Vector2.Transform = function (vector, transformation) {
  922. var r = Vector2.Zero();
  923. Vector2.TransformToRef(vector, transformation, r);
  924. return r;
  925. };
  926. /**
  927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  928. */
  929. Vector2.TransformToRef = function (vector, transformation, result) {
  930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  932. result.x = x;
  933. result.y = y;
  934. };
  935. /**
  936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  937. */
  938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  940. var sign = a < 0 ? -1 : 1;
  941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  944. };
  945. /**
  946. * Returns the distance (float) between the vectors "value1" and "value2".
  947. */
  948. Vector2.Distance = function (value1, value2) {
  949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  950. };
  951. /**
  952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  953. */
  954. Vector2.DistanceSquared = function (value1, value2) {
  955. var x = value1.x - value2.x;
  956. var y = value1.y - value2.y;
  957. return (x * x) + (y * y);
  958. };
  959. /**
  960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  961. */
  962. Vector2.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. /**
  968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  969. */
  970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  971. var l2 = Vector2.DistanceSquared(segA, segB);
  972. if (l2 === 0.0) {
  973. return Vector2.Distance(p, segA);
  974. }
  975. var v = segB.subtract(segA);
  976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  977. var proj = segA.add(v.multiplyByFloats(t, t));
  978. return Vector2.Distance(p, proj);
  979. };
  980. return Vector2;
  981. }());
  982. BABYLON.Vector2 = Vector2;
  983. var Vector3 = (function () {
  984. /**
  985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  986. * A Vector3 is the main object used in 3D geometry.
  987. * It can represent etiher the coordinates of a point the space, either a direction.
  988. */
  989. function Vector3(x, y, z) {
  990. this.x = x;
  991. this.y = y;
  992. this.z = z;
  993. }
  994. /**
  995. * Returns a string with the Vector3 coordinates.
  996. */
  997. Vector3.prototype.toString = function () {
  998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  999. };
  1000. /**
  1001. * Returns the string "Vector3"
  1002. */
  1003. Vector3.prototype.getClassName = function () {
  1004. return "Vector3";
  1005. };
  1006. /**
  1007. * Returns the Vector hash code.
  1008. */
  1009. Vector3.prototype.getHashCode = function () {
  1010. var hash = this.x || 0;
  1011. hash = (hash * 397) ^ (this.y || 0);
  1012. hash = (hash * 397) ^ (this.z || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Returns a new array with three elements : the coordinates the Vector3.
  1018. */
  1019. Vector3.prototype.asArray = function () {
  1020. var result = [];
  1021. this.toArray(result, 0);
  1022. return result;
  1023. };
  1024. /**
  1025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1026. * Returns the Vector3.
  1027. */
  1028. Vector3.prototype.toArray = function (array, index) {
  1029. if (index === void 0) { index = 0; }
  1030. array[index] = this.x;
  1031. array[index + 1] = this.y;
  1032. array[index + 2] = this.z;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1037. */
  1038. Vector3.prototype.toQuaternion = function () {
  1039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1044. var cosy = Math.cos(this.y * 0.5);
  1045. var siny = Math.sin(this.y * 0.5);
  1046. result.x = coszMinusx * siny;
  1047. result.y = -sinzMinusx * siny;
  1048. result.z = sinxPlusz * cosy;
  1049. result.w = cosxPlusz * cosy;
  1050. return result;
  1051. };
  1052. /**
  1053. * Adds the passed vector to the current Vector3.
  1054. * Returns the updated Vector3.
  1055. */
  1056. Vector3.prototype.addInPlace = function (otherVector) {
  1057. this.x += otherVector.x;
  1058. this.y += otherVector.y;
  1059. this.z += otherVector.z;
  1060. return this;
  1061. };
  1062. /**
  1063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1064. */
  1065. Vector3.prototype.add = function (otherVector) {
  1066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1067. };
  1068. /**
  1069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1070. * Returns the current Vector3.
  1071. */
  1072. Vector3.prototype.addToRef = function (otherVector, result) {
  1073. result.x = this.x + otherVector.x;
  1074. result.y = this.y + otherVector.y;
  1075. result.z = this.z + otherVector.z;
  1076. return this;
  1077. };
  1078. /**
  1079. * Subtract the passed vector from the current Vector3.
  1080. * Returns the updated Vector3.
  1081. */
  1082. Vector3.prototype.subtractInPlace = function (otherVector) {
  1083. this.x -= otherVector.x;
  1084. this.y -= otherVector.y;
  1085. this.z -= otherVector.z;
  1086. return this;
  1087. };
  1088. /**
  1089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1090. */
  1091. Vector3.prototype.subtract = function (otherVector) {
  1092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1093. };
  1094. /**
  1095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1096. * Returns the current Vector3.
  1097. */
  1098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1099. result.x = this.x - otherVector.x;
  1100. result.y = this.y - otherVector.y;
  1101. result.z = this.z - otherVector.z;
  1102. return this;
  1103. };
  1104. /**
  1105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1106. */
  1107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1108. return new Vector3(this.x - x, this.y - y, this.z - z);
  1109. };
  1110. /**
  1111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1112. * Returns the current Vector3.
  1113. */
  1114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1115. result.x = this.x - x;
  1116. result.y = this.y - y;
  1117. result.z = this.z - z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1122. */
  1123. Vector3.prototype.negate = function () {
  1124. return new Vector3(-this.x, -this.y, -this.z);
  1125. };
  1126. /**
  1127. * Multiplies the Vector3 coordinates by the float "scale".
  1128. * Returns the updated Vector3.
  1129. */
  1130. Vector3.prototype.scaleInPlace = function (scale) {
  1131. this.x *= scale;
  1132. this.y *= scale;
  1133. this.z *= scale;
  1134. return this;
  1135. };
  1136. /**
  1137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1138. */
  1139. Vector3.prototype.scale = function (scale) {
  1140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1141. };
  1142. /**
  1143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1144. * Returns the current Vector3.
  1145. */
  1146. Vector3.prototype.scaleToRef = function (scale, result) {
  1147. result.x = this.x * scale;
  1148. result.y = this.y * scale;
  1149. result.z = this.z * scale;
  1150. return this;
  1151. };
  1152. /**
  1153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1154. */
  1155. Vector3.prototype.equals = function (otherVector) {
  1156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1157. };
  1158. /**
  1159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1160. */
  1161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1163. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1164. };
  1165. /**
  1166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1167. */
  1168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1169. return this.x === x && this.y === y && this.z === z;
  1170. };
  1171. /**
  1172. * Muliplies the current Vector3 coordinates by the passed ones.
  1173. * Returns the updated Vector3.
  1174. */
  1175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1176. this.x *= otherVector.x;
  1177. this.y *= otherVector.y;
  1178. this.z *= otherVector.z;
  1179. return this;
  1180. };
  1181. /**
  1182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1183. */
  1184. Vector3.prototype.multiply = function (otherVector) {
  1185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1186. };
  1187. /**
  1188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1189. * Returns the current Vector3.
  1190. */
  1191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1192. result.x = this.x * otherVector.x;
  1193. result.y = this.y * otherVector.y;
  1194. result.z = this.z * otherVector.z;
  1195. return this;
  1196. };
  1197. /**
  1198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1199. */
  1200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1201. return new Vector3(this.x * x, this.y * y, this.z * z);
  1202. };
  1203. /**
  1204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1205. */
  1206. Vector3.prototype.divide = function (otherVector) {
  1207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1208. };
  1209. /**
  1210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1211. * Returns the current Vector3.
  1212. */
  1213. Vector3.prototype.divideToRef = function (otherVector, result) {
  1214. result.x = this.x / otherVector.x;
  1215. result.y = this.y / otherVector.y;
  1216. result.z = this.z / otherVector.z;
  1217. return this;
  1218. };
  1219. /**
  1220. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.MinimizeInPlace = function (other) {
  1224. if (other.x < this.x)
  1225. this.x = other.x;
  1226. if (other.y < this.y)
  1227. this.y = other.y;
  1228. if (other.z < this.z)
  1229. this.z = other.z;
  1230. return this;
  1231. };
  1232. /**
  1233. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1234. * Returns the updated Vector3.
  1235. */
  1236. Vector3.prototype.MaximizeInPlace = function (other) {
  1237. if (other.x > this.x)
  1238. this.x = other.x;
  1239. if (other.y > this.y)
  1240. this.y = other.y;
  1241. if (other.z > this.z)
  1242. this.z = other.z;
  1243. return this;
  1244. };
  1245. // Properties
  1246. /**
  1247. * Returns the length of the Vector3 (float).
  1248. */
  1249. Vector3.prototype.length = function () {
  1250. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1251. };
  1252. /**
  1253. * Returns the squared length of the Vector3 (float).
  1254. */
  1255. Vector3.prototype.lengthSquared = function () {
  1256. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1257. };
  1258. // Methods
  1259. /**
  1260. * Normalize the current Vector3.
  1261. * Returns the updated Vector3.
  1262. */
  1263. Vector3.prototype.normalize = function () {
  1264. var len = this.length();
  1265. if (len === 0 || len === 1.0)
  1266. return this;
  1267. var num = 1.0 / len;
  1268. this.x *= num;
  1269. this.y *= num;
  1270. this.z *= num;
  1271. return this;
  1272. };
  1273. /**
  1274. * Returns a new Vector3 copied from the current Vector3.
  1275. */
  1276. Vector3.prototype.clone = function () {
  1277. return new Vector3(this.x, this.y, this.z);
  1278. };
  1279. /**
  1280. * Copies the passed vector coordinates to the current Vector3 ones.
  1281. * Returns the updated Vector3.
  1282. */
  1283. Vector3.prototype.copyFrom = function (source) {
  1284. this.x = source.x;
  1285. this.y = source.y;
  1286. this.z = source.z;
  1287. return this;
  1288. };
  1289. /**
  1290. * Copies the passed floats to the current Vector3 coordinates.
  1291. * Returns the updated Vector3.
  1292. */
  1293. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. return this;
  1298. };
  1299. /**
  1300. * Copies the passed floats to the current Vector3 coordinates.
  1301. * Returns the updated Vector3.
  1302. */
  1303. Vector3.prototype.set = function (x, y, z) {
  1304. return this.copyFromFloats(x, y, z);
  1305. };
  1306. // Statics
  1307. /**
  1308. *
  1309. */
  1310. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1311. var d0 = Vector3.Dot(vector0, axis) - size;
  1312. var d1 = Vector3.Dot(vector1, axis) - size;
  1313. var s = d0 / (d0 - d1);
  1314. return s;
  1315. };
  1316. /**
  1317. * Returns a new Vector3 set from the index "offset" of the passed array.
  1318. */
  1319. Vector3.FromArray = function (array, offset) {
  1320. if (!offset) {
  1321. offset = 0;
  1322. }
  1323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1324. };
  1325. /**
  1326. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1327. * This function is deprecated. Use FromArray instead.
  1328. */
  1329. Vector3.FromFloatArray = function (array, offset) {
  1330. return Vector3.FromArray(array, offset);
  1331. };
  1332. /**
  1333. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1334. */
  1335. Vector3.FromArrayToRef = function (array, offset, result) {
  1336. result.x = array[offset];
  1337. result.y = array[offset + 1];
  1338. result.z = array[offset + 2];
  1339. };
  1340. /**
  1341. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1342. * This function is deprecated. Use FromArrayToRef instead.
  1343. */
  1344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1345. return Vector3.FromArrayToRef(array, offset, result);
  1346. };
  1347. /**
  1348. * Sets the passed vector "result" with the passed floats.
  1349. */
  1350. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1351. result.x = x;
  1352. result.y = y;
  1353. result.z = z;
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1357. */
  1358. Vector3.Zero = function () {
  1359. return new Vector3(0.0, 0.0, 0.0);
  1360. };
  1361. /**
  1362. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1363. */
  1364. Vector3.One = function () {
  1365. return new Vector3(1.0, 1.0, 1.0);
  1366. };
  1367. /**
  1368. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1369. */
  1370. Vector3.Up = function () {
  1371. return new Vector3(0.0, 1.0, 0.0);
  1372. };
  1373. /**
  1374. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1375. */
  1376. Vector3.Forward = function () {
  1377. return new Vector3(0.0, 0.0, 1.0);
  1378. };
  1379. /**
  1380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1381. */
  1382. Vector3.Right = function () {
  1383. return new Vector3(1.0, 0.0, 0.0);
  1384. };
  1385. /**
  1386. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1387. */
  1388. Vector3.Left = function () {
  1389. return new Vector3(-1.0, 0.0, 0.0);
  1390. };
  1391. /**
  1392. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1393. * This method computes tranformed coordinates only, not transformed direction vectors.
  1394. */
  1395. Vector3.TransformCoordinates = function (vector, transformation) {
  1396. var result = Vector3.Zero();
  1397. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1398. return result;
  1399. };
  1400. /**
  1401. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1402. * This method computes tranformed coordinates only, not transformed direction vectors.
  1403. */
  1404. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1408. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1409. result.x = x / w;
  1410. result.y = y / w;
  1411. result.z = z / w;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1418. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1419. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1420. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1421. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1422. result.x = rx / rw;
  1423. result.y = ry / rw;
  1424. result.z = rz / rw;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1428. * This methods computes transformed normalized direction vectors only.
  1429. */
  1430. Vector3.TransformNormal = function (vector, transformation) {
  1431. var result = Vector3.Zero();
  1432. Vector3.TransformNormalToRef(vector, transformation, result);
  1433. return result;
  1434. };
  1435. /**
  1436. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1437. * This methods computes transformed normalized direction vectors only.
  1438. */
  1439. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1443. result.x = x;
  1444. result.y = y;
  1445. result.z = z;
  1446. };
  1447. /**
  1448. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1449. * This methods computes transformed normalized direction vectors only.
  1450. */
  1451. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1452. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1453. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1454. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1455. };
  1456. /**
  1457. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1458. */
  1459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1460. var squared = amount * amount;
  1461. var cubed = amount * squared;
  1462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1471. return new Vector3(x, y, z);
  1472. };
  1473. /**
  1474. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1477. */
  1478. Vector3.Clamp = function (value, min, max) {
  1479. var x = value.x;
  1480. x = (x > max.x) ? max.x : x;
  1481. x = (x < min.x) ? min.x : x;
  1482. var y = value.y;
  1483. y = (y > max.y) ? max.y : y;
  1484. y = (y < min.y) ? min.y : y;
  1485. var z = value.z;
  1486. z = (z > max.z) ? max.z : z;
  1487. z = (z < min.z) ? min.z : z;
  1488. return new Vector3(x, y, z);
  1489. };
  1490. /**
  1491. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1492. */
  1493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1494. var squared = amount * amount;
  1495. var cubed = amount * squared;
  1496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1498. var part3 = (cubed - (2.0 * squared)) + amount;
  1499. var part4 = cubed - squared;
  1500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1503. return new Vector3(x, y, z);
  1504. };
  1505. /**
  1506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1507. */
  1508. Vector3.Lerp = function (start, end, amount) {
  1509. var result = new Vector3(0, 0, 0);
  1510. Vector3.LerpToRef(start, end, amount, result);
  1511. return result;
  1512. };
  1513. /**
  1514. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1515. */
  1516. Vector3.LerpToRef = function (start, end, amount, result) {
  1517. result.x = start.x + ((end.x - start.x) * amount);
  1518. result.y = start.y + ((end.y - start.y) * amount);
  1519. result.z = start.z + ((end.z - start.z) * amount);
  1520. };
  1521. /**
  1522. * Returns the dot product (float) between the vectors "left" and "right".
  1523. */
  1524. Vector3.Dot = function (left, right) {
  1525. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1526. };
  1527. /**
  1528. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1529. * The cross product is then orthogonal to both "left" and "right".
  1530. */
  1531. Vector3.Cross = function (left, right) {
  1532. var result = Vector3.Zero();
  1533. Vector3.CrossToRef(left, right, result);
  1534. return result;
  1535. };
  1536. /**
  1537. * Sets the passed vector "result" with the cross product of "left" and "right".
  1538. * The cross product is then orthogonal to both "left" and "right".
  1539. */
  1540. Vector3.CrossToRef = function (left, right, result) {
  1541. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1542. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1543. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1544. result.copyFrom(MathTmp.Vector3[0]);
  1545. };
  1546. /**
  1547. * Returns a new Vector3 as the normalization of the passed vector.
  1548. */
  1549. Vector3.Normalize = function (vector) {
  1550. var result = Vector3.Zero();
  1551. Vector3.NormalizeToRef(vector, result);
  1552. return result;
  1553. };
  1554. /**
  1555. * Sets the passed vector "result" with the normalization of the passed first vector.
  1556. */
  1557. Vector3.NormalizeToRef = function (vector, result) {
  1558. result.copyFrom(vector);
  1559. result.normalize();
  1560. };
  1561. Vector3.Project = function (vector, world, transform, viewport) {
  1562. var cw = viewport.width;
  1563. var ch = viewport.height;
  1564. var cx = viewport.x;
  1565. var cy = viewport.y;
  1566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1567. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1568. var matrix = MathTmp.Matrix[0];
  1569. world.multiplyToRef(transform, matrix);
  1570. matrix.multiplyToRef(viewportMatrix, matrix);
  1571. return Vector3.TransformCoordinates(vector, matrix);
  1572. };
  1573. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1574. var matrix = MathTmp.Matrix[0];
  1575. world.multiplyToRef(transform, matrix);
  1576. matrix.invert();
  1577. source.x = source.x / viewportWidth * 2 - 1;
  1578. source.y = -(source.y / viewportHeight * 2 - 1);
  1579. var vector = Vector3.TransformCoordinates(source, matrix);
  1580. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1581. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1582. vector = vector.scale(1.0 / num);
  1583. }
  1584. return vector;
  1585. };
  1586. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1587. var matrix = MathTmp.Matrix[0];
  1588. world.multiplyToRef(view, matrix);
  1589. matrix.multiplyToRef(projection, matrix);
  1590. matrix.invert();
  1591. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1592. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1593. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1594. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Minimize = function (left, right) {
  1600. var min = left.clone();
  1601. min.MinimizeInPlace(right);
  1602. return min;
  1603. };
  1604. Vector3.Maximize = function (left, right) {
  1605. var max = left.clone();
  1606. max.MaximizeInPlace(right);
  1607. return max;
  1608. };
  1609. /**
  1610. * Returns the distance (float) between the vectors "value1" and "value2".
  1611. */
  1612. Vector3.Distance = function (value1, value2) {
  1613. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1614. };
  1615. /**
  1616. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1617. */
  1618. Vector3.DistanceSquared = function (value1, value2) {
  1619. var x = value1.x - value2.x;
  1620. var y = value1.y - value2.y;
  1621. var z = value1.z - value2.z;
  1622. return (x * x) + (y * y) + (z * z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 located at the center between "value1" and "value2".
  1626. */
  1627. Vector3.Center = function (value1, value2) {
  1628. var center = value1.add(value2);
  1629. center.scaleInPlace(0.5);
  1630. return center;
  1631. };
  1632. /**
  1633. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1634. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1635. * to something in order to rotate it from its local system to the given target system.
  1636. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1637. * Returns a new Vector3.
  1638. */
  1639. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1640. var rotation = Vector3.Zero();
  1641. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1642. return rotation;
  1643. };
  1644. /**
  1645. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1646. */
  1647. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1648. var quat = MathTmp.Quaternion[0];
  1649. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1650. quat.toEulerAnglesToRef(ref);
  1651. };
  1652. return Vector3;
  1653. }());
  1654. BABYLON.Vector3 = Vector3;
  1655. //Vector4 class created for EulerAngle class conversion to Quaternion
  1656. var Vector4 = (function () {
  1657. /**
  1658. * Creates a Vector4 object from the passed floats.
  1659. */
  1660. function Vector4(x, y, z, w) {
  1661. this.x = x;
  1662. this.y = y;
  1663. this.z = z;
  1664. this.w = w;
  1665. }
  1666. /**
  1667. * Returns the string with the Vector4 coordinates.
  1668. */
  1669. Vector4.prototype.toString = function () {
  1670. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1671. };
  1672. /**
  1673. * Returns the string "Vector4".
  1674. */
  1675. Vector4.prototype.getClassName = function () {
  1676. return "Vector4";
  1677. };
  1678. /**
  1679. * Returns the Vector4 hash code.
  1680. */
  1681. Vector4.prototype.getHashCode = function () {
  1682. var hash = this.x || 0;
  1683. hash = (hash * 397) ^ (this.y || 0);
  1684. hash = (hash * 397) ^ (this.z || 0);
  1685. hash = (hash * 397) ^ (this.w || 0);
  1686. return hash;
  1687. };
  1688. // Operators
  1689. /**
  1690. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1691. */
  1692. Vector4.prototype.asArray = function () {
  1693. var result = [];
  1694. this.toArray(result, 0);
  1695. return result;
  1696. };
  1697. /**
  1698. * Populates the passed array from the passed index with the Vector4 coordinates.
  1699. * Returns the Vector4.
  1700. */
  1701. Vector4.prototype.toArray = function (array, index) {
  1702. if (index === undefined) {
  1703. index = 0;
  1704. }
  1705. array[index] = this.x;
  1706. array[index + 1] = this.y;
  1707. array[index + 2] = this.z;
  1708. array[index + 3] = this.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Adds the passed vector to the current Vector4.
  1713. * Returns the updated Vector4.
  1714. */
  1715. Vector4.prototype.addInPlace = function (otherVector) {
  1716. this.x += otherVector.x;
  1717. this.y += otherVector.y;
  1718. this.z += otherVector.z;
  1719. this.w += otherVector.w;
  1720. return this;
  1721. };
  1722. /**
  1723. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1724. */
  1725. Vector4.prototype.add = function (otherVector) {
  1726. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1727. };
  1728. /**
  1729. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1730. * Returns the current Vector4.
  1731. */
  1732. Vector4.prototype.addToRef = function (otherVector, result) {
  1733. result.x = this.x + otherVector.x;
  1734. result.y = this.y + otherVector.y;
  1735. result.z = this.z + otherVector.z;
  1736. result.w = this.w + otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Subtract in place the passed vector from the current Vector4.
  1741. * Returns the updated Vector4.
  1742. */
  1743. Vector4.prototype.subtractInPlace = function (otherVector) {
  1744. this.x -= otherVector.x;
  1745. this.y -= otherVector.y;
  1746. this.z -= otherVector.z;
  1747. this.w -= otherVector.w;
  1748. return this;
  1749. };
  1750. /**
  1751. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1752. */
  1753. Vector4.prototype.subtract = function (otherVector) {
  1754. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1755. };
  1756. /**
  1757. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1758. * Returns the current Vector4.
  1759. */
  1760. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1761. result.x = this.x - otherVector.x;
  1762. result.y = this.y - otherVector.y;
  1763. result.z = this.z - otherVector.z;
  1764. result.w = this.w - otherVector.w;
  1765. return this;
  1766. };
  1767. /**
  1768. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1769. */
  1770. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1771. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1772. };
  1773. /**
  1774. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1775. * Returns the current Vector4.
  1776. */
  1777. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1778. result.x = this.x - x;
  1779. result.y = this.y - y;
  1780. result.z = this.z - z;
  1781. result.w = this.w - w;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1786. */
  1787. Vector4.prototype.negate = function () {
  1788. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1789. };
  1790. /**
  1791. * Multiplies the current Vector4 coordinates by scale (float).
  1792. * Returns the updated Vector4.
  1793. */
  1794. Vector4.prototype.scaleInPlace = function (scale) {
  1795. this.x *= scale;
  1796. this.y *= scale;
  1797. this.z *= scale;
  1798. this.w *= scale;
  1799. return this;
  1800. };
  1801. /**
  1802. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1803. */
  1804. Vector4.prototype.scale = function (scale) {
  1805. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1806. };
  1807. /**
  1808. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1809. * Returns the current Vector4.
  1810. */
  1811. Vector4.prototype.scaleToRef = function (scale, result) {
  1812. result.x = this.x * scale;
  1813. result.y = this.y * scale;
  1814. result.z = this.z * scale;
  1815. result.w = this.w * scale;
  1816. return this;
  1817. };
  1818. /**
  1819. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1820. */
  1821. Vector4.prototype.equals = function (otherVector) {
  1822. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1823. };
  1824. /**
  1825. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1826. */
  1827. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1828. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1829. return otherVector
  1830. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1831. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1832. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1833. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1834. };
  1835. /**
  1836. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1837. */
  1838. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1839. return this.x === x && this.y === y && this.z === z && this.w === w;
  1840. };
  1841. /**
  1842. * Multiplies in place the current Vector4 by the passed one.
  1843. * Returns the updated Vector4.
  1844. */
  1845. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1846. this.x *= otherVector.x;
  1847. this.y *= otherVector.y;
  1848. this.z *= otherVector.z;
  1849. this.w *= otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1854. */
  1855. Vector4.prototype.multiply = function (otherVector) {
  1856. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1857. };
  1858. /**
  1859. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1863. result.x = this.x * otherVector.x;
  1864. result.y = this.y * otherVector.y;
  1865. result.z = this.z * otherVector.z;
  1866. result.w = this.w * otherVector.w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1871. */
  1872. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1873. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1874. };
  1875. /**
  1876. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1877. */
  1878. Vector4.prototype.divide = function (otherVector) {
  1879. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1880. };
  1881. /**
  1882. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1883. * Returns the current Vector4.
  1884. */
  1885. Vector4.prototype.divideToRef = function (otherVector, result) {
  1886. result.x = this.x / otherVector.x;
  1887. result.y = this.y / otherVector.y;
  1888. result.z = this.z / otherVector.z;
  1889. result.w = this.w / otherVector.w;
  1890. return this;
  1891. };
  1892. /**
  1893. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1894. */
  1895. Vector4.prototype.MinimizeInPlace = function (other) {
  1896. if (other.x < this.x)
  1897. this.x = other.x;
  1898. if (other.y < this.y)
  1899. this.y = other.y;
  1900. if (other.z < this.z)
  1901. this.z = other.z;
  1902. if (other.w < this.w)
  1903. this.w = other.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1908. */
  1909. Vector4.prototype.MaximizeInPlace = function (other) {
  1910. if (other.x > this.x)
  1911. this.x = other.x;
  1912. if (other.y > this.y)
  1913. this.y = other.y;
  1914. if (other.z > this.z)
  1915. this.z = other.z;
  1916. if (other.w > this.w)
  1917. this.w = other.w;
  1918. return this;
  1919. };
  1920. // Properties
  1921. /**
  1922. * Returns the Vector4 length (float).
  1923. */
  1924. Vector4.prototype.length = function () {
  1925. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1926. };
  1927. /**
  1928. * Returns the Vector4 squared length (float).
  1929. */
  1930. Vector4.prototype.lengthSquared = function () {
  1931. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1932. };
  1933. // Methods
  1934. /**
  1935. * Normalizes in place the Vector4.
  1936. * Returns the updated Vector4.
  1937. */
  1938. Vector4.prototype.normalize = function () {
  1939. var len = this.length();
  1940. if (len === 0)
  1941. return this;
  1942. var num = 1.0 / len;
  1943. this.x *= num;
  1944. this.y *= num;
  1945. this.z *= num;
  1946. this.w *= num;
  1947. return this;
  1948. };
  1949. /**
  1950. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1951. */
  1952. Vector4.prototype.toVector3 = function () {
  1953. return new Vector3(this.x, this.y, this.z);
  1954. };
  1955. /**
  1956. * Returns a new Vector4 copied from the current one.
  1957. */
  1958. Vector4.prototype.clone = function () {
  1959. return new Vector4(this.x, this.y, this.z, this.w);
  1960. };
  1961. /**
  1962. * Updates the current Vector4 with the passed one coordinates.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFrom = function (source) {
  1966. this.x = source.x;
  1967. this.y = source.y;
  1968. this.z = source.z;
  1969. this.w = source.w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1977. this.x = x;
  1978. this.y = y;
  1979. this.z = z;
  1980. this.w = w;
  1981. return this;
  1982. };
  1983. /**
  1984. * Updates the current Vector4 coordinates with the passed floats.
  1985. * Returns the updated Vector4.
  1986. */
  1987. Vector4.prototype.set = function (x, y, z, w) {
  1988. return this.copyFromFloats(x, y, z, w);
  1989. };
  1990. // Statics
  1991. /**
  1992. * Returns a new Vector4 set from the starting index of the passed array.
  1993. */
  1994. Vector4.FromArray = function (array, offset) {
  1995. if (!offset) {
  1996. offset = 0;
  1997. }
  1998. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1999. };
  2000. /**
  2001. * Updates the passed vector "result" from the starting index of the passed array.
  2002. */
  2003. Vector4.FromArrayToRef = function (array, offset, result) {
  2004. result.x = array[offset];
  2005. result.y = array[offset + 1];
  2006. result.z = array[offset + 2];
  2007. result.w = array[offset + 3];
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2011. */
  2012. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2013. Vector4.FromArrayToRef(array, offset, result);
  2014. };
  2015. /**
  2016. * Updates the passed vector "result" coordinates from the passed floats.
  2017. */
  2018. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2019. result.x = x;
  2020. result.y = y;
  2021. result.z = z;
  2022. result.w = w;
  2023. };
  2024. /**
  2025. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2026. */
  2027. Vector4.Zero = function () {
  2028. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2032. */
  2033. Vector4.One = function () {
  2034. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2035. };
  2036. /**
  2037. * Returns a new normalized Vector4 from the passed one.
  2038. */
  2039. Vector4.Normalize = function (vector) {
  2040. var result = Vector4.Zero();
  2041. Vector4.NormalizeToRef(vector, result);
  2042. return result;
  2043. };
  2044. /**
  2045. * Updates the passed vector "result" from the normalization of the passed one.
  2046. */
  2047. Vector4.NormalizeToRef = function (vector, result) {
  2048. result.copyFrom(vector);
  2049. result.normalize();
  2050. };
  2051. Vector4.Minimize = function (left, right) {
  2052. var min = left.clone();
  2053. min.MinimizeInPlace(right);
  2054. return min;
  2055. };
  2056. Vector4.Maximize = function (left, right) {
  2057. var max = left.clone();
  2058. max.MaximizeInPlace(right);
  2059. return max;
  2060. };
  2061. /**
  2062. * Returns the distance (float) between the vectors "value1" and "value2".
  2063. */
  2064. Vector4.Distance = function (value1, value2) {
  2065. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2066. };
  2067. /**
  2068. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.DistanceSquared = function (value1, value2) {
  2071. var x = value1.x - value2.x;
  2072. var y = value1.y - value2.y;
  2073. var z = value1.z - value2.z;
  2074. var w = value1.w - value2.w;
  2075. return (x * x) + (y * y) + (z * z) + (w * w);
  2076. };
  2077. /**
  2078. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2079. */
  2080. Vector4.Center = function (value1, value2) {
  2081. var center = value1.add(value2);
  2082. center.scaleInPlace(0.5);
  2083. return center;
  2084. };
  2085. /**
  2086. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2087. * This methods computes transformed normalized direction vectors only.
  2088. */
  2089. Vector4.TransformNormal = function (vector, transformation) {
  2090. var result = Vector4.Zero();
  2091. Vector4.TransformNormalToRef(vector, transformation, result);
  2092. return result;
  2093. };
  2094. /**
  2095. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2096. * This methods computes transformed normalized direction vectors only.
  2097. */
  2098. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2099. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2100. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2101. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2102. result.x = x;
  2103. result.y = y;
  2104. result.z = z;
  2105. result.w = vector.w;
  2106. };
  2107. /**
  2108. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2109. * This methods computes transformed normalized direction vectors only.
  2110. */
  2111. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2112. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2113. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2114. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2115. result.w = w;
  2116. };
  2117. return Vector4;
  2118. }());
  2119. BABYLON.Vector4 = Vector4;
  2120. var Size = (function () {
  2121. /**
  2122. * Creates a Size object from the passed width and height (floats).
  2123. */
  2124. function Size(width, height) {
  2125. this.width = width;
  2126. this.height = height;
  2127. }
  2128. // Returns a string with the Size width and height.
  2129. Size.prototype.toString = function () {
  2130. return "{W: " + this.width + ", H: " + this.height + "}";
  2131. };
  2132. /**
  2133. * Returns the string "Size"
  2134. */
  2135. Size.prototype.getClassName = function () {
  2136. return "Size";
  2137. };
  2138. /**
  2139. * Returns the Size hash code.
  2140. */
  2141. Size.prototype.getHashCode = function () {
  2142. var hash = this.width || 0;
  2143. hash = (hash * 397) ^ (this.height || 0);
  2144. return hash;
  2145. };
  2146. /**
  2147. * Updates the current size from the passed one.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.copyFrom = function (src) {
  2151. this.width = src.width;
  2152. this.height = src.height;
  2153. };
  2154. /**
  2155. * Updates in place the current Size from the passed floats.
  2156. * Returns the updated Size.
  2157. */
  2158. Size.prototype.copyFromFloats = function (width, height) {
  2159. this.width = width;
  2160. this.height = height;
  2161. return this;
  2162. };
  2163. /**
  2164. * Updates in place the current Size from the passed floats.
  2165. * Returns the updated Size.
  2166. */
  2167. Size.prototype.set = function (width, height) {
  2168. return this.copyFromFloats(width, height);
  2169. };
  2170. /**
  2171. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2172. */
  2173. Size.prototype.multiplyByFloats = function (w, h) {
  2174. return new Size(this.width * w, this.height * h);
  2175. };
  2176. /**
  2177. * Returns a new Size copied from the passed one.
  2178. */
  2179. Size.prototype.clone = function () {
  2180. return new Size(this.width, this.height);
  2181. };
  2182. /**
  2183. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2184. */
  2185. Size.prototype.equals = function (other) {
  2186. if (!other) {
  2187. return false;
  2188. }
  2189. return (this.width === other.width) && (this.height === other.height);
  2190. };
  2191. Object.defineProperty(Size.prototype, "surface", {
  2192. /**
  2193. * Returns the surface of the Size : width * height (float).
  2194. */
  2195. get: function () {
  2196. return this.width * this.height;
  2197. },
  2198. enumerable: true,
  2199. configurable: true
  2200. });
  2201. /**
  2202. * Returns a new Size set to (0.0, 0.0)
  2203. */
  2204. Size.Zero = function () {
  2205. return new Size(0.0, 0.0);
  2206. };
  2207. /**
  2208. * Returns a new Size set as the addition result of the current Size and the passed one.
  2209. */
  2210. Size.prototype.add = function (otherSize) {
  2211. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2212. return r;
  2213. };
  2214. /**
  2215. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2216. */
  2217. Size.prototype.subtract = function (otherSize) {
  2218. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2223. */
  2224. Size.Lerp = function (start, end, amount) {
  2225. var w = start.width + ((end.width - start.width) * amount);
  2226. var h = start.height + ((end.height - start.height) * amount);
  2227. return new Size(w, h);
  2228. };
  2229. return Size;
  2230. }());
  2231. BABYLON.Size = Size;
  2232. var Quaternion = (function () {
  2233. /**
  2234. * Creates a new Quaternion from the passed floats.
  2235. */
  2236. function Quaternion(x, y, z, w) {
  2237. if (x === void 0) { x = 0.0; }
  2238. if (y === void 0) { y = 0.0; }
  2239. if (z === void 0) { z = 0.0; }
  2240. if (w === void 0) { w = 1.0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. this.z = z;
  2244. this.w = w;
  2245. }
  2246. /**
  2247. * Returns a string with the Quaternion coordinates.
  2248. */
  2249. Quaternion.prototype.toString = function () {
  2250. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2251. };
  2252. /**
  2253. * Returns the string "Quaternion".
  2254. */
  2255. Quaternion.prototype.getClassName = function () {
  2256. return "Quaternion";
  2257. };
  2258. /**
  2259. * Returns the Quaternion hash code.
  2260. */
  2261. Quaternion.prototype.getHashCode = function () {
  2262. var hash = this.x || 0;
  2263. hash = (hash * 397) ^ (this.y || 0);
  2264. hash = (hash * 397) ^ (this.z || 0);
  2265. hash = (hash * 397) ^ (this.w || 0);
  2266. return hash;
  2267. };
  2268. /**
  2269. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2270. */
  2271. Quaternion.prototype.asArray = function () {
  2272. return [this.x, this.y, this.z, this.w];
  2273. };
  2274. /**
  2275. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2276. */
  2277. Quaternion.prototype.equals = function (otherQuaternion) {
  2278. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2279. };
  2280. /**
  2281. * Returns a new Quaternion copied from the current one.
  2282. */
  2283. Quaternion.prototype.clone = function () {
  2284. return new Quaternion(this.x, this.y, this.z, this.w);
  2285. };
  2286. /**
  2287. * Updates the current Quaternion from the passed one coordinates.
  2288. * Returns the updated Quaterion.
  2289. */
  2290. Quaternion.prototype.copyFrom = function (other) {
  2291. this.x = other.x;
  2292. this.y = other.y;
  2293. this.z = other.z;
  2294. this.w = other.w;
  2295. return this;
  2296. };
  2297. /**
  2298. * Updates the current Quaternion from the passed float coordinates.
  2299. * Returns the updated Quaterion.
  2300. */
  2301. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2302. this.x = x;
  2303. this.y = y;
  2304. this.z = z;
  2305. this.w = w;
  2306. return this;
  2307. };
  2308. /**
  2309. * Updates the current Quaternion from the passed float coordinates.
  2310. * Returns the updated Quaterion.
  2311. */
  2312. Quaternion.prototype.set = function (x, y, z, w) {
  2313. return this.copyFromFloats(x, y, z, w);
  2314. };
  2315. /**
  2316. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2317. */
  2318. Quaternion.prototype.add = function (other) {
  2319. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2320. };
  2321. /**
  2322. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2323. */
  2324. Quaternion.prototype.subtract = function (other) {
  2325. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2326. };
  2327. /**
  2328. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2329. */
  2330. Quaternion.prototype.scale = function (value) {
  2331. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2332. };
  2333. /**
  2334. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2335. */
  2336. Quaternion.prototype.multiply = function (q1) {
  2337. var result = new Quaternion(0, 0, 0, 1.0);
  2338. this.multiplyToRef(q1, result);
  2339. return result;
  2340. };
  2341. /**
  2342. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2343. * Returns the current Quaternion.
  2344. */
  2345. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2346. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2347. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2348. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2349. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2350. result.copyFromFloats(x, y, z, w);
  2351. return this;
  2352. };
  2353. /**
  2354. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2355. * Returns the updated Quaternion.
  2356. */
  2357. Quaternion.prototype.multiplyInPlace = function (q1) {
  2358. this.multiplyToRef(q1, this);
  2359. return this;
  2360. };
  2361. /**
  2362. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2363. * Returns the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugateToRef = function (ref) {
  2366. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2367. return this;
  2368. };
  2369. /**
  2370. * Conjugates in place the current Quaternion.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.conjugateInPlace = function () {
  2374. this.x *= -1;
  2375. this.y *= -1;
  2376. this.z *= -1;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2381. */
  2382. Quaternion.prototype.conjugate = function () {
  2383. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2384. return result;
  2385. };
  2386. /**
  2387. * Returns the Quaternion length (float).
  2388. */
  2389. Quaternion.prototype.length = function () {
  2390. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2391. };
  2392. /**
  2393. * Normalize in place the current Quaternion.
  2394. * Returns the updated Quaternion.
  2395. */
  2396. Quaternion.prototype.normalize = function () {
  2397. var length = 1.0 / this.length();
  2398. this.x *= length;
  2399. this.y *= length;
  2400. this.z *= length;
  2401. this.w *= length;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAngles = function (order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var result = Vector3.Zero();
  2410. this.toEulerAnglesToRef(result, order);
  2411. return result;
  2412. };
  2413. /**
  2414. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2415. * Returns the current Quaternion.
  2416. */
  2417. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2418. if (order === void 0) { order = "YZX"; }
  2419. var qz = this.z;
  2420. var qx = this.x;
  2421. var qy = this.y;
  2422. var qw = this.w;
  2423. var sqw = qw * qw;
  2424. var sqz = qz * qz;
  2425. var sqx = qx * qx;
  2426. var sqy = qy * qy;
  2427. var zAxisY = qy * qz - qx * qw;
  2428. var limit = .4999999;
  2429. if (zAxisY < -limit) {
  2430. result.y = 2 * Math.atan2(qy, qw);
  2431. result.x = Math.PI / 2;
  2432. result.z = 0;
  2433. }
  2434. else if (zAxisY > limit) {
  2435. result.y = 2 * Math.atan2(qy, qw);
  2436. result.x = -Math.PI / 2;
  2437. result.z = 0;
  2438. }
  2439. else {
  2440. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2441. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2442. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2443. }
  2444. return this;
  2445. };
  2446. /**
  2447. * Updates the passed rotation matrix with the current Quaternion values.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.toRotationMatrix = function (result) {
  2451. var xx = this.x * this.x;
  2452. var yy = this.y * this.y;
  2453. var zz = this.z * this.z;
  2454. var xy = this.x * this.y;
  2455. var zw = this.z * this.w;
  2456. var zx = this.z * this.x;
  2457. var yw = this.y * this.w;
  2458. var yz = this.y * this.z;
  2459. var xw = this.x * this.w;
  2460. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2461. result.m[1] = 2.0 * (xy + zw);
  2462. result.m[2] = 2.0 * (zx - yw);
  2463. result.m[3] = 0;
  2464. result.m[4] = 2.0 * (xy - zw);
  2465. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2466. result.m[6] = 2.0 * (yz + xw);
  2467. result.m[7] = 0;
  2468. result.m[8] = 2.0 * (zx + yw);
  2469. result.m[9] = 2.0 * (yz - xw);
  2470. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2471. result.m[11] = 0;
  2472. result.m[12] = 0;
  2473. result.m[13] = 0;
  2474. result.m[14] = 0;
  2475. result.m[15] = 1.0;
  2476. result._markAsUpdated();
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed rotation matrix values.
  2481. * Returns the updated Quaternion.
  2482. */
  2483. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2484. Quaternion.FromRotationMatrixToRef(matrix, this);
  2485. return this;
  2486. };
  2487. // Statics
  2488. /**
  2489. * Returns a new Quaternion set from the passed rotation matrix values.
  2490. */
  2491. Quaternion.FromRotationMatrix = function (matrix) {
  2492. var result = new Quaternion();
  2493. Quaternion.FromRotationMatrixToRef(matrix, result);
  2494. return result;
  2495. };
  2496. /**
  2497. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2498. */
  2499. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2500. var data = matrix.m;
  2501. var m11 = data[0], m12 = data[4], m13 = data[8];
  2502. var m21 = data[1], m22 = data[5], m23 = data[9];
  2503. var m31 = data[2], m32 = data[6], m33 = data[10];
  2504. var trace = m11 + m22 + m33;
  2505. var s;
  2506. if (trace > 0) {
  2507. s = 0.5 / Math.sqrt(trace + 1.0);
  2508. result.w = 0.25 / s;
  2509. result.x = (m32 - m23) * s;
  2510. result.y = (m13 - m31) * s;
  2511. result.z = (m21 - m12) * s;
  2512. }
  2513. else if (m11 > m22 && m11 > m33) {
  2514. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2515. result.w = (m32 - m23) / s;
  2516. result.x = 0.25 * s;
  2517. result.y = (m12 + m21) / s;
  2518. result.z = (m13 + m31) / s;
  2519. }
  2520. else if (m22 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2522. result.w = (m13 - m31) / s;
  2523. result.x = (m12 + m21) / s;
  2524. result.y = 0.25 * s;
  2525. result.z = (m23 + m32) / s;
  2526. }
  2527. else {
  2528. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2529. result.w = (m21 - m12) / s;
  2530. result.x = (m13 + m31) / s;
  2531. result.y = (m23 + m32) / s;
  2532. result.z = 0.25 * s;
  2533. }
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2537. */
  2538. Quaternion.Zero = function () {
  2539. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion as the inverted current Quaternion.
  2543. */
  2544. Quaternion.Inverse = function (q) {
  2545. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2546. };
  2547. /**
  2548. * Returns the identity Quaternion.
  2549. */
  2550. Quaternion.Identity = function () {
  2551. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2552. };
  2553. Quaternion.IsIdentity = function (quaternion) {
  2554. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2558. */
  2559. Quaternion.RotationAxis = function (axis, angle) {
  2560. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2561. };
  2562. /**
  2563. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2564. */
  2565. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2566. var sin = Math.sin(angle / 2);
  2567. axis.normalize();
  2568. result.w = Math.cos(angle / 2);
  2569. result.x = axis.x * sin;
  2570. result.y = axis.y * sin;
  2571. result.z = axis.z * sin;
  2572. return result;
  2573. };
  2574. /**
  2575. * Retuns a new Quaternion set from the starting index of the passed array.
  2576. */
  2577. Quaternion.FromArray = function (array, offset) {
  2578. if (!offset) {
  2579. offset = 0;
  2580. }
  2581. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2585. */
  2586. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2587. var q = new Quaternion();
  2588. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2589. return q;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2593. */
  2594. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2595. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2596. var halfRoll = roll * 0.5;
  2597. var halfPitch = pitch * 0.5;
  2598. var halfYaw = yaw * 0.5;
  2599. var sinRoll = Math.sin(halfRoll);
  2600. var cosRoll = Math.cos(halfRoll);
  2601. var sinPitch = Math.sin(halfPitch);
  2602. var cosPitch = Math.cos(halfPitch);
  2603. var sinYaw = Math.sin(halfYaw);
  2604. var cosYaw = Math.cos(halfYaw);
  2605. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2606. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2607. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2608. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2609. };
  2610. /**
  2611. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2612. */
  2613. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2614. var result = new Quaternion();
  2615. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2620. */
  2621. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2622. // Produces a quaternion from Euler angles in the z-x-z orientation
  2623. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2624. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2625. var halfBeta = beta * 0.5;
  2626. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2627. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2628. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2629. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2637. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2639. return quat;
  2640. };
  2641. /**
  2642. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2643. * cf to Vector3.RotationFromAxis() documentation.
  2644. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2645. */
  2646. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2647. var rotMat = MathTmp.Matrix[0];
  2648. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2649. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2650. };
  2651. Quaternion.Slerp = function (left, right, amount) {
  2652. var result = Quaternion.Identity();
  2653. Quaternion.SlerpToRef(left, right, amount, result);
  2654. return result;
  2655. };
  2656. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2657. var num2;
  2658. var num3;
  2659. var num = amount;
  2660. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2661. var flag = false;
  2662. if (num4 < 0) {
  2663. flag = true;
  2664. num4 = -num4;
  2665. }
  2666. if (num4 > 0.999999) {
  2667. num3 = 1 - num;
  2668. num2 = flag ? -num : num;
  2669. }
  2670. else {
  2671. var num5 = Math.acos(num4);
  2672. var num6 = (1.0 / Math.sin(num5));
  2673. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2674. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2675. }
  2676. result.x = (num3 * left.x) + (num2 * right.x);
  2677. result.y = (num3 * left.y) + (num2 * right.y);
  2678. result.z = (num3 * left.z) + (num2 * right.z);
  2679. result.w = (num3 * left.w) + (num2 * right.w);
  2680. };
  2681. /**
  2682. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2683. */
  2684. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2685. var squared = amount * amount;
  2686. var cubed = amount * squared;
  2687. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2688. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2689. var part3 = (cubed - (2.0 * squared)) + amount;
  2690. var part4 = cubed - squared;
  2691. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2692. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2693. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2694. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2695. return new Quaternion(x, y, z, w);
  2696. };
  2697. return Quaternion;
  2698. }());
  2699. BABYLON.Quaternion = Quaternion;
  2700. var Matrix = (function () {
  2701. function Matrix() {
  2702. this._isIdentity = false;
  2703. this._isIdentityDirty = true;
  2704. this.m = new Float32Array(16);
  2705. this._markAsUpdated();
  2706. }
  2707. Matrix.prototype._markAsUpdated = function () {
  2708. this.updateFlag = Matrix._updateFlagSeed++;
  2709. this._isIdentityDirty = true;
  2710. };
  2711. // Properties
  2712. /**
  2713. * Boolean : True is the matrix is the identity matrix
  2714. */
  2715. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2716. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2717. if (this._isIdentityDirty) {
  2718. this._isIdentityDirty = false;
  2719. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2720. this._isIdentity = false;
  2721. }
  2722. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2726. this._isIdentity = false;
  2727. }
  2728. else {
  2729. this._isIdentity = true;
  2730. }
  2731. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2732. this._isIdentity = false;
  2733. }
  2734. }
  2735. return this._isIdentity;
  2736. };
  2737. /**
  2738. * Returns the matrix determinant (float).
  2739. */
  2740. Matrix.prototype.determinant = function () {
  2741. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2742. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2743. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2744. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2745. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2746. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2747. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2748. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2749. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2750. };
  2751. // Methods
  2752. /**
  2753. * Returns the matrix underlying array.
  2754. */
  2755. Matrix.prototype.toArray = function () {
  2756. return this.m;
  2757. };
  2758. /**
  2759. * Returns the matrix underlying array.
  2760. */
  2761. Matrix.prototype.asArray = function () {
  2762. return this.toArray();
  2763. };
  2764. /**
  2765. * Inverts in place the Matrix.
  2766. * Returns the Matrix inverted.
  2767. */
  2768. Matrix.prototype.invert = function () {
  2769. this.invertToRef(this);
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets all the matrix elements to zero.
  2774. * Returns the Matrix.
  2775. */
  2776. Matrix.prototype.reset = function () {
  2777. for (var index = 0; index < 16; index++) {
  2778. this.m[index] = 0.0;
  2779. }
  2780. this._markAsUpdated();
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2785. */
  2786. Matrix.prototype.add = function (other) {
  2787. var result = new Matrix();
  2788. this.addToRef(other, result);
  2789. return result;
  2790. };
  2791. /**
  2792. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2793. * Returns the Matrix.
  2794. */
  2795. Matrix.prototype.addToRef = function (other, result) {
  2796. for (var index = 0; index < 16; index++) {
  2797. result.m[index] = this.m[index] + other.m[index];
  2798. }
  2799. result._markAsUpdated();
  2800. return this;
  2801. };
  2802. /**
  2803. * Adds in place the passed matrix to the current Matrix.
  2804. * Returns the updated Matrix.
  2805. */
  2806. Matrix.prototype.addToSelf = function (other) {
  2807. for (var index = 0; index < 16; index++) {
  2808. this.m[index] += other.m[index];
  2809. }
  2810. this._markAsUpdated();
  2811. return this;
  2812. };
  2813. /**
  2814. * Sets the passed matrix with the current inverted Matrix.
  2815. * Returns the unmodified current Matrix.
  2816. */
  2817. Matrix.prototype.invertToRef = function (other) {
  2818. var l1 = this.m[0];
  2819. var l2 = this.m[1];
  2820. var l3 = this.m[2];
  2821. var l4 = this.m[3];
  2822. var l5 = this.m[4];
  2823. var l6 = this.m[5];
  2824. var l7 = this.m[6];
  2825. var l8 = this.m[7];
  2826. var l9 = this.m[8];
  2827. var l10 = this.m[9];
  2828. var l11 = this.m[10];
  2829. var l12 = this.m[11];
  2830. var l13 = this.m[12];
  2831. var l14 = this.m[13];
  2832. var l15 = this.m[14];
  2833. var l16 = this.m[15];
  2834. var l17 = (l11 * l16) - (l12 * l15);
  2835. var l18 = (l10 * l16) - (l12 * l14);
  2836. var l19 = (l10 * l15) - (l11 * l14);
  2837. var l20 = (l9 * l16) - (l12 * l13);
  2838. var l21 = (l9 * l15) - (l11 * l13);
  2839. var l22 = (l9 * l14) - (l10 * l13);
  2840. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2841. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2842. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2843. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2844. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2845. var l28 = (l7 * l16) - (l8 * l15);
  2846. var l29 = (l6 * l16) - (l8 * l14);
  2847. var l30 = (l6 * l15) - (l7 * l14);
  2848. var l31 = (l5 * l16) - (l8 * l13);
  2849. var l32 = (l5 * l15) - (l7 * l13);
  2850. var l33 = (l5 * l14) - (l6 * l13);
  2851. var l34 = (l7 * l12) - (l8 * l11);
  2852. var l35 = (l6 * l12) - (l8 * l10);
  2853. var l36 = (l6 * l11) - (l7 * l10);
  2854. var l37 = (l5 * l12) - (l8 * l9);
  2855. var l38 = (l5 * l11) - (l7 * l9);
  2856. var l39 = (l5 * l10) - (l6 * l9);
  2857. other.m[0] = l23 * l27;
  2858. other.m[4] = l24 * l27;
  2859. other.m[8] = l25 * l27;
  2860. other.m[12] = l26 * l27;
  2861. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2862. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2863. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2864. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2865. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2866. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2867. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2868. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2869. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2870. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2871. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2872. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2873. other._markAsUpdated();
  2874. return this;
  2875. };
  2876. /**
  2877. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2878. * Returns the updated Matrix.
  2879. */
  2880. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2881. this.m[12] = x;
  2882. this.m[13] = y;
  2883. this.m[14] = z;
  2884. this._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Inserts the translation vector in the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.setTranslation = function (vector3) {
  2892. this.m[12] = vector3.x;
  2893. this.m[13] = vector3.y;
  2894. this.m[14] = vector3.z;
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3 as the extracted translation from the Matrix.
  2900. */
  2901. Matrix.prototype.getTranslation = function () {
  2902. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2903. };
  2904. /**
  2905. * Fill a Vector3 with the extracted translation from the Matrix.
  2906. */
  2907. Matrix.prototype.getTranslationToRef = function (result) {
  2908. result.x = this.m[12];
  2909. result.y = this.m[13];
  2910. result.z = this.m[14];
  2911. return this;
  2912. };
  2913. /**
  2914. * Remove rotation and scaling part from the Matrix.
  2915. * Returns the updated Matrix.
  2916. */
  2917. Matrix.prototype.removeRotationAndScaling = function () {
  2918. this.setRowFromFloats(0, 1, 0, 0, 0);
  2919. this.setRowFromFloats(1, 0, 1, 0, 0);
  2920. this.setRowFromFloats(2, 0, 0, 1, 0);
  2921. return this;
  2922. };
  2923. /**
  2924. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2925. */
  2926. Matrix.prototype.multiply = function (other) {
  2927. var result = new Matrix();
  2928. this.multiplyToRef(other, result);
  2929. return result;
  2930. };
  2931. /**
  2932. * Updates the current Matrix from the passed one values.
  2933. * Returns the updated Matrix.
  2934. */
  2935. Matrix.prototype.copyFrom = function (other) {
  2936. for (var index = 0; index < 16; index++) {
  2937. this.m[index] = other.m[index];
  2938. }
  2939. this._markAsUpdated();
  2940. return this;
  2941. };
  2942. /**
  2943. * Populates the passed array from the starting index with the Matrix values.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.copyToArray = function (array, offset) {
  2947. if (offset === void 0) { offset = 0; }
  2948. for (var index = 0; index < 16; index++) {
  2949. array[offset + index] = this.m[index];
  2950. }
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToRef = function (other, result) {
  2957. this.multiplyToArray(other, result.m, 0);
  2958. result._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2963. */
  2964. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2965. var tm0 = this.m[0];
  2966. var tm1 = this.m[1];
  2967. var tm2 = this.m[2];
  2968. var tm3 = this.m[3];
  2969. var tm4 = this.m[4];
  2970. var tm5 = this.m[5];
  2971. var tm6 = this.m[6];
  2972. var tm7 = this.m[7];
  2973. var tm8 = this.m[8];
  2974. var tm9 = this.m[9];
  2975. var tm10 = this.m[10];
  2976. var tm11 = this.m[11];
  2977. var tm12 = this.m[12];
  2978. var tm13 = this.m[13];
  2979. var tm14 = this.m[14];
  2980. var tm15 = this.m[15];
  2981. var om0 = other.m[0];
  2982. var om1 = other.m[1];
  2983. var om2 = other.m[2];
  2984. var om3 = other.m[3];
  2985. var om4 = other.m[4];
  2986. var om5 = other.m[5];
  2987. var om6 = other.m[6];
  2988. var om7 = other.m[7];
  2989. var om8 = other.m[8];
  2990. var om9 = other.m[9];
  2991. var om10 = other.m[10];
  2992. var om11 = other.m[11];
  2993. var om12 = other.m[12];
  2994. var om13 = other.m[13];
  2995. var om14 = other.m[14];
  2996. var om15 = other.m[15];
  2997. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2998. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2999. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3000. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3001. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3002. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3003. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3004. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3005. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3006. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3007. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3008. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3009. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3010. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3011. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3012. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3013. return this;
  3014. };
  3015. /**
  3016. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3017. */
  3018. Matrix.prototype.equals = function (value) {
  3019. return value &&
  3020. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3021. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3022. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3023. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3024. };
  3025. /**
  3026. * Returns a new Matrix from the current Matrix.
  3027. */
  3028. Matrix.prototype.clone = function () {
  3029. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3030. };
  3031. /**
  3032. * Returns the string "Matrix"
  3033. */
  3034. Matrix.prototype.getClassName = function () {
  3035. return "Matrix";
  3036. };
  3037. /**
  3038. * Returns the Matrix hash code.
  3039. */
  3040. Matrix.prototype.getHashCode = function () {
  3041. var hash = this.m[0] || 0;
  3042. for (var i = 1; i < 16; i++) {
  3043. hash = (hash * 397) ^ (this.m[i] || 0);
  3044. }
  3045. return hash;
  3046. };
  3047. /**
  3048. * Decomposes the current Matrix into :
  3049. * - a scale vector3 passed as a reference to update,
  3050. * - a rotation quaternion passed as a reference to update,
  3051. * - a translation vector3 passed as a reference to update.
  3052. * Returns the boolean `true`.
  3053. */
  3054. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3055. translation.x = this.m[12];
  3056. translation.y = this.m[13];
  3057. translation.z = this.m[14];
  3058. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3059. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3060. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3061. if (this.determinant() <= 0) {
  3062. scale.y *= -1;
  3063. }
  3064. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3065. rotation.x = 0;
  3066. rotation.y = 0;
  3067. rotation.z = 0;
  3068. rotation.w = 1;
  3069. return false;
  3070. }
  3071. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3072. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3073. return true;
  3074. };
  3075. /**
  3076. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3077. */
  3078. Matrix.prototype.getRotationMatrix = function () {
  3079. var result = Matrix.Identity();
  3080. this.getRotationMatrixToRef(result);
  3081. return result;
  3082. };
  3083. /**
  3084. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3085. * Returns the current Matrix.
  3086. */
  3087. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3088. var m = this.m;
  3089. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3090. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3091. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3092. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3093. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3094. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3095. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3096. return this;
  3097. };
  3098. // Statics
  3099. /**
  3100. * Returns a new Matrix set from the starting index of the passed array.
  3101. */
  3102. Matrix.FromArray = function (array, offset) {
  3103. var result = new Matrix();
  3104. if (!offset) {
  3105. offset = 0;
  3106. }
  3107. Matrix.FromArrayToRef(array, offset, result);
  3108. return result;
  3109. };
  3110. /**
  3111. * Sets the passed "result" matrix from the starting index of the passed array.
  3112. */
  3113. Matrix.FromArrayToRef = function (array, offset, result) {
  3114. for (var index = 0; index < 16; index++) {
  3115. result.m[index] = array[index + offset];
  3116. }
  3117. result._markAsUpdated();
  3118. };
  3119. /**
  3120. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3121. */
  3122. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3123. for (var index = 0; index < 16; index++) {
  3124. result.m[index] = array[index + offset] * scale;
  3125. }
  3126. result._markAsUpdated();
  3127. };
  3128. /**
  3129. * Sets the passed matrix "result" with the 16 passed floats.
  3130. */
  3131. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3132. result.m[0] = initialM11;
  3133. result.m[1] = initialM12;
  3134. result.m[2] = initialM13;
  3135. result.m[3] = initialM14;
  3136. result.m[4] = initialM21;
  3137. result.m[5] = initialM22;
  3138. result.m[6] = initialM23;
  3139. result.m[7] = initialM24;
  3140. result.m[8] = initialM31;
  3141. result.m[9] = initialM32;
  3142. result.m[10] = initialM33;
  3143. result.m[11] = initialM34;
  3144. result.m[12] = initialM41;
  3145. result.m[13] = initialM42;
  3146. result.m[14] = initialM43;
  3147. result.m[15] = initialM44;
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Returns the index-th row of the current matrix as a new Vector4.
  3152. */
  3153. Matrix.prototype.getRow = function (index) {
  3154. if (index < 0 || index > 3) {
  3155. return null;
  3156. }
  3157. var i = index * 4;
  3158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3159. };
  3160. /**
  3161. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.setRow = function (index, row) {
  3165. if (index < 0 || index > 3) {
  3166. return this;
  3167. }
  3168. var i = index * 4;
  3169. this.m[i + 0] = row.x;
  3170. this.m[i + 1] = row.y;
  3171. this.m[i + 2] = row.z;
  3172. this.m[i + 3] = row.w;
  3173. this._markAsUpdated();
  3174. return this;
  3175. };
  3176. /**
  3177. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3178. * Returns the updated Matrix.
  3179. */
  3180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3181. if (index < 0 || index > 3) {
  3182. return this;
  3183. }
  3184. var i = index * 4;
  3185. this.m[i + 0] = x;
  3186. this.m[i + 1] = y;
  3187. this.m[i + 2] = z;
  3188. this.m[i + 3] = w;
  3189. this._markAsUpdated();
  3190. return this;
  3191. };
  3192. /**
  3193. * Returns a new Matrix set from the 16 passed floats.
  3194. */
  3195. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3196. var result = new Matrix();
  3197. result.m[0] = initialM11;
  3198. result.m[1] = initialM12;
  3199. result.m[2] = initialM13;
  3200. result.m[3] = initialM14;
  3201. result.m[4] = initialM21;
  3202. result.m[5] = initialM22;
  3203. result.m[6] = initialM23;
  3204. result.m[7] = initialM24;
  3205. result.m[8] = initialM31;
  3206. result.m[9] = initialM32;
  3207. result.m[10] = initialM33;
  3208. result.m[11] = initialM34;
  3209. result.m[12] = initialM41;
  3210. result.m[13] = initialM42;
  3211. result.m[14] = initialM43;
  3212. result.m[15] = initialM44;
  3213. return result;
  3214. };
  3215. /**
  3216. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.Compose = function (scale, rotation, translation) {
  3219. var result = Matrix.Identity();
  3220. Matrix.ComposeToRef(scale, rotation, translation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3225. */
  3226. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3227. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3228. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3229. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3230. result.setTranslation(translation);
  3231. };
  3232. /**
  3233. * Returns a new indentity Matrix.
  3234. */
  3235. Matrix.Identity = function () {
  3236. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3237. };
  3238. /**
  3239. * Sets the passed "result" as an identity matrix.
  3240. */
  3241. Matrix.IdentityToRef = function (result) {
  3242. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3243. };
  3244. /**
  3245. * Returns a new zero Matrix.
  3246. */
  3247. Matrix.Zero = function () {
  3248. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3249. };
  3250. /**
  3251. * Returns a new rotation matrix for "angle" radians around the X axis.
  3252. */
  3253. Matrix.RotationX = function (angle) {
  3254. var result = new Matrix();
  3255. Matrix.RotationXToRef(angle, result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Returns a new Matrix as the passed inverted one.
  3260. */
  3261. Matrix.Invert = function (source) {
  3262. var result = new Matrix();
  3263. source.invertToRef(result);
  3264. return result;
  3265. };
  3266. /**
  3267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3268. */
  3269. Matrix.RotationXToRef = function (angle, result) {
  3270. var s = Math.sin(angle);
  3271. var c = Math.cos(angle);
  3272. result.m[0] = 1.0;
  3273. result.m[15] = 1.0;
  3274. result.m[5] = c;
  3275. result.m[10] = c;
  3276. result.m[9] = -s;
  3277. result.m[6] = s;
  3278. result.m[1] = 0.0;
  3279. result.m[2] = 0.0;
  3280. result.m[3] = 0.0;
  3281. result.m[4] = 0.0;
  3282. result.m[7] = 0.0;
  3283. result.m[8] = 0.0;
  3284. result.m[11] = 0.0;
  3285. result.m[12] = 0.0;
  3286. result.m[13] = 0.0;
  3287. result.m[14] = 0.0;
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationY = function (angle) {
  3294. var result = new Matrix();
  3295. Matrix.RotationYToRef(angle, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3300. */
  3301. Matrix.RotationYToRef = function (angle, result) {
  3302. var s = Math.sin(angle);
  3303. var c = Math.cos(angle);
  3304. result.m[5] = 1.0;
  3305. result.m[15] = 1.0;
  3306. result.m[0] = c;
  3307. result.m[2] = -s;
  3308. result.m[8] = s;
  3309. result.m[10] = c;
  3310. result.m[1] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[6] = 0.0;
  3314. result.m[7] = 0.0;
  3315. result.m[9] = 0.0;
  3316. result.m[11] = 0.0;
  3317. result.m[12] = 0.0;
  3318. result.m[13] = 0.0;
  3319. result.m[14] = 0.0;
  3320. result._markAsUpdated();
  3321. };
  3322. /**
  3323. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZ = function (angle) {
  3326. var result = new Matrix();
  3327. Matrix.RotationZToRef(angle, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3332. */
  3333. Matrix.RotationZToRef = function (angle, result) {
  3334. var s = Math.sin(angle);
  3335. var c = Math.cos(angle);
  3336. result.m[10] = 1.0;
  3337. result.m[15] = 1.0;
  3338. result.m[0] = c;
  3339. result.m[1] = s;
  3340. result.m[4] = -s;
  3341. result.m[5] = c;
  3342. result.m[2] = 0.0;
  3343. result.m[3] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[8] = 0.0;
  3347. result.m[9] = 0.0;
  3348. result.m[11] = 0.0;
  3349. result.m[12] = 0.0;
  3350. result.m[13] = 0.0;
  3351. result.m[14] = 0.0;
  3352. result._markAsUpdated();
  3353. };
  3354. /**
  3355. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxis = function (axis, angle) {
  3358. var result = Matrix.Zero();
  3359. Matrix.RotationAxisToRef(axis, angle, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3364. */
  3365. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3366. var s = Math.sin(-angle);
  3367. var c = Math.cos(-angle);
  3368. var c1 = 1 - c;
  3369. axis.normalize();
  3370. result.m[0] = (axis.x * axis.x) * c1 + c;
  3371. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3372. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3373. result.m[3] = 0.0;
  3374. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3375. result.m[5] = (axis.y * axis.y) * c1 + c;
  3376. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3377. result.m[7] = 0.0;
  3378. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3379. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3380. result.m[10] = (axis.z * axis.z) * c1 + c;
  3381. result.m[11] = 0.0;
  3382. result.m[15] = 1.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3389. var result = new Matrix();
  3390. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3395. */
  3396. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3397. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3398. this._tempQuaternion.toRotationMatrix(result);
  3399. };
  3400. /**
  3401. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.Scaling = function (x, y, z) {
  3404. var result = Matrix.Zero();
  3405. Matrix.ScalingToRef(x, y, z, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3410. */
  3411. Matrix.ScalingToRef = function (x, y, z, result) {
  3412. result.m[0] = x;
  3413. result.m[1] = 0.0;
  3414. result.m[2] = 0.0;
  3415. result.m[3] = 0.0;
  3416. result.m[4] = 0.0;
  3417. result.m[5] = y;
  3418. result.m[6] = 0.0;
  3419. result.m[7] = 0.0;
  3420. result.m[8] = 0.0;
  3421. result.m[9] = 0.0;
  3422. result.m[10] = z;
  3423. result.m[11] = 0.0;
  3424. result.m[12] = 0.0;
  3425. result.m[13] = 0.0;
  3426. result.m[14] = 0.0;
  3427. result.m[15] = 1.0;
  3428. result._markAsUpdated();
  3429. };
  3430. /**
  3431. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.Translation = function (x, y, z) {
  3434. var result = Matrix.Identity();
  3435. Matrix.TranslationToRef(x, y, z, result);
  3436. return result;
  3437. };
  3438. /**
  3439. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3440. */
  3441. Matrix.TranslationToRef = function (x, y, z, result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3446. */
  3447. Matrix.Lerp = function (startValue, endValue, gradient) {
  3448. var result = Matrix.Zero();
  3449. for (var index = 0; index < 16; index++) {
  3450. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3451. }
  3452. result._markAsUpdated();
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix whose values are computed by :
  3457. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3458. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3459. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3460. */
  3461. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3462. var startScale = new Vector3(0, 0, 0);
  3463. var startRotation = new Quaternion();
  3464. var startTranslation = new Vector3(0, 0, 0);
  3465. startValue.decompose(startScale, startRotation, startTranslation);
  3466. var endScale = new Vector3(0, 0, 0);
  3467. var endRotation = new Quaternion();
  3468. var endTranslation = new Vector3(0, 0, 0);
  3469. endValue.decompose(endScale, endRotation, endTranslation);
  3470. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3471. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3472. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3473. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3474. };
  3475. /**
  3476. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3477. * This methods works for a Left-Handed system.
  3478. */
  3479. Matrix.LookAtLH = function (eye, target, up) {
  3480. var result = Matrix.Zero();
  3481. Matrix.LookAtLHToRef(eye, target, up, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3486. * This methods works for a Left-Handed system.
  3487. */
  3488. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3489. // Z axis
  3490. target.subtractToRef(eye, this._zAxis);
  3491. this._zAxis.normalize();
  3492. // X axis
  3493. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3494. if (this._xAxis.lengthSquared() === 0) {
  3495. this._xAxis.x = 1.0;
  3496. }
  3497. else {
  3498. this._xAxis.normalize();
  3499. }
  3500. // Y axis
  3501. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3502. this._yAxis.normalize();
  3503. // Eye angles
  3504. var ex = -Vector3.Dot(this._xAxis, eye);
  3505. var ey = -Vector3.Dot(this._yAxis, eye);
  3506. var ez = -Vector3.Dot(this._zAxis, eye);
  3507. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3508. };
  3509. /**
  3510. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3511. * This methods works for a Right-Handed system.
  3512. */
  3513. Matrix.LookAtRH = function (eye, target, up) {
  3514. var result = Matrix.Zero();
  3515. Matrix.LookAtRHToRef(eye, target, up, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3520. * This methods works for a Left-Handed system.
  3521. */
  3522. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3523. // Z axis
  3524. eye.subtractToRef(target, this._zAxis);
  3525. this._zAxis.normalize();
  3526. // X axis
  3527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3528. if (this._xAxis.lengthSquared() === 0) {
  3529. this._xAxis.x = 1.0;
  3530. }
  3531. else {
  3532. this._xAxis.normalize();
  3533. }
  3534. // Y axis
  3535. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3536. this._yAxis.normalize();
  3537. // Eye angles
  3538. var ex = -Vector3.Dot(this._xAxis, eye);
  3539. var ey = -Vector3.Dot(this._yAxis, eye);
  3540. var ez = -Vector3.Dot(this._zAxis, eye);
  3541. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3542. };
  3543. /**
  3544. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3545. */
  3546. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3547. var matrix = Matrix.Zero();
  3548. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3549. return matrix;
  3550. };
  3551. /**
  3552. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3553. */
  3554. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3555. var n = znear;
  3556. var f = zfar;
  3557. var a = 2.0 / width;
  3558. var b = 2.0 / height;
  3559. var c = 2.0 / (f - n);
  3560. var d = -(f + n) / (f - n);
  3561. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3562. };
  3563. /**
  3564. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3565. */
  3566. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3567. var matrix = Matrix.Zero();
  3568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3569. return matrix;
  3570. };
  3571. /**
  3572. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3573. */
  3574. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3575. var n = znear;
  3576. var f = zfar;
  3577. var a = 2.0 / (right - left);
  3578. var b = 2.0 / (top - bottom);
  3579. var c = 2.0 / (f - n);
  3580. var d = -(f + n) / (f - n);
  3581. var i0 = (left + right) / (left - right);
  3582. var i1 = (top + bottom) / (bottom - top);
  3583. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3587. */
  3588. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3589. var matrix = Matrix.Zero();
  3590. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3591. return matrix;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3595. */
  3596. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3597. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3598. result.m[10] *= -1.0;
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3602. */
  3603. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3604. var matrix = Matrix.Zero();
  3605. var n = znear;
  3606. var f = zfar;
  3607. var a = 2.0 * n / width;
  3608. var b = 2.0 * n / height;
  3609. var c = (f + n) / (f - n);
  3610. var d = -2.0 * f * n / (f - n);
  3611. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3616. */
  3617. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3618. var matrix = Matrix.Zero();
  3619. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3620. return matrix;
  3621. };
  3622. /**
  3623. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3624. */
  3625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3627. var n = znear;
  3628. var f = zfar;
  3629. var t = 1.0 / (Math.tan(fov * 0.5));
  3630. var a = isVerticalFovFixed ? (t / aspect) : t;
  3631. var b = isVerticalFovFixed ? t : (t * aspect);
  3632. var c = (f + n) / (f - n);
  3633. var d = -2.0 * f * n / (f - n);
  3634. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3635. };
  3636. /**
  3637. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3638. */
  3639. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3640. var matrix = Matrix.Zero();
  3641. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3642. return matrix;
  3643. };
  3644. /**
  3645. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3646. */
  3647. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3648. //alternatively this could be expressed as:
  3649. // m = PerspectiveFovLHToRef
  3650. // m[10] *= -1.0;
  3651. // m[11] *= -1.0;
  3652. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3653. var n = znear;
  3654. var f = zfar;
  3655. var t = 1.0 / (Math.tan(fov * 0.5));
  3656. var a = isVerticalFovFixed ? (t / aspect) : t;
  3657. var b = isVerticalFovFixed ? t : (t * aspect);
  3658. var c = -(f + n) / (f - n);
  3659. var d = -2 * f * n / (f - n);
  3660. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3661. };
  3662. /**
  3663. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3664. */
  3665. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3666. if (rightHanded === void 0) { rightHanded = false; }
  3667. var rightHandedFactor = rightHanded ? -1 : 1;
  3668. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3669. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3670. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3671. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3672. var xScale = 2.0 / (leftTan + rightTan);
  3673. var yScale = 2.0 / (upTan + downTan);
  3674. result.m[0] = xScale;
  3675. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3676. result.m[5] = yScale;
  3677. result.m[6] = result.m[7] = 0.0;
  3678. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3679. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3680. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3681. result.m[10] = -zfar / (znear - zfar);
  3682. result.m[11] = 1.0 * rightHandedFactor;
  3683. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3684. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3685. // result.m[14] = (znear * zfar) / (znear - zfar);
  3686. result._markAsUpdated();
  3687. };
  3688. /**
  3689. * Returns the final transformation matrix : world * view * projection * viewport
  3690. */
  3691. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3692. var cw = viewport.width;
  3693. var ch = viewport.height;
  3694. var cx = viewport.x;
  3695. var cy = viewport.y;
  3696. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3697. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3698. };
  3699. /**
  3700. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3701. */
  3702. Matrix.GetAsMatrix2x2 = function (matrix) {
  3703. return new Float32Array([
  3704. matrix.m[0], matrix.m[1],
  3705. matrix.m[4], matrix.m[5]
  3706. ]);
  3707. };
  3708. /**
  3709. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3710. */
  3711. Matrix.GetAsMatrix3x3 = function (matrix) {
  3712. return new Float32Array([
  3713. matrix.m[0], matrix.m[1], matrix.m[2],
  3714. matrix.m[4], matrix.m[5], matrix.m[6],
  3715. matrix.m[8], matrix.m[9], matrix.m[10]
  3716. ]);
  3717. };
  3718. /**
  3719. * Compute the transpose of the passed Matrix.
  3720. * Returns a new Matrix.
  3721. */
  3722. Matrix.Transpose = function (matrix) {
  3723. var result = new Matrix();
  3724. result.m[0] = matrix.m[0];
  3725. result.m[1] = matrix.m[4];
  3726. result.m[2] = matrix.m[8];
  3727. result.m[3] = matrix.m[12];
  3728. result.m[4] = matrix.m[1];
  3729. result.m[5] = matrix.m[5];
  3730. result.m[6] = matrix.m[9];
  3731. result.m[7] = matrix.m[13];
  3732. result.m[8] = matrix.m[2];
  3733. result.m[9] = matrix.m[6];
  3734. result.m[10] = matrix.m[10];
  3735. result.m[11] = matrix.m[14];
  3736. result.m[12] = matrix.m[3];
  3737. result.m[13] = matrix.m[7];
  3738. result.m[14] = matrix.m[11];
  3739. result.m[15] = matrix.m[15];
  3740. return result;
  3741. };
  3742. /**
  3743. * Returns a new Matrix as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.Reflection = function (plane) {
  3746. var matrix = new Matrix();
  3747. Matrix.ReflectionToRef(plane, matrix);
  3748. return matrix;
  3749. };
  3750. /**
  3751. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3752. */
  3753. Matrix.ReflectionToRef = function (plane, result) {
  3754. plane.normalize();
  3755. var x = plane.normal.x;
  3756. var y = plane.normal.y;
  3757. var z = plane.normal.z;
  3758. var temp = -2 * x;
  3759. var temp2 = -2 * y;
  3760. var temp3 = -2 * z;
  3761. result.m[0] = (temp * x) + 1;
  3762. result.m[1] = temp2 * x;
  3763. result.m[2] = temp3 * x;
  3764. result.m[3] = 0.0;
  3765. result.m[4] = temp * y;
  3766. result.m[5] = (temp2 * y) + 1;
  3767. result.m[6] = temp3 * y;
  3768. result.m[7] = 0.0;
  3769. result.m[8] = temp * z;
  3770. result.m[9] = temp2 * z;
  3771. result.m[10] = (temp3 * z) + 1;
  3772. result.m[11] = 0.0;
  3773. result.m[12] = temp * plane.d;
  3774. result.m[13] = temp2 * plane.d;
  3775. result.m[14] = temp3 * plane.d;
  3776. result.m[15] = 1.0;
  3777. result._markAsUpdated();
  3778. };
  3779. /**
  3780. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3781. */
  3782. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3783. result.m[0] = xaxis.x;
  3784. result.m[1] = xaxis.y;
  3785. result.m[2] = xaxis.z;
  3786. result.m[3] = 0.0;
  3787. result.m[4] = yaxis.x;
  3788. result.m[5] = yaxis.y;
  3789. result.m[6] = yaxis.z;
  3790. result.m[7] = 0.0;
  3791. result.m[8] = zaxis.x;
  3792. result.m[9] = zaxis.y;
  3793. result.m[10] = zaxis.z;
  3794. result.m[11] = 0.0;
  3795. result.m[12] = 0.0;
  3796. result.m[13] = 0.0;
  3797. result.m[14] = 0.0;
  3798. result.m[15] = 1.0;
  3799. result._markAsUpdated();
  3800. };
  3801. /**
  3802. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3803. */
  3804. Matrix.FromQuaternionToRef = function (quat, result) {
  3805. var xx = quat.x * quat.x;
  3806. var yy = quat.y * quat.y;
  3807. var zz = quat.z * quat.z;
  3808. var xy = quat.x * quat.y;
  3809. var zw = quat.z * quat.w;
  3810. var zx = quat.z * quat.x;
  3811. var yw = quat.y * quat.w;
  3812. var yz = quat.y * quat.z;
  3813. var xw = quat.x * quat.w;
  3814. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3815. result.m[1] = 2.0 * (xy + zw);
  3816. result.m[2] = 2.0 * (zx - yw);
  3817. result.m[3] = 0.0;
  3818. result.m[4] = 2.0 * (xy - zw);
  3819. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3820. result.m[6] = 2.0 * (yz + xw);
  3821. result.m[7] = 0.0;
  3822. result.m[8] = 2.0 * (zx + yw);
  3823. result.m[9] = 2.0 * (yz - xw);
  3824. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. Matrix._tempQuaternion = new Quaternion();
  3833. Matrix._xAxis = Vector3.Zero();
  3834. Matrix._yAxis = Vector3.Zero();
  3835. Matrix._zAxis = Vector3.Zero();
  3836. Matrix._updateFlagSeed = 0;
  3837. return Matrix;
  3838. }());
  3839. BABYLON.Matrix = Matrix;
  3840. var Plane = (function () {
  3841. /**
  3842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3843. */
  3844. function Plane(a, b, c, d) {
  3845. this.normal = new Vector3(a, b, c);
  3846. this.d = d;
  3847. }
  3848. /**
  3849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3850. */
  3851. Plane.prototype.asArray = function () {
  3852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3853. };
  3854. // Methods
  3855. /**
  3856. * Returns a new plane copied from the current Plane.
  3857. */
  3858. Plane.prototype.clone = function () {
  3859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3860. };
  3861. /**
  3862. * Returns the string "Plane".
  3863. */
  3864. Plane.prototype.getClassName = function () {
  3865. return "Plane";
  3866. };
  3867. /**
  3868. * Returns the Plane hash code.
  3869. */
  3870. Plane.prototype.getHashCode = function () {
  3871. var hash = this.normal.getHashCode();
  3872. hash = (hash * 397) ^ (this.d || 0);
  3873. return hash;
  3874. };
  3875. /**
  3876. * Normalize the current Plane in place.
  3877. * Returns the updated Plane.
  3878. */
  3879. Plane.prototype.normalize = function () {
  3880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3881. var magnitude = 0.0;
  3882. if (norm !== 0) {
  3883. magnitude = 1.0 / norm;
  3884. }
  3885. this.normal.x *= magnitude;
  3886. this.normal.y *= magnitude;
  3887. this.normal.z *= magnitude;
  3888. this.d *= magnitude;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3893. */
  3894. Plane.prototype.transform = function (transformation) {
  3895. var transposedMatrix = Matrix.Transpose(transformation);
  3896. var x = this.normal.x;
  3897. var y = this.normal.y;
  3898. var z = this.normal.z;
  3899. var d = this.d;
  3900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3904. return new Plane(normalX, normalY, normalZ, finalD);
  3905. };
  3906. /**
  3907. * Returns the dot product (float) of the point coordinates and the plane normal.
  3908. */
  3909. Plane.prototype.dotCoordinate = function (point) {
  3910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3911. };
  3912. /**
  3913. * Updates the current Plane from the plane defined by the three passed points.
  3914. * Returns the updated Plane.
  3915. */
  3916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3917. var x1 = point2.x - point1.x;
  3918. var y1 = point2.y - point1.y;
  3919. var z1 = point2.z - point1.z;
  3920. var x2 = point3.x - point1.x;
  3921. var y2 = point3.y - point1.y;
  3922. var z2 = point3.z - point1.z;
  3923. var yz = (y1 * z2) - (z1 * y2);
  3924. var xz = (z1 * x2) - (x1 * z2);
  3925. var xy = (x1 * y2) - (y1 * x2);
  3926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3927. var invPyth;
  3928. if (pyth !== 0) {
  3929. invPyth = 1.0 / pyth;
  3930. }
  3931. else {
  3932. invPyth = 0.0;
  3933. }
  3934. this.normal.x = yz * invPyth;
  3935. this.normal.y = xz * invPyth;
  3936. this.normal.z = xy * invPyth;
  3937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3942. */
  3943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3944. var dot = Vector3.Dot(this.normal, direction);
  3945. return (dot <= epsilon);
  3946. };
  3947. /**
  3948. * Returns the signed distance (float) from the passed point to the Plane.
  3949. */
  3950. Plane.prototype.signedDistanceTo = function (point) {
  3951. return Vector3.Dot(point, this.normal) + this.d;
  3952. };
  3953. // Statics
  3954. /**
  3955. * Returns a new Plane from the passed array.
  3956. */
  3957. Plane.FromArray = function (array) {
  3958. return new Plane(array[0], array[1], array[2], array[3]);
  3959. };
  3960. /**
  3961. * Returns a new Plane defined by the three passed points.
  3962. */
  3963. Plane.FromPoints = function (point1, point2, point3) {
  3964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3965. result.copyFromPoints(point1, point2, point3);
  3966. return result;
  3967. };
  3968. /**
  3969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3970. * Note : the vector "normal" is updated because normalized.
  3971. */
  3972. Plane.FromPositionAndNormal = function (origin, normal) {
  3973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3974. normal.normalize();
  3975. result.normal = normal;
  3976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3977. return result;
  3978. };
  3979. /**
  3980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3981. */
  3982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3984. return Vector3.Dot(point, normal) + d;
  3985. };
  3986. return Plane;
  3987. }());
  3988. BABYLON.Plane = Plane;
  3989. var Viewport = (function () {
  3990. /**
  3991. * Creates a Viewport object located at (x, y) and sized (width, height).
  3992. */
  3993. function Viewport(x, y, width, height) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.width = width;
  3997. this.height = height;
  3998. }
  3999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4000. if (renderWidthOrEngine._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. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4084. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4085. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4086. return Axis;
  4087. }());
  4088. BABYLON.Axis = Axis;
  4089. ;
  4090. var BezierCurve = (function () {
  4091. function BezierCurve() {
  4092. }
  4093. /**
  4094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4095. */
  4096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4097. // Extract X (which is equal to time here)
  4098. var f0 = 1 - 3 * x2 + 3 * x1;
  4099. var f1 = 3 * x2 - 6 * x1;
  4100. var f2 = 3 * x1;
  4101. var refinedT = t;
  4102. for (var i = 0; i < 5; i++) {
  4103. var refinedT2 = refinedT * refinedT;
  4104. var refinedT3 = refinedT2 * refinedT;
  4105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4107. refinedT -= (x - t) * slope;
  4108. refinedT = Math.min(1, Math.max(0, refinedT));
  4109. }
  4110. // Resolve cubic bezier for the given x
  4111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4113. Math.pow(refinedT, 3);
  4114. };
  4115. return BezierCurve;
  4116. }());
  4117. BABYLON.BezierCurve = BezierCurve;
  4118. var Orientation;
  4119. (function (Orientation) {
  4120. Orientation[Orientation["CW"] = 0] = "CW";
  4121. Orientation[Orientation["CCW"] = 1] = "CCW";
  4122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4123. var Angle = (function () {
  4124. /**
  4125. * Creates an Angle object of "radians" radians (float).
  4126. */
  4127. function Angle(radians) {
  4128. var _this = this;
  4129. /**
  4130. * Returns the Angle value in degrees (float).
  4131. */
  4132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4133. /**
  4134. * Returns the Angle value in radians (float).
  4135. */
  4136. this.radians = function () { return _this._radians; };
  4137. this._radians = radians;
  4138. if (this._radians < 0.0)
  4139. this._radians += (2.0 * Math.PI);
  4140. }
  4141. /**
  4142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4143. */
  4144. Angle.BetweenTwoPoints = function (a, b) {
  4145. var delta = b.subtract(a);
  4146. var theta = Math.atan2(delta.y, delta.x);
  4147. return new Angle(theta);
  4148. };
  4149. /**
  4150. * Returns a new Angle object from the passed float in radians.
  4151. */
  4152. Angle.FromRadians = function (radians) {
  4153. return new Angle(radians);
  4154. };
  4155. /**
  4156. * Returns a new Angle object from the passed float in degrees.
  4157. */
  4158. Angle.FromDegrees = function (degrees) {
  4159. return new Angle(degrees * Math.PI / 180.0);
  4160. };
  4161. return Angle;
  4162. }());
  4163. BABYLON.Angle = Angle;
  4164. var Arc2 = (function () {
  4165. /**
  4166. * Creates an Arc object from the three passed points : start, middle and end.
  4167. */
  4168. function Arc2(startPoint, midPoint, endPoint) {
  4169. this.startPoint = startPoint;
  4170. this.midPoint = midPoint;
  4171. this.endPoint = endPoint;
  4172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4176. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4179. var a1 = this.startAngle.degrees();
  4180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4182. // angles correction
  4183. if (a2 - a1 > +180.0)
  4184. a2 -= 360.0;
  4185. if (a2 - a1 < -180.0)
  4186. a2 += 360.0;
  4187. if (a3 - a2 > +180.0)
  4188. a3 -= 360.0;
  4189. if (a3 - a2 < -180.0)
  4190. a3 += 360.0;
  4191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4193. }
  4194. return Arc2;
  4195. }());
  4196. BABYLON.Arc2 = Arc2;
  4197. var Path2 = (function () {
  4198. /**
  4199. * Creates a Path2 object from the starting 2D coordinates x and y.
  4200. */
  4201. function Path2(x, y) {
  4202. this._points = new Array();
  4203. this._length = 0.0;
  4204. this.closed = false;
  4205. this._points.push(new Vector2(x, y));
  4206. }
  4207. /**
  4208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4209. * Returns the updated Path2.
  4210. */
  4211. Path2.prototype.addLineTo = function (x, y) {
  4212. if (closed) {
  4213. //Tools.Error("cannot add lines to closed paths");
  4214. return this;
  4215. }
  4216. var newPoint = new Vector2(x, y);
  4217. var previousPoint = this._points[this._points.length - 1];
  4218. this._points.push(newPoint);
  4219. this._length += newPoint.subtract(previousPoint).length();
  4220. return this;
  4221. };
  4222. /**
  4223. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4224. * Returns the updated Path2.
  4225. */
  4226. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4227. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4228. if (closed) {
  4229. //Tools.Error("cannot add arcs to closed paths");
  4230. return this;
  4231. }
  4232. var startPoint = this._points[this._points.length - 1];
  4233. var midPoint = new Vector2(midX, midY);
  4234. var endPoint = new Vector2(endX, endY);
  4235. var arc = new Arc2(startPoint, midPoint, endPoint);
  4236. var increment = arc.angle.radians() / numberOfSegments;
  4237. if (arc.orientation === Orientation.CW)
  4238. increment *= -1;
  4239. var currentAngle = arc.startAngle.radians() + increment;
  4240. for (var i = 0; i < numberOfSegments; i++) {
  4241. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4242. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4243. this.addLineTo(x, y);
  4244. currentAngle += increment;
  4245. }
  4246. return this;
  4247. };
  4248. /**
  4249. * Closes the Path2.
  4250. * Returns the Path2.
  4251. */
  4252. Path2.prototype.close = function () {
  4253. this.closed = true;
  4254. return this;
  4255. };
  4256. /**
  4257. * Returns the Path2 total length (float).
  4258. */
  4259. Path2.prototype.length = function () {
  4260. var result = this._length;
  4261. if (!this.closed) {
  4262. var lastPoint = this._points[this._points.length - 1];
  4263. var firstPoint = this._points[0];
  4264. result += (firstPoint.subtract(lastPoint).length());
  4265. }
  4266. return result;
  4267. };
  4268. /**
  4269. * Returns the Path2 internal array of points.
  4270. */
  4271. Path2.prototype.getPoints = function () {
  4272. return this._points;
  4273. };
  4274. /**
  4275. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4276. */
  4277. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4278. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4279. //Tools.Error("normalized length position should be between 0 and 1.");
  4280. return Vector2.Zero();
  4281. }
  4282. var lengthPosition = normalizedLengthPosition * this.length();
  4283. var previousOffset = 0;
  4284. for (var i = 0; i < this._points.length; i++) {
  4285. var j = (i + 1) % this._points.length;
  4286. var a = this._points[i];
  4287. var b = this._points[j];
  4288. var bToA = b.subtract(a);
  4289. var nextOffset = (bToA.length() + previousOffset);
  4290. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4291. var dir = bToA.normalize();
  4292. var localOffset = lengthPosition - previousOffset;
  4293. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4294. }
  4295. previousOffset = nextOffset;
  4296. }
  4297. //Tools.Error("internal error");
  4298. return Vector2.Zero();
  4299. };
  4300. /**
  4301. * Returns a new Path2 starting at the coordinates (x, y).
  4302. */
  4303. Path2.StartingAt = function (x, y) {
  4304. return new Path2(x, y);
  4305. };
  4306. return Path2;
  4307. }());
  4308. BABYLON.Path2 = Path2;
  4309. var Path3D = (function () {
  4310. /**
  4311. * new Path3D(path, normal, raw)
  4312. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4313. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4314. * path : an array of Vector3, the curve axis of the Path3D
  4315. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4316. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4317. */
  4318. function Path3D(path, firstNormal, raw) {
  4319. this.path = path;
  4320. this._curve = new Array();
  4321. this._distances = new Array();
  4322. this._tangents = new Array();
  4323. this._normals = new Array();
  4324. this._binormals = new Array();
  4325. for (var p = 0; p < path.length; p++) {
  4326. this._curve[p] = path[p].clone(); // hard copy
  4327. }
  4328. this._raw = raw || false;
  4329. this._compute(firstNormal);
  4330. }
  4331. /**
  4332. * Returns the Path3D array of successive Vector3 designing its curve.
  4333. */
  4334. Path3D.prototype.getCurve = function () {
  4335. return this._curve;
  4336. };
  4337. /**
  4338. * Returns an array populated with tangent vectors on each Path3D curve point.
  4339. */
  4340. Path3D.prototype.getTangents = function () {
  4341. return this._tangents;
  4342. };
  4343. /**
  4344. * Returns an array populated with normal vectors on each Path3D curve point.
  4345. */
  4346. Path3D.prototype.getNormals = function () {
  4347. return this._normals;
  4348. };
  4349. /**
  4350. * Returns an array populated with binormal vectors on each Path3D curve point.
  4351. */
  4352. Path3D.prototype.getBinormals = function () {
  4353. return this._binormals;
  4354. };
  4355. /**
  4356. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4357. */
  4358. Path3D.prototype.getDistances = function () {
  4359. return this._distances;
  4360. };
  4361. /**
  4362. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4363. * Returns the same object updated.
  4364. */
  4365. Path3D.prototype.update = function (path, firstNormal) {
  4366. for (var p = 0; p < path.length; p++) {
  4367. this._curve[p].x = path[p].x;
  4368. this._curve[p].y = path[p].y;
  4369. this._curve[p].z = path[p].z;
  4370. }
  4371. this._compute(firstNormal);
  4372. return this;
  4373. };
  4374. // private function compute() : computes tangents, normals and binormals
  4375. Path3D.prototype._compute = function (firstNormal) {
  4376. var l = this._curve.length;
  4377. // first and last tangents
  4378. this._tangents[0] = this._getFirstNonNullVector(0);
  4379. if (!this._raw) {
  4380. this._tangents[0].normalize();
  4381. }
  4382. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4383. if (!this._raw) {
  4384. this._tangents[l - 1].normalize();
  4385. }
  4386. // normals and binormals at first point : arbitrary vector with _normalVector()
  4387. var tg0 = this._tangents[0];
  4388. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4389. this._normals[0] = pp0;
  4390. if (!this._raw) {
  4391. this._normals[0].normalize();
  4392. }
  4393. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4394. if (!this._raw) {
  4395. this._binormals[0].normalize();
  4396. }
  4397. this._distances[0] = 0.0;
  4398. // normals and binormals : next points
  4399. var prev; // previous vector (segment)
  4400. var cur; // current vector (segment)
  4401. var curTang; // current tangent
  4402. // previous normal
  4403. var prevBinor; // previous binormal
  4404. for (var i = 1; i < l; i++) {
  4405. // tangents
  4406. prev = this._getLastNonNullVector(i);
  4407. if (i < l - 1) {
  4408. cur = this._getFirstNonNullVector(i);
  4409. this._tangents[i] = prev.add(cur);
  4410. this._tangents[i].normalize();
  4411. }
  4412. this._distances[i] = this._distances[i - 1] + prev.length();
  4413. // normals and binormals
  4414. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4415. curTang = this._tangents[i];
  4416. prevBinor = this._binormals[i - 1];
  4417. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4418. if (!this._raw) {
  4419. this._normals[i].normalize();
  4420. }
  4421. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4422. if (!this._raw) {
  4423. this._binormals[i].normalize();
  4424. }
  4425. }
  4426. };
  4427. // private function getFirstNonNullVector(index)
  4428. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4429. Path3D.prototype._getFirstNonNullVector = function (index) {
  4430. var i = 1;
  4431. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4432. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4433. i++;
  4434. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4435. }
  4436. return nNVector;
  4437. };
  4438. // private function getLastNonNullVector(index)
  4439. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4440. Path3D.prototype._getLastNonNullVector = function (index) {
  4441. var i = 1;
  4442. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4443. while (nLVector.length() === 0 && index > i + 1) {
  4444. i++;
  4445. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4446. }
  4447. return nLVector;
  4448. };
  4449. // private function normalVector(v0, vt, va) :
  4450. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4451. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4452. Path3D.prototype._normalVector = function (v0, vt, va) {
  4453. var normal0;
  4454. var tgl = vt.length();
  4455. if (tgl === 0.0) {
  4456. tgl = 1.0;
  4457. }
  4458. if (va === undefined || va === null) {
  4459. var point;
  4460. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4461. point = new Vector3(0.0, -1.0, 0.0);
  4462. }
  4463. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4464. point = new Vector3(1.0, 0.0, 0.0);
  4465. }
  4466. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4467. point = new Vector3(0.0, 0.0, 1.0);
  4468. }
  4469. normal0 = Vector3.Cross(vt, point);
  4470. }
  4471. else {
  4472. normal0 = Vector3.Cross(vt, va);
  4473. Vector3.CrossToRef(normal0, vt, normal0);
  4474. }
  4475. normal0.normalize();
  4476. return normal0;
  4477. };
  4478. return Path3D;
  4479. }());
  4480. BABYLON.Path3D = Path3D;
  4481. var Curve3 = (function () {
  4482. /**
  4483. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4484. * A Curve3 is designed from a series of successive Vector3.
  4485. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4486. */
  4487. function Curve3(points) {
  4488. this._length = 0.0;
  4489. this._points = points;
  4490. this._length = this._computeLength(points);
  4491. }
  4492. /**
  4493. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4494. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4495. * @param v1 (Vector3) the control point
  4496. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4500. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4501. var bez = new Array();
  4502. var equation = function (t, val0, val1, val2) {
  4503. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4504. return res;
  4505. };
  4506. for (var i = 0; i <= nbPoints; i++) {
  4507. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4508. }
  4509. return new Curve3(bez);
  4510. };
  4511. /**
  4512. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4513. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4514. * @param v1 (Vector3) the first control point
  4515. * @param v2 (Vector3) the second control point
  4516. * @param v3 (Vector3) the end point of the Cubic Bezier
  4517. * @param nbPoints (integer) the wanted number of points in the curve
  4518. */
  4519. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4520. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4521. var bez = new Array();
  4522. var equation = function (t, val0, val1, val2, val3) {
  4523. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4524. return res;
  4525. };
  4526. for (var i = 0; i <= nbPoints; i++) {
  4527. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4528. }
  4529. return new Curve3(bez);
  4530. };
  4531. /**
  4532. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4533. * @param p1 (Vector3) the origin point of the Hermite Spline
  4534. * @param t1 (Vector3) the tangent vector at the origin point
  4535. * @param p2 (Vector3) the end point of the Hermite Spline
  4536. * @param t2 (Vector3) the tangent vector at the end point
  4537. * @param nbPoints (integer) the wanted number of points in the curve
  4538. */
  4539. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4540. var hermite = new Array();
  4541. var step = 1.0 / nbPoints;
  4542. for (var i = 0; i <= nbPoints; i++) {
  4543. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4544. }
  4545. return new Curve3(hermite);
  4546. };
  4547. /**
  4548. * Returns a Curve3 object along a CatmullRom Spline curve :
  4549. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4550. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4551. */
  4552. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4553. var totalPoints = new Array();
  4554. totalPoints.push(points[0].clone());
  4555. Array.prototype.push.apply(totalPoints, points);
  4556. totalPoints.push(points[points.length - 1].clone());
  4557. var catmullRom = new Array();
  4558. var step = 1.0 / nbPoints;
  4559. for (var i = 0; i < totalPoints.length - 3; i++) {
  4560. var amount = 0.0;
  4561. for (var c = 0; c < nbPoints; c++) {
  4562. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4563. amount += step;
  4564. }
  4565. }
  4566. i--;
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. return new Curve3(catmullRom);
  4569. };
  4570. /**
  4571. * Returns the Curve3 stored array of successive Vector3
  4572. */
  4573. Curve3.prototype.getPoints = function () {
  4574. return this._points;
  4575. };
  4576. /**
  4577. * Returns the computed length (float) of the curve.
  4578. */
  4579. Curve3.prototype.length = function () {
  4580. return this._length;
  4581. };
  4582. /**
  4583. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4584. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4585. * curveA and curveB keep unchanged.
  4586. */
  4587. Curve3.prototype.continue = function (curve) {
  4588. var lastPoint = this._points[this._points.length - 1];
  4589. var continuedPoints = this._points.slice();
  4590. var curvePoints = curve.getPoints();
  4591. for (var i = 1; i < curvePoints.length; i++) {
  4592. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4593. }
  4594. var continuedCurve = new Curve3(continuedPoints);
  4595. return continuedCurve;
  4596. };
  4597. Curve3.prototype._computeLength = function (path) {
  4598. var l = 0;
  4599. for (var i = 1; i < path.length; i++) {
  4600. l += (path[i].subtract(path[i - 1])).length();
  4601. }
  4602. return l;
  4603. };
  4604. return Curve3;
  4605. }());
  4606. BABYLON.Curve3 = Curve3;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4644. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4645. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4646. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4647. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4648. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4649. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero(),
  4651. Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4653. return Tmp;
  4654. }());
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. MathTmp.Vector3 = [Vector3.Zero()];
  4661. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4662. MathTmp.Quaternion = [Quaternion.Zero()];
  4663. return MathTmp;
  4664. }());
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. var BABYLON;
  4668. (function (BABYLON) {
  4669. var Scalar = (function () {
  4670. function Scalar() {
  4671. }
  4672. /**
  4673. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4674. */
  4675. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4676. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4677. var num = a - b;
  4678. return -epsilon <= num && num <= epsilon;
  4679. };
  4680. /**
  4681. * Returns a string : the upper case translation of the number i to hexadecimal.
  4682. */
  4683. Scalar.ToHex = function (i) {
  4684. var str = i.toString(16);
  4685. if (i <= 15) {
  4686. return ("0" + str).toUpperCase();
  4687. }
  4688. return str.toUpperCase();
  4689. };
  4690. /**
  4691. * Returns -1 if value is negative and +1 is value is positive.
  4692. * Returns the value itself if it's equal to zero.
  4693. */
  4694. Scalar.Sign = function (value) {
  4695. value = +value; // convert to a number
  4696. if (value === 0 || isNaN(value))
  4697. return value;
  4698. return value > 0 ? 1 : -1;
  4699. };
  4700. /**
  4701. * Returns the value itself if it's between min and max.
  4702. * Returns min if the value is lower than min.
  4703. * Returns max if the value is greater than max.
  4704. */
  4705. Scalar.Clamp = function (value, min, max) {
  4706. if (min === void 0) { min = 0; }
  4707. if (max === void 0) { max = 1; }
  4708. return Math.min(max, Math.max(min, value));
  4709. };
  4710. /**
  4711. * Returns the log2 of value.
  4712. */
  4713. Scalar.Log2 = function (value) {
  4714. return Math.log(value) * Math.LOG2E;
  4715. };
  4716. /**
  4717. * Loops the value, so that it is never larger than length and never smaller than 0.
  4718. *
  4719. * This is similar to the modulo operator but it works with floating point numbers.
  4720. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4721. * With t = 5 and length = 2.5, the result would be 0.0.
  4722. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4723. */
  4724. Scalar.Repeat = function (value, length) {
  4725. return value - Math.floor(value / length) * length;
  4726. };
  4727. /**
  4728. * Normalize the value between 0.0 and 1.0 using min and max values
  4729. */
  4730. Scalar.Normalize = function (value, min, max) {
  4731. return (value - min) / (max - min);
  4732. };
  4733. /**
  4734. * Denormalize the value from 0.0 and 1.0 using min and max values
  4735. */
  4736. Scalar.Denormalize = function (normalized, min, max) {
  4737. return (normalized * (max - min) + min);
  4738. };
  4739. /**
  4740. * Calculates the shortest difference between two given angles given in degrees.
  4741. */
  4742. Scalar.DeltaAngle = function (current, target) {
  4743. var num = Scalar.Repeat(target - current, 360.0);
  4744. if (num > 180.0) {
  4745. num -= 360.0;
  4746. }
  4747. return num;
  4748. };
  4749. /**
  4750. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4751. *
  4752. * The returned value will move back and forth between 0 and length
  4753. */
  4754. Scalar.PingPong = function (tx, length) {
  4755. var t = Scalar.Repeat(tx, length * 2.0);
  4756. return length - Math.abs(t - length);
  4757. };
  4758. /**
  4759. * Interpolates between min and max with smoothing at the limits.
  4760. *
  4761. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4762. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4763. */
  4764. Scalar.SmoothStep = function (from, to, tx) {
  4765. var t = Scalar.Clamp(tx);
  4766. t = -2.0 * t * t * t + 3.0 * t * t;
  4767. return to * t + from * (1.0 - t);
  4768. };
  4769. /**
  4770. * Moves a value current towards target.
  4771. *
  4772. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4773. * Negative values of maxDelta pushes the value away from target.
  4774. */
  4775. Scalar.MoveTowards = function (current, target, maxDelta) {
  4776. var result = 0;
  4777. if (Math.abs(target - current) <= maxDelta) {
  4778. result = target;
  4779. }
  4780. else {
  4781. result = current + Scalar.Sign(target - current) * maxDelta;
  4782. }
  4783. return result;
  4784. };
  4785. /**
  4786. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4787. *
  4788. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4789. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4790. */
  4791. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4792. var num = Scalar.DeltaAngle(current, target);
  4793. var result = 0;
  4794. if (-maxDelta < num && num < maxDelta) {
  4795. result = target;
  4796. }
  4797. else {
  4798. target = current + num;
  4799. result = Scalar.MoveTowards(current, target, maxDelta);
  4800. }
  4801. return result;
  4802. };
  4803. /**
  4804. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4805. */
  4806. Scalar.Lerp = function (start, end, amount) {
  4807. return start + ((end - start) * amount);
  4808. };
  4809. /**
  4810. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4811. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4812. */
  4813. Scalar.LerpAngle = function (start, end, amount) {
  4814. var num = Scalar.Repeat(end - start, 360.0);
  4815. if (num > 180.0) {
  4816. num -= 360.0;
  4817. }
  4818. return start + num * Scalar.Clamp(amount);
  4819. };
  4820. /**
  4821. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4822. */
  4823. Scalar.InverseLerp = function (a, b, value) {
  4824. var result = 0;
  4825. if (a != b) {
  4826. result = Scalar.Clamp((value - a) / (b - a));
  4827. }
  4828. else {
  4829. result = 0.0;
  4830. }
  4831. return result;
  4832. };
  4833. /**
  4834. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4835. */
  4836. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4837. var squared = amount * amount;
  4838. var cubed = amount * squared;
  4839. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4840. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4841. var part3 = (cubed - (2.0 * squared)) + amount;
  4842. var part4 = cubed - squared;
  4843. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4844. };
  4845. /**
  4846. * Returns a random float number between and min and max values
  4847. */
  4848. Scalar.RandomRange = function (min, max) {
  4849. if (min === max)
  4850. return min;
  4851. return ((Math.random() * (max - min)) + min);
  4852. };
  4853. /**
  4854. * This function returns percentage of a number in a given range.
  4855. *
  4856. * RangeToPercent(40,20,60) will return 0.5 (50%)
  4857. * RangeToPercent(34,0,100) will return 0.34 (34%)
  4858. */
  4859. Scalar.RangeToPercent = function (number, min, max) {
  4860. return ((number - min) / (max - min));
  4861. };
  4862. /**
  4863. * This function returns number that corresponds to the percentage in a given range.
  4864. *
  4865. * PercentToRange(0.34,0,100) will return 34.
  4866. */
  4867. Scalar.PercentToRange = function (percent, min, max) {
  4868. return ((max - min) * percent + min);
  4869. };
  4870. return Scalar;
  4871. }());
  4872. BABYLON.Scalar = Scalar;
  4873. })(BABYLON || (BABYLON = {}));
  4874. //# sourceMappingURL=babylon.math.scalar.js.map
  4875. //# sourceMappingURL=babylon.mixins.js.map
  4876. var BABYLON;
  4877. (function (BABYLON) {
  4878. var __decoratorInitialStore = {};
  4879. var __mergedStore = {};
  4880. var _copySource = function (creationFunction, source, instanciate) {
  4881. var destination = creationFunction();
  4882. // Tags
  4883. if (BABYLON.Tags) {
  4884. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4885. }
  4886. var classStore = getMergedStore(destination);
  4887. // Properties
  4888. for (var property in classStore) {
  4889. var propertyDescriptor = classStore[property];
  4890. var sourceProperty = source[property];
  4891. var propertyType = propertyDescriptor.type;
  4892. if (sourceProperty !== undefined && sourceProperty !== null) {
  4893. switch (propertyType) {
  4894. case 0: // Value
  4895. case 6:// Mesh reference
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1: // Texture
  4899. case 2: // Color3
  4900. case 3: // FresnelParameters
  4901. case 4: // Vector2
  4902. case 5: // Vector3
  4903. case 7:// Color Curves
  4904. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  4905. break;
  4906. }
  4907. }
  4908. }
  4909. return destination;
  4910. };
  4911. function getDirectStore(target) {
  4912. var classKey = target.getClassName();
  4913. if (!__decoratorInitialStore[classKey]) {
  4914. __decoratorInitialStore[classKey] = {};
  4915. }
  4916. return __decoratorInitialStore[classKey];
  4917. }
  4918. /**
  4919. * Return the list of properties flagged as serializable
  4920. * @param target: host object
  4921. */
  4922. function getMergedStore(target) {
  4923. var classKey = target.getClassName();
  4924. if (__mergedStore[classKey]) {
  4925. return __mergedStore[classKey];
  4926. }
  4927. __mergedStore[classKey] = {};
  4928. var store = __mergedStore[classKey];
  4929. var currentTarget = target;
  4930. var currentKey = classKey;
  4931. while (currentKey) {
  4932. var initialStore = __decoratorInitialStore[currentKey];
  4933. for (var property in initialStore) {
  4934. store[property] = initialStore[property];
  4935. }
  4936. var parent_1 = void 0;
  4937. var done = false;
  4938. do {
  4939. parent_1 = Object.getPrototypeOf(currentTarget);
  4940. if (!parent_1.getClassName) {
  4941. done = true;
  4942. break;
  4943. }
  4944. if (parent_1.getClassName() !== currentKey) {
  4945. break;
  4946. }
  4947. currentTarget = parent_1;
  4948. } while (parent_1);
  4949. if (done) {
  4950. break;
  4951. }
  4952. currentKey = parent_1.getClassName();
  4953. currentTarget = parent_1;
  4954. }
  4955. return store;
  4956. }
  4957. function generateSerializableMember(type, sourceName) {
  4958. return function (target, propertyKey) {
  4959. var classStore = getDirectStore(target);
  4960. if (!classStore[propertyKey]) {
  4961. classStore[propertyKey] = { type: type, sourceName: sourceName };
  4962. }
  4963. };
  4964. }
  4965. function generateExpandMember(setCallback, targetKey) {
  4966. return function (target, propertyKey) {
  4967. var key = targetKey || ("_" + propertyKey);
  4968. Object.defineProperty(target, propertyKey, {
  4969. get: function () {
  4970. return this[key];
  4971. },
  4972. set: function (value) {
  4973. if (this[key] === value) {
  4974. return;
  4975. }
  4976. this[key] = value;
  4977. target[setCallback].apply(this);
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. };
  4983. }
  4984. function expandToProperty(callback, targetKey) {
  4985. return generateExpandMember(callback, targetKey);
  4986. }
  4987. BABYLON.expandToProperty = expandToProperty;
  4988. function serialize(sourceName) {
  4989. return generateSerializableMember(0, sourceName); // value member
  4990. }
  4991. BABYLON.serialize = serialize;
  4992. function serializeAsTexture(sourceName) {
  4993. return generateSerializableMember(1, sourceName); // texture member
  4994. }
  4995. BABYLON.serializeAsTexture = serializeAsTexture;
  4996. function serializeAsColor3(sourceName) {
  4997. return generateSerializableMember(2, sourceName); // color3 member
  4998. }
  4999. BABYLON.serializeAsColor3 = serializeAsColor3;
  5000. function serializeAsFresnelParameters(sourceName) {
  5001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5002. }
  5003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5004. function serializeAsVector2(sourceName) {
  5005. return generateSerializableMember(4, sourceName); // vector2 member
  5006. }
  5007. BABYLON.serializeAsVector2 = serializeAsVector2;
  5008. function serializeAsVector3(sourceName) {
  5009. return generateSerializableMember(5, sourceName); // vector3 member
  5010. }
  5011. BABYLON.serializeAsVector3 = serializeAsVector3;
  5012. function serializeAsMeshReference(sourceName) {
  5013. return generateSerializableMember(6, sourceName); // mesh reference member
  5014. }
  5015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5016. function serializeAsColorCurves(sourceName) {
  5017. return generateSerializableMember(7, sourceName); // color curves
  5018. }
  5019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5020. function serializeAsColor4(sourceName) {
  5021. return generateSerializableMember(8, sourceName); // color 4
  5022. }
  5023. BABYLON.serializeAsColor4 = serializeAsColor4;
  5024. function serializeAsImageProcessingConfiguration(sourceName) {
  5025. return generateSerializableMember(9, sourceName); // image processing
  5026. }
  5027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5028. var SerializationHelper = (function () {
  5029. function SerializationHelper() {
  5030. }
  5031. SerializationHelper.Serialize = function (entity, serializationObject) {
  5032. if (!serializationObject) {
  5033. serializationObject = {};
  5034. }
  5035. // Tags
  5036. if (BABYLON.Tags) {
  5037. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5038. }
  5039. var serializedProperties = getMergedStore(entity);
  5040. // Properties
  5041. for (var property in serializedProperties) {
  5042. var propertyDescriptor = serializedProperties[property];
  5043. var targetPropertyName = propertyDescriptor.sourceName || property;
  5044. var propertyType = propertyDescriptor.type;
  5045. var sourceProperty = entity[property];
  5046. if (sourceProperty !== undefined && sourceProperty !== null) {
  5047. switch (propertyType) {
  5048. case 0:// Value
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:// Texture
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:// Color3
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:// FresnelParameters
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:// Vector2
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:// Vector3
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:// Mesh reference
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:// Color Curves
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:// Color 4
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:// Image Processing
  5076. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. return serializationObject;
  5082. };
  5083. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5084. var destination = creationFunction();
  5085. // Tags
  5086. if (BABYLON.Tags) {
  5087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5088. }
  5089. var classStore = getMergedStore(destination);
  5090. // Properties
  5091. for (var property in classStore) {
  5092. var propertyDescriptor = classStore[property];
  5093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5094. var propertyType = propertyDescriptor.type;
  5095. if (sourceProperty !== undefined && sourceProperty !== null) {
  5096. switch (propertyType) {
  5097. case 0:// Value
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:// Texture
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:// Color3
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:// FresnelParameters
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:// Vector2
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:// Vector3
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:// Mesh reference
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:// Color Curves
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:// Color 4
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:// Image Processing
  5125. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. return destination;
  5131. };
  5132. SerializationHelper.Clone = function (creationFunction, source) {
  5133. return _copySource(creationFunction, source, false);
  5134. };
  5135. SerializationHelper.Instanciate = function (creationFunction, source) {
  5136. return _copySource(creationFunction, source, true);
  5137. };
  5138. return SerializationHelper;
  5139. }());
  5140. BABYLON.SerializationHelper = SerializationHelper;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.decorators.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. /**
  5146. * A class serves as a medium between the observable and its observers
  5147. */
  5148. var EventState = (function () {
  5149. /**
  5150. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5151. */
  5152. function EventState(mask, skipNextObservers) {
  5153. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5154. this.initalize(mask, skipNextObservers);
  5155. }
  5156. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5157. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5158. this.mask = mask;
  5159. this.skipNextObservers = skipNextObservers;
  5160. return this;
  5161. };
  5162. return EventState;
  5163. }());
  5164. BABYLON.EventState = EventState;
  5165. /**
  5166. * Represent an Observer registered to a given Observable object.
  5167. */
  5168. var Observer = (function () {
  5169. function Observer(callback, mask) {
  5170. this.callback = callback;
  5171. this.mask = mask;
  5172. }
  5173. return Observer;
  5174. }());
  5175. BABYLON.Observer = Observer;
  5176. /**
  5177. * The Observable class is a simple implementation of the Observable pattern.
  5178. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5179. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5180. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5181. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5182. */
  5183. var Observable = (function () {
  5184. function Observable() {
  5185. this._observers = new Array();
  5186. this._eventState = new EventState(0);
  5187. }
  5188. /**
  5189. * Create a new Observer with the specified callback
  5190. * @param callback the callback that will be executed for that Observer
  5191. * @param mask the mask used to filter observers
  5192. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5193. */
  5194. Observable.prototype.add = function (callback, mask, insertFirst) {
  5195. if (mask === void 0) { mask = -1; }
  5196. if (insertFirst === void 0) { insertFirst = false; }
  5197. if (!callback) {
  5198. return null;
  5199. }
  5200. var observer = new Observer(callback, mask);
  5201. if (insertFirst) {
  5202. this._observers.unshift(observer);
  5203. }
  5204. else {
  5205. this._observers.push(observer);
  5206. }
  5207. return observer;
  5208. };
  5209. /**
  5210. * Remove an Observer from the Observable object
  5211. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5212. */
  5213. Observable.prototype.remove = function (observer) {
  5214. var index = this._observers.indexOf(observer);
  5215. if (index !== -1) {
  5216. this._observers.splice(index, 1);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. /**
  5222. * Remove a callback from the Observable object
  5223. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5224. */
  5225. Observable.prototype.removeCallback = function (callback) {
  5226. for (var index = 0; index < this._observers.length; index++) {
  5227. if (this._observers[index].callback === callback) {
  5228. this._observers.splice(index, 1);
  5229. return true;
  5230. }
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Notify all Observers by calling their respective callback with the given data
  5236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5237. * @param eventData
  5238. * @param mask
  5239. */
  5240. Observable.prototype.notifyObservers = function (eventData, mask) {
  5241. if (mask === void 0) { mask = -1; }
  5242. var state = this._eventState;
  5243. state.mask = mask;
  5244. state.skipNextObservers = false;
  5245. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5246. var obs = _a[_i];
  5247. if (obs.mask & mask) {
  5248. obs.callback(eventData, state);
  5249. }
  5250. if (state.skipNextObservers) {
  5251. return false;
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. /**
  5257. * return true is the Observable has at least one Observer registered
  5258. */
  5259. Observable.prototype.hasObservers = function () {
  5260. return this._observers.length > 0;
  5261. };
  5262. /**
  5263. * Clear the list of observers
  5264. */
  5265. Observable.prototype.clear = function () {
  5266. this._observers = new Array();
  5267. };
  5268. /**
  5269. * Clone the current observable
  5270. */
  5271. Observable.prototype.clone = function () {
  5272. var result = new Observable();
  5273. result._observers = this._observers.slice(0);
  5274. return result;
  5275. };
  5276. /**
  5277. * Does this observable handles observer registered with a given mask
  5278. * @param {number} trigger - the mask to be tested
  5279. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5280. **/
  5281. Observable.prototype.hasSpecificMask = function (mask) {
  5282. if (mask === void 0) { mask = -1; }
  5283. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5284. var obs = _a[_i];
  5285. if (obs.mask & mask && obs.mask === mask) {
  5286. return true;
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. return Observable;
  5292. }());
  5293. BABYLON.Observable = Observable;
  5294. })(BABYLON || (BABYLON = {}));
  5295. //# sourceMappingURL=babylon.observable.js.map
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var SmartArray = (function () {
  5299. function SmartArray(capacity) {
  5300. this.length = 0;
  5301. this._duplicateId = 0;
  5302. this.data = new Array(capacity);
  5303. this._id = SmartArray._GlobalId++;
  5304. }
  5305. SmartArray.prototype.push = function (value) {
  5306. this.data[this.length++] = value;
  5307. if (this.length > this.data.length) {
  5308. this.data.length *= 2;
  5309. }
  5310. if (!value.__smartArrayFlags) {
  5311. value.__smartArrayFlags = {};
  5312. }
  5313. value.__smartArrayFlags[this._id] = this._duplicateId;
  5314. };
  5315. SmartArray.prototype.forEach = function (func) {
  5316. for (var index = 0; index < this.length; index++) {
  5317. func(this.data[index]);
  5318. }
  5319. };
  5320. SmartArray.prototype.pushNoDuplicate = function (value) {
  5321. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5322. return false;
  5323. }
  5324. this.push(value);
  5325. return true;
  5326. };
  5327. SmartArray.prototype.sort = function (compareFn) {
  5328. this.data.sort(compareFn);
  5329. };
  5330. SmartArray.prototype.reset = function () {
  5331. this.length = 0;
  5332. this._duplicateId++;
  5333. };
  5334. SmartArray.prototype.dispose = function () {
  5335. this.reset();
  5336. if (this.data) {
  5337. this.data.length = 0;
  5338. this.data = null;
  5339. }
  5340. };
  5341. SmartArray.prototype.concat = function (array) {
  5342. if (array.length === 0) {
  5343. return;
  5344. }
  5345. if (this.length + array.length > this.data.length) {
  5346. this.data.length = (this.length + array.length) * 2;
  5347. }
  5348. for (var index = 0; index < array.length; index++) {
  5349. this.data[this.length++] = (array.data || array)[index];
  5350. }
  5351. };
  5352. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5353. if (array.length === 0) {
  5354. return;
  5355. }
  5356. if (this.length + array.length > this.data.length) {
  5357. this.data.length = (this.length + array.length) * 2;
  5358. }
  5359. for (var index = 0; index < array.length; index++) {
  5360. var item = (array.data || array)[index];
  5361. this.pushNoDuplicate(item);
  5362. }
  5363. };
  5364. SmartArray.prototype.indexOf = function (value) {
  5365. var position = this.data.indexOf(value);
  5366. if (position >= this.length) {
  5367. return -1;
  5368. }
  5369. return position;
  5370. };
  5371. SmartArray.prototype.contains = function (value) {
  5372. return this.data.indexOf(value) !== -1;
  5373. };
  5374. // Statics
  5375. SmartArray._GlobalId = 0;
  5376. return SmartArray;
  5377. }());
  5378. BABYLON.SmartArray = SmartArray;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.smartArray.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. // Screenshots
  5384. var screenshotCanvas;
  5385. var cloneValue = function (source, destinationObject) {
  5386. if (!source)
  5387. return null;
  5388. if (source instanceof BABYLON.Mesh) {
  5389. return null;
  5390. }
  5391. if (source instanceof BABYLON.SubMesh) {
  5392. return source.clone(destinationObject);
  5393. }
  5394. else if (source.clone) {
  5395. return source.clone();
  5396. }
  5397. return null;
  5398. };
  5399. var Tools = (function () {
  5400. function Tools() {
  5401. }
  5402. ;
  5403. /**
  5404. * Interpolates between a and b via alpha
  5405. * @param a The lower value (returned when alpha = 0)
  5406. * @param b The upper value (returned when alpha = 1)
  5407. * @param alpha The interpolation-factor
  5408. * @return The mixed value
  5409. */
  5410. Tools.Mix = function (a, b, alpha) {
  5411. return a * (1 - alpha) + b * alpha;
  5412. };
  5413. Tools.Instantiate = function (className) {
  5414. var arr = className.split(".");
  5415. var fn = (window || this);
  5416. for (var i = 0, len = arr.length; i < len; i++) {
  5417. fn = fn[arr[i]];
  5418. }
  5419. if (typeof fn !== "function") {
  5420. return null;
  5421. }
  5422. return fn;
  5423. };
  5424. Tools.SetImmediate = function (action) {
  5425. if (window.setImmediate) {
  5426. window.setImmediate(action);
  5427. }
  5428. else {
  5429. setTimeout(action, 1);
  5430. }
  5431. };
  5432. Tools.IsExponentOfTwo = function (value) {
  5433. var count = 1;
  5434. do {
  5435. count *= 2;
  5436. } while (count < value);
  5437. return count === value;
  5438. };
  5439. /**
  5440. * Find the next highest power of two.
  5441. * @param x Number to start search from.
  5442. * @return Next highest power of two.
  5443. */
  5444. Tools.CeilingPOT = function (x) {
  5445. x--;
  5446. x |= x >> 1;
  5447. x |= x >> 2;
  5448. x |= x >> 4;
  5449. x |= x >> 8;
  5450. x |= x >> 16;
  5451. x++;
  5452. return x;
  5453. };
  5454. /**
  5455. * Find the next lowest power of two.
  5456. * @param x Number to start search from.
  5457. * @return Next lowest power of two.
  5458. */
  5459. Tools.FloorPOT = function (x) {
  5460. x = x | (x >> 1);
  5461. x = x | (x >> 2);
  5462. x = x | (x >> 4);
  5463. x = x | (x >> 8);
  5464. x = x | (x >> 16);
  5465. return x - (x >> 1);
  5466. };
  5467. /**
  5468. * Find the nearest power of two.
  5469. * @param x Number to start search from.
  5470. * @return Next nearest power of two.
  5471. */
  5472. Tools.NearestPOT = function (x) {
  5473. var c = Tools.CeilingPOT(x);
  5474. var f = Tools.FloorPOT(x);
  5475. return (c - x) > (x - f) ? f : c;
  5476. };
  5477. Tools.GetExponentOfTwo = function (value, max, mode) {
  5478. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5479. var pot;
  5480. switch (mode) {
  5481. case BABYLON.Engine.SCALEMODE_FLOOR:
  5482. pot = Tools.FloorPOT(value);
  5483. break;
  5484. case BABYLON.Engine.SCALEMODE_NEAREST:
  5485. pot = Tools.NearestPOT(value);
  5486. break;
  5487. case BABYLON.Engine.SCALEMODE_CEILING:
  5488. pot = Tools.CeilingPOT(value);
  5489. break;
  5490. }
  5491. return Math.min(pot, max);
  5492. };
  5493. Tools.GetFilename = function (path) {
  5494. var index = path.lastIndexOf("/");
  5495. if (index < 0)
  5496. return path;
  5497. return path.substring(index + 1);
  5498. };
  5499. Tools.GetDOMTextContent = function (element) {
  5500. var result = "";
  5501. var child = element.firstChild;
  5502. while (child) {
  5503. if (child.nodeType === 3) {
  5504. result += child.textContent;
  5505. }
  5506. child = child.nextSibling;
  5507. }
  5508. return result;
  5509. };
  5510. Tools.ToDegrees = function (angle) {
  5511. return angle * 180 / Math.PI;
  5512. };
  5513. Tools.ToRadians = function (angle) {
  5514. return angle * Math.PI / 180;
  5515. };
  5516. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5517. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5518. var output = "";
  5519. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5520. var i = 0;
  5521. var bytes = new Uint8Array(buffer);
  5522. while (i < bytes.length) {
  5523. chr1 = bytes[i++];
  5524. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5525. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5526. enc1 = chr1 >> 2;
  5527. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5528. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5529. enc4 = chr3 & 63;
  5530. if (isNaN(chr2)) {
  5531. enc3 = enc4 = 64;
  5532. }
  5533. else if (isNaN(chr3)) {
  5534. enc4 = 64;
  5535. }
  5536. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5537. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5538. }
  5539. return "data:image/png;base64," + output;
  5540. };
  5541. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5542. if (bias === void 0) { bias = null; }
  5543. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5544. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5545. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5546. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5547. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5548. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5549. }
  5550. if (bias) {
  5551. minimum.x -= minimum.x * bias.x + bias.y;
  5552. minimum.y -= minimum.y * bias.x + bias.y;
  5553. minimum.z -= minimum.z * bias.x + bias.y;
  5554. maximum.x += maximum.x * bias.x + bias.y;
  5555. maximum.y += maximum.y * bias.x + bias.y;
  5556. maximum.z += maximum.z * bias.x + bias.y;
  5557. }
  5558. return {
  5559. minimum: minimum,
  5560. maximum: maximum
  5561. };
  5562. };
  5563. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5564. if (bias === void 0) { bias = null; }
  5565. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5566. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5567. if (!stride) {
  5568. stride = 3;
  5569. }
  5570. for (var index = start; index < start + count; index++) {
  5571. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5572. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5573. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5574. }
  5575. if (bias) {
  5576. minimum.x -= minimum.x * bias.x + bias.y;
  5577. minimum.y -= minimum.y * bias.x + bias.y;
  5578. minimum.z -= minimum.z * bias.x + bias.y;
  5579. maximum.x += maximum.x * bias.x + bias.y;
  5580. maximum.y += maximum.y * bias.x + bias.y;
  5581. maximum.z += maximum.z * bias.x + bias.y;
  5582. }
  5583. return {
  5584. minimum: minimum,
  5585. maximum: maximum
  5586. };
  5587. };
  5588. Tools.Vector2ArrayFeeder = function (array) {
  5589. return function (index) {
  5590. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5591. var length = isFloatArray ? array.length / 2 : array.length;
  5592. if (index >= length) {
  5593. return null;
  5594. }
  5595. if (isFloatArray) {
  5596. var fa = array;
  5597. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5598. }
  5599. var a = array;
  5600. return a[index];
  5601. };
  5602. };
  5603. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5604. if (bias === void 0) { bias = null; }
  5605. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5606. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5607. var i = 0;
  5608. var cur = feeder(i++);
  5609. while (cur) {
  5610. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5611. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5612. cur = feeder(i++);
  5613. }
  5614. if (bias) {
  5615. minimum.x -= minimum.x * bias.x + bias.y;
  5616. minimum.y -= minimum.y * bias.x + bias.y;
  5617. maximum.x += maximum.x * bias.x + bias.y;
  5618. maximum.y += maximum.y * bias.x + bias.y;
  5619. }
  5620. return {
  5621. minimum: minimum,
  5622. maximum: maximum
  5623. };
  5624. };
  5625. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5626. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5627. return undefined;
  5628. return Array.isArray(obj) ? obj : [obj];
  5629. };
  5630. // Misc.
  5631. Tools.GetPointerPrefix = function () {
  5632. var eventPrefix = "pointer";
  5633. // Check if pointer events are supported
  5634. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5635. eventPrefix = "mouse";
  5636. }
  5637. return eventPrefix;
  5638. };
  5639. /**
  5640. * @param func - the function to be called
  5641. * @param requester - the object that will request the next frame. Falls back to window.
  5642. */
  5643. Tools.QueueNewFrame = function (func, requester) {
  5644. if (requester === void 0) { requester = window; }
  5645. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5646. /*if(requester.isPresenting) {
  5647. return;
  5648. } else*/ if (requester.requestAnimationFrame)
  5649. requester.requestAnimationFrame(func);
  5650. else if (requester.msRequestAnimationFrame)
  5651. requester.msRequestAnimationFrame(func);
  5652. else if (requester.webkitRequestAnimationFrame)
  5653. requester.webkitRequestAnimationFrame(func);
  5654. else if (requester.mozRequestAnimationFrame)
  5655. requester.mozRequestAnimationFrame(func);
  5656. else if (requester.oRequestAnimationFrame)
  5657. requester.oRequestAnimationFrame(func);
  5658. else {
  5659. window.setTimeout(func, 16);
  5660. }
  5661. };
  5662. Tools.RequestFullscreen = function (element) {
  5663. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5664. if (!requestFunction)
  5665. return;
  5666. requestFunction.call(element);
  5667. };
  5668. Tools.ExitFullscreen = function () {
  5669. if (document.exitFullscreen) {
  5670. document.exitFullscreen();
  5671. }
  5672. else if (document.mozCancelFullScreen) {
  5673. document.mozCancelFullScreen();
  5674. }
  5675. else if (document.webkitCancelFullScreen) {
  5676. document.webkitCancelFullScreen();
  5677. }
  5678. else if (document.msCancelFullScreen) {
  5679. document.msCancelFullScreen();
  5680. }
  5681. };
  5682. Tools.SetCorsBehavior = function (url, img) {
  5683. if (Tools.CorsBehavior) {
  5684. switch (typeof (Tools.CorsBehavior)) {
  5685. case "function":
  5686. var result = Tools.CorsBehavior(url);
  5687. if (result) {
  5688. img.crossOrigin = result;
  5689. }
  5690. break;
  5691. case "string":
  5692. default:
  5693. img.crossOrigin = Tools.CorsBehavior;
  5694. break;
  5695. }
  5696. }
  5697. };
  5698. // External files
  5699. Tools.CleanUrl = function (url) {
  5700. url = url.replace(/#/mg, "%23");
  5701. return url;
  5702. };
  5703. Tools.LoadImage = function (url, onload, onerror, database) {
  5704. if (url instanceof ArrayBuffer) {
  5705. url = Tools.EncodeArrayBufferTobase64(url);
  5706. }
  5707. url = Tools.CleanUrl(url);
  5708. url = Tools.PreprocessUrl(url);
  5709. var img = new Image();
  5710. if (url.substr(0, 5) !== "data:") {
  5711. Tools.SetCorsBehavior(url, img);
  5712. }
  5713. img.onload = function () {
  5714. onload(img);
  5715. };
  5716. img.onerror = function (err) {
  5717. Tools.Error("Error while trying to load image: " + url);
  5718. if (Tools.UseFallbackTexture) {
  5719. img.src = Tools.fallbackTexture;
  5720. onload(img);
  5721. }
  5722. else {
  5723. onerror();
  5724. }
  5725. };
  5726. var noIndexedDB = function () {
  5727. img.src = url;
  5728. };
  5729. var loadFromIndexedDB = function () {
  5730. database.loadImageFromDB(url, img);
  5731. };
  5732. //ANY database to do!
  5733. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5734. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5735. }
  5736. else {
  5737. if (url.indexOf("file:") !== 0) {
  5738. noIndexedDB();
  5739. }
  5740. else {
  5741. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5742. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5743. try {
  5744. var blobURL;
  5745. try {
  5746. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5747. }
  5748. catch (ex) {
  5749. // Chrome doesn't support oneTimeOnly parameter
  5750. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5751. }
  5752. img.src = blobURL;
  5753. }
  5754. catch (e) {
  5755. img.src = null;
  5756. }
  5757. }
  5758. else {
  5759. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5760. img.src = Tools.fallbackTexture;
  5761. }
  5762. }
  5763. }
  5764. return img;
  5765. };
  5766. //ANY
  5767. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5768. url = Tools.CleanUrl(url);
  5769. url = Tools.PreprocessUrl(url);
  5770. var noIndexedDB = function () {
  5771. var request = new XMLHttpRequest();
  5772. var loadUrl = Tools.BaseUrl + url;
  5773. request.open('GET', loadUrl, true);
  5774. if (useArrayBuffer) {
  5775. request.responseType = "arraybuffer";
  5776. }
  5777. request.onprogress = progressCallBack;
  5778. request.onreadystatechange = function () {
  5779. // In case of undefined state in some browsers.
  5780. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5781. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5782. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5783. callback(!useArrayBuffer ? request.responseText : request.response);
  5784. }
  5785. else {
  5786. if (onError) {
  5787. onError(request);
  5788. }
  5789. else {
  5790. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5791. }
  5792. }
  5793. }
  5794. };
  5795. request.send(null);
  5796. };
  5797. var loadFromIndexedDB = function () {
  5798. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5799. };
  5800. if (url.indexOf("file:") !== -1) {
  5801. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5802. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5803. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5804. }
  5805. else {
  5806. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5807. }
  5808. }
  5809. else {
  5810. // Caching all files
  5811. if (database && database.enableSceneOffline) {
  5812. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5813. }
  5814. else {
  5815. noIndexedDB();
  5816. }
  5817. }
  5818. };
  5819. /**
  5820. * Load a script (identified by an url). When the url returns, the
  5821. * content of this file is added into a new script element, attached to the DOM (body element)
  5822. */
  5823. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5824. var head = document.getElementsByTagName('head')[0];
  5825. var script = document.createElement('script');
  5826. script.type = 'text/javascript';
  5827. script.src = scriptUrl;
  5828. var self = this;
  5829. script.onload = function () {
  5830. if (onSuccess) {
  5831. onSuccess();
  5832. }
  5833. };
  5834. script.onerror = function () {
  5835. if (onError) {
  5836. onError();
  5837. }
  5838. };
  5839. head.appendChild(script);
  5840. };
  5841. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5842. var reader = new FileReader();
  5843. reader.onload = function (e) {
  5844. //target doesn't have result from ts 1.3
  5845. callback(e.target['result']);
  5846. };
  5847. reader.onprogress = progressCallback;
  5848. reader.readAsDataURL(fileToLoad);
  5849. };
  5850. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5851. var reader = new FileReader();
  5852. reader.onerror = function (e) {
  5853. Tools.Log("Error while reading file: " + fileToLoad.name);
  5854. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5855. };
  5856. reader.onload = function (e) {
  5857. //target doesn't have result from ts 1.3
  5858. callback(e.target['result']);
  5859. };
  5860. reader.onprogress = progressCallBack;
  5861. if (!useArrayBuffer) {
  5862. // Asynchronous read
  5863. reader.readAsText(fileToLoad);
  5864. }
  5865. else {
  5866. reader.readAsArrayBuffer(fileToLoad);
  5867. }
  5868. };
  5869. //returns a downloadable url to a file content.
  5870. Tools.FileAsURL = function (content) {
  5871. var fileBlob = new Blob([content]);
  5872. var url = window.URL || window.webkitURL;
  5873. var link = url.createObjectURL(fileBlob);
  5874. return link;
  5875. };
  5876. // Misc.
  5877. Tools.Format = function (value, decimals) {
  5878. if (decimals === void 0) { decimals = 2; }
  5879. return value.toFixed(decimals);
  5880. };
  5881. Tools.CheckExtends = function (v, min, max) {
  5882. if (v.x < min.x)
  5883. min.x = v.x;
  5884. if (v.y < min.y)
  5885. min.y = v.y;
  5886. if (v.z < min.z)
  5887. min.z = v.z;
  5888. if (v.x > max.x)
  5889. max.x = v.x;
  5890. if (v.y > max.y)
  5891. max.y = v.y;
  5892. if (v.z > max.z)
  5893. max.z = v.z;
  5894. };
  5895. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5896. for (var prop in source) {
  5897. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5898. continue;
  5899. }
  5900. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5901. continue;
  5902. }
  5903. var sourceValue = source[prop];
  5904. var typeOfSourceValue = typeof sourceValue;
  5905. if (typeOfSourceValue === "function") {
  5906. continue;
  5907. }
  5908. if (typeOfSourceValue === "object") {
  5909. if (sourceValue instanceof Array) {
  5910. destination[prop] = [];
  5911. if (sourceValue.length > 0) {
  5912. if (typeof sourceValue[0] == "object") {
  5913. for (var index = 0; index < sourceValue.length; index++) {
  5914. var clonedValue = cloneValue(sourceValue[index], destination);
  5915. if (destination[prop].indexOf(clonedValue) === -1) {
  5916. destination[prop].push(clonedValue);
  5917. }
  5918. }
  5919. }
  5920. else {
  5921. destination[prop] = sourceValue.slice(0);
  5922. }
  5923. }
  5924. }
  5925. else {
  5926. destination[prop] = cloneValue(sourceValue, destination);
  5927. }
  5928. }
  5929. else {
  5930. destination[prop] = sourceValue;
  5931. }
  5932. }
  5933. };
  5934. Tools.IsEmpty = function (obj) {
  5935. for (var i in obj) {
  5936. return false;
  5937. }
  5938. return true;
  5939. };
  5940. Tools.RegisterTopRootEvents = function (events) {
  5941. for (var index = 0; index < events.length; index++) {
  5942. var event = events[index];
  5943. window.addEventListener(event.name, event.handler, false);
  5944. try {
  5945. if (window.parent) {
  5946. window.parent.addEventListener(event.name, event.handler, false);
  5947. }
  5948. }
  5949. catch (e) {
  5950. // Silently fails...
  5951. }
  5952. }
  5953. };
  5954. Tools.UnregisterTopRootEvents = function (events) {
  5955. for (var index = 0; index < events.length; index++) {
  5956. var event = events[index];
  5957. window.removeEventListener(event.name, event.handler);
  5958. try {
  5959. if (window.parent) {
  5960. window.parent.removeEventListener(event.name, event.handler);
  5961. }
  5962. }
  5963. catch (e) {
  5964. // Silently fails...
  5965. }
  5966. }
  5967. };
  5968. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5969. if (mimeType === void 0) { mimeType = "image/png"; }
  5970. // Read the contents of the framebuffer
  5971. var numberOfChannelsByLine = width * 4;
  5972. var halfHeight = height / 2;
  5973. //Reading datas from WebGL
  5974. var data = engine.readPixels(0, 0, width, height);
  5975. //To flip image on Y axis.
  5976. for (var i = 0; i < halfHeight; i++) {
  5977. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5978. var currentCell = j + i * numberOfChannelsByLine;
  5979. var targetLine = height - i - 1;
  5980. var targetCell = j + targetLine * numberOfChannelsByLine;
  5981. var temp = data[currentCell];
  5982. data[currentCell] = data[targetCell];
  5983. data[targetCell] = temp;
  5984. }
  5985. }
  5986. // Create a 2D canvas to store the result
  5987. if (!screenshotCanvas) {
  5988. screenshotCanvas = document.createElement('canvas');
  5989. }
  5990. screenshotCanvas.width = width;
  5991. screenshotCanvas.height = height;
  5992. var context = screenshotCanvas.getContext('2d');
  5993. // Copy the pixels to a 2D canvas
  5994. var imageData = context.createImageData(width, height);
  5995. var castData = (imageData.data);
  5996. castData.set(data);
  5997. context.putImageData(imageData, 0, 0);
  5998. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5999. };
  6000. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6001. if (mimeType === void 0) { mimeType = "image/png"; }
  6002. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6003. if (successCallback) {
  6004. successCallback(base64Image);
  6005. }
  6006. else {
  6007. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6008. if (("download" in document.createElement("a"))) {
  6009. var a = window.document.createElement("a");
  6010. a.href = base64Image;
  6011. var date = new Date();
  6012. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6013. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6014. window.document.body.appendChild(a);
  6015. a.addEventListener("click", function () {
  6016. a.parentElement.removeChild(a);
  6017. });
  6018. a.click();
  6019. //Or opening a new tab with the image if it is not possible to automatically start download.
  6020. }
  6021. else {
  6022. var newWindow = window.open("");
  6023. var img = newWindow.document.createElement("img");
  6024. img.src = base64Image;
  6025. newWindow.document.body.appendChild(img);
  6026. }
  6027. }
  6028. };
  6029. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6030. if (mimeType === void 0) { mimeType = "image/png"; }
  6031. var width;
  6032. var height;
  6033. // If a precision value is specified
  6034. if (size.precision) {
  6035. width = Math.round(engine.getRenderWidth() * size.precision);
  6036. height = Math.round(width / engine.getAspectRatio(camera));
  6037. }
  6038. else if (size.width && size.height) {
  6039. width = size.width;
  6040. height = size.height;
  6041. }
  6042. else if (size.width && !size.height) {
  6043. width = size.width;
  6044. height = Math.round(width / engine.getAspectRatio(camera));
  6045. }
  6046. else if (size.height && !size.width) {
  6047. height = size.height;
  6048. width = Math.round(height * engine.getAspectRatio(camera));
  6049. }
  6050. else if (!isNaN(size)) {
  6051. height = size;
  6052. width = size;
  6053. }
  6054. else {
  6055. Tools.Error("Invalid 'size' parameter !");
  6056. return;
  6057. }
  6058. if (!screenshotCanvas) {
  6059. screenshotCanvas = document.createElement('canvas');
  6060. }
  6061. screenshotCanvas.width = width;
  6062. screenshotCanvas.height = height;
  6063. var renderContext = screenshotCanvas.getContext("2d");
  6064. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6065. var newWidth = width;
  6066. var newHeight = newWidth / ratio;
  6067. if (newHeight > height) {
  6068. newHeight = height;
  6069. newWidth = newHeight * ratio;
  6070. }
  6071. var offsetX = Math.max(0, width - newWidth) / 2;
  6072. var offsetY = Math.max(0, height - newHeight) / 2;
  6073. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6074. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6075. };
  6076. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6077. if (mimeType === void 0) { mimeType = "image/png"; }
  6078. if (samples === void 0) { samples = 1; }
  6079. var width;
  6080. var height;
  6081. //If a precision value is specified
  6082. if (size.precision) {
  6083. width = Math.round(engine.getRenderWidth() * size.precision);
  6084. height = Math.round(width / engine.getAspectRatio(camera));
  6085. size = { width: width, height: height };
  6086. }
  6087. else if (size.width && size.height) {
  6088. width = size.width;
  6089. height = size.height;
  6090. }
  6091. else if (size.width && !size.height) {
  6092. width = size.width;
  6093. height = Math.round(width / engine.getAspectRatio(camera));
  6094. size = { width: width, height: height };
  6095. }
  6096. else if (size.height && !size.width) {
  6097. height = size.height;
  6098. width = Math.round(height * engine.getAspectRatio(camera));
  6099. size = { width: width, height: height };
  6100. }
  6101. else if (!isNaN(size)) {
  6102. height = size;
  6103. width = size;
  6104. }
  6105. else {
  6106. Tools.Error("Invalid 'size' parameter !");
  6107. return;
  6108. }
  6109. var scene = camera.getScene();
  6110. var previousCamera = null;
  6111. if (scene.activeCamera !== camera) {
  6112. previousCamera = scene.activeCamera;
  6113. scene.activeCamera = camera;
  6114. }
  6115. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6116. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6117. texture.renderList = null;
  6118. texture.samples = samples;
  6119. texture.onAfterRenderObservable.add(function () {
  6120. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6121. });
  6122. scene.incrementRenderId();
  6123. scene.resetCachedMaterial();
  6124. texture.render(true);
  6125. texture.dispose();
  6126. if (previousCamera) {
  6127. scene.activeCamera = previousCamera;
  6128. }
  6129. camera.getProjectionMatrix(true); // Force cache refresh;
  6130. };
  6131. // XHR response validator for local file scenario
  6132. Tools.ValidateXHRData = function (xhr, dataType) {
  6133. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6134. if (dataType === void 0) { dataType = 7; }
  6135. try {
  6136. if (dataType & 1) {
  6137. if (xhr.responseText && xhr.responseText.length > 0) {
  6138. return true;
  6139. }
  6140. else if (dataType === 1) {
  6141. return false;
  6142. }
  6143. }
  6144. if (dataType & 2) {
  6145. // Check header width and height since there is no "TGA" magic number
  6146. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6147. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6148. return true;
  6149. }
  6150. else if (dataType === 2) {
  6151. return false;
  6152. }
  6153. }
  6154. if (dataType & 4) {
  6155. // Check for the "DDS" magic number
  6156. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6157. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6158. return true;
  6159. }
  6160. else {
  6161. return false;
  6162. }
  6163. }
  6164. }
  6165. catch (e) {
  6166. // Global protection
  6167. }
  6168. return false;
  6169. };
  6170. /**
  6171. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6172. * Be aware Math.random() could cause collisions, but:
  6173. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6174. */
  6175. Tools.RandomId = function () {
  6176. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6177. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6178. return v.toString(16);
  6179. });
  6180. };
  6181. Object.defineProperty(Tools, "NoneLogLevel", {
  6182. get: function () {
  6183. return Tools._NoneLogLevel;
  6184. },
  6185. enumerable: true,
  6186. configurable: true
  6187. });
  6188. Object.defineProperty(Tools, "MessageLogLevel", {
  6189. get: function () {
  6190. return Tools._MessageLogLevel;
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. Object.defineProperty(Tools, "WarningLogLevel", {
  6196. get: function () {
  6197. return Tools._WarningLogLevel;
  6198. },
  6199. enumerable: true,
  6200. configurable: true
  6201. });
  6202. Object.defineProperty(Tools, "ErrorLogLevel", {
  6203. get: function () {
  6204. return Tools._ErrorLogLevel;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(Tools, "AllLogLevel", {
  6210. get: function () {
  6211. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Tools._AddLogEntry = function (entry) {
  6217. Tools._LogCache = entry + Tools._LogCache;
  6218. if (Tools.OnNewCacheEntry) {
  6219. Tools.OnNewCacheEntry(entry);
  6220. }
  6221. };
  6222. Tools._FormatMessage = function (message) {
  6223. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6224. var date = new Date();
  6225. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6226. };
  6227. Tools._LogDisabled = function (message) {
  6228. // nothing to do
  6229. };
  6230. Tools._LogEnabled = function (message) {
  6231. var formattedMessage = Tools._FormatMessage(message);
  6232. console.log("BJS - " + formattedMessage);
  6233. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6234. Tools._AddLogEntry(entry);
  6235. };
  6236. Tools._WarnDisabled = function (message) {
  6237. // nothing to do
  6238. };
  6239. Tools._WarnEnabled = function (message) {
  6240. var formattedMessage = Tools._FormatMessage(message);
  6241. console.warn("BJS - " + formattedMessage);
  6242. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6243. Tools._AddLogEntry(entry);
  6244. };
  6245. Tools._ErrorDisabled = function (message) {
  6246. // nothing to do
  6247. };
  6248. Tools._ErrorEnabled = function (message) {
  6249. Tools.errorsCount++;
  6250. var formattedMessage = Tools._FormatMessage(message);
  6251. console.error("BJS - " + formattedMessage);
  6252. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6253. Tools._AddLogEntry(entry);
  6254. };
  6255. Object.defineProperty(Tools, "LogCache", {
  6256. get: function () {
  6257. return Tools._LogCache;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Tools.ClearLogCache = function () {
  6263. Tools._LogCache = "";
  6264. Tools.errorsCount = 0;
  6265. };
  6266. Object.defineProperty(Tools, "LogLevels", {
  6267. set: function (level) {
  6268. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6269. Tools.Log = Tools._LogEnabled;
  6270. }
  6271. else {
  6272. Tools.Log = Tools._LogDisabled;
  6273. }
  6274. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6275. Tools.Warn = Tools._WarnEnabled;
  6276. }
  6277. else {
  6278. Tools.Warn = Tools._WarnDisabled;
  6279. }
  6280. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6281. Tools.Error = Tools._ErrorEnabled;
  6282. }
  6283. else {
  6284. Tools.Error = Tools._ErrorDisabled;
  6285. }
  6286. },
  6287. enumerable: true,
  6288. configurable: true
  6289. });
  6290. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6291. get: function () {
  6292. return Tools._PerformanceNoneLogLevel;
  6293. },
  6294. enumerable: true,
  6295. configurable: true
  6296. });
  6297. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6298. get: function () {
  6299. return Tools._PerformanceUserMarkLogLevel;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6305. get: function () {
  6306. return Tools._PerformanceConsoleLogLevel;
  6307. },
  6308. enumerable: true,
  6309. configurable: true
  6310. });
  6311. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6312. set: function (level) {
  6313. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6314. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6315. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6316. return;
  6317. }
  6318. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6319. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6320. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6321. return;
  6322. }
  6323. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6324. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6325. },
  6326. enumerable: true,
  6327. configurable: true
  6328. });
  6329. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6332. };
  6333. Tools._StartUserMark = function (counterName, condition) {
  6334. if (condition === void 0) { condition = true; }
  6335. if (!condition || !Tools._performance.mark) {
  6336. return;
  6337. }
  6338. Tools._performance.mark(counterName + "-Begin");
  6339. };
  6340. Tools._EndUserMark = function (counterName, condition) {
  6341. if (condition === void 0) { condition = true; }
  6342. if (!condition || !Tools._performance.mark) {
  6343. return;
  6344. }
  6345. Tools._performance.mark(counterName + "-End");
  6346. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6347. };
  6348. Tools._StartPerformanceConsole = function (counterName, condition) {
  6349. if (condition === void 0) { condition = true; }
  6350. if (!condition) {
  6351. return;
  6352. }
  6353. Tools._StartUserMark(counterName, condition);
  6354. if (console.time) {
  6355. console.time(counterName);
  6356. }
  6357. };
  6358. Tools._EndPerformanceConsole = function (counterName, condition) {
  6359. if (condition === void 0) { condition = true; }
  6360. if (!condition) {
  6361. return;
  6362. }
  6363. Tools._EndUserMark(counterName, condition);
  6364. if (console.time) {
  6365. console.timeEnd(counterName);
  6366. }
  6367. };
  6368. Object.defineProperty(Tools, "Now", {
  6369. get: function () {
  6370. if (window.performance && window.performance.now) {
  6371. return window.performance.now();
  6372. }
  6373. return new Date().getTime();
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. /**
  6379. * This method will return the name of the class used to create the instance of the given object.
  6380. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6381. * @param object the object to get the class name from
  6382. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6383. */
  6384. Tools.GetClassName = function (object, isType) {
  6385. if (isType === void 0) { isType = false; }
  6386. var name = null;
  6387. if (!isType && object.getClassName) {
  6388. name = object.getClassName();
  6389. }
  6390. else {
  6391. if (object instanceof Object) {
  6392. var classObj = isType ? object : Object.getPrototypeOf(object);
  6393. name = classObj.constructor["__bjsclassName__"];
  6394. }
  6395. if (!name) {
  6396. name = typeof object;
  6397. }
  6398. }
  6399. return name;
  6400. };
  6401. Tools.first = function (array, predicate) {
  6402. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6403. var el = array_1[_i];
  6404. if (predicate(el)) {
  6405. return el;
  6406. }
  6407. }
  6408. };
  6409. /**
  6410. * This method will return the name of the full name of the class, including its owning module (if any).
  6411. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6412. * @param object the object to get the class name from
  6413. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6414. */
  6415. Tools.getFullClassName = function (object, isType) {
  6416. if (isType === void 0) { isType = false; }
  6417. var className = null;
  6418. var moduleName = null;
  6419. if (!isType && object.getClassName) {
  6420. className = object.getClassName();
  6421. }
  6422. else {
  6423. if (object instanceof Object) {
  6424. var classObj = isType ? object : Object.getPrototypeOf(object);
  6425. className = classObj.constructor["__bjsclassName__"];
  6426. moduleName = classObj.constructor["__bjsmoduleName__"];
  6427. }
  6428. if (!className) {
  6429. className = typeof object;
  6430. }
  6431. }
  6432. if (!className) {
  6433. return null;
  6434. }
  6435. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6436. };
  6437. /**
  6438. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6439. * @param array
  6440. */
  6441. Tools.arrayOrStringFeeder = function (array) {
  6442. return function (index) {
  6443. if (index >= array.length) {
  6444. return null;
  6445. }
  6446. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6447. if (val && val.getHashCode) {
  6448. val = val.getHashCode();
  6449. }
  6450. if (typeof val === "string") {
  6451. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6452. }
  6453. return val;
  6454. };
  6455. };
  6456. /**
  6457. * Compute the hashCode of a stream of number
  6458. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6459. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6460. * @return the hash code computed
  6461. */
  6462. Tools.hashCodeFromStream = function (feeder) {
  6463. // Based from here: http://stackoverflow.com/a/7616484/802124
  6464. var hash = 0;
  6465. var index = 0;
  6466. var chr = feeder(index++);
  6467. while (chr != null) {
  6468. hash = ((hash << 5) - hash) + chr;
  6469. hash |= 0; // Convert to 32bit integer
  6470. chr = feeder(index++);
  6471. }
  6472. return hash;
  6473. };
  6474. Tools.BaseUrl = "";
  6475. Tools.CorsBehavior = "anonymous";
  6476. Tools.UseFallbackTexture = true;
  6477. // Used in case of a texture loading problem
  6478. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6479. Tools.PreprocessUrl = function (url) {
  6480. return url;
  6481. };
  6482. // Logs
  6483. Tools._NoneLogLevel = 0;
  6484. Tools._MessageLogLevel = 1;
  6485. Tools._WarningLogLevel = 2;
  6486. Tools._ErrorLogLevel = 4;
  6487. Tools._LogCache = "";
  6488. Tools.errorsCount = 0;
  6489. Tools.Log = Tools._LogEnabled;
  6490. Tools.Warn = Tools._WarnEnabled;
  6491. Tools.Error = Tools._ErrorEnabled;
  6492. // Performances
  6493. Tools._PerformanceNoneLogLevel = 0;
  6494. Tools._PerformanceUserMarkLogLevel = 1;
  6495. Tools._PerformanceConsoleLogLevel = 2;
  6496. Tools._performance = window.performance;
  6497. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6498. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6499. return Tools;
  6500. }());
  6501. BABYLON.Tools = Tools;
  6502. /**
  6503. * This class is used to track a performance counter which is number based.
  6504. * The user has access to many properties which give statistics of different nature
  6505. *
  6506. * The implementer can track two kinds of Performance Counter: time and count
  6507. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6508. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6509. */
  6510. var PerfCounter = (function () {
  6511. function PerfCounter() {
  6512. this._startMonitoringTime = 0;
  6513. this._min = 0;
  6514. this._max = 0;
  6515. this._average = 0;
  6516. this._lastSecAverage = 0;
  6517. this._current = 0;
  6518. this._totalValueCount = 0;
  6519. this._totalAccumulated = 0;
  6520. this._lastSecAccumulated = 0;
  6521. this._lastSecTime = 0;
  6522. this._lastSecValueCount = 0;
  6523. }
  6524. Object.defineProperty(PerfCounter.prototype, "min", {
  6525. /**
  6526. * Returns the smallest value ever
  6527. */
  6528. get: function () {
  6529. return this._min;
  6530. },
  6531. enumerable: true,
  6532. configurable: true
  6533. });
  6534. Object.defineProperty(PerfCounter.prototype, "max", {
  6535. /**
  6536. * Returns the biggest value ever
  6537. */
  6538. get: function () {
  6539. return this._max;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(PerfCounter.prototype, "average", {
  6545. /**
  6546. * Returns the average value since the performance counter is running
  6547. */
  6548. get: function () {
  6549. return this._average;
  6550. },
  6551. enumerable: true,
  6552. configurable: true
  6553. });
  6554. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6555. /**
  6556. * Returns the average value of the last second the counter was monitored
  6557. */
  6558. get: function () {
  6559. return this._lastSecAverage;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. Object.defineProperty(PerfCounter.prototype, "current", {
  6565. /**
  6566. * Returns the current value
  6567. */
  6568. get: function () {
  6569. return this._current;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Object.defineProperty(PerfCounter.prototype, "total", {
  6575. get: function () {
  6576. return this._totalAccumulated;
  6577. },
  6578. enumerable: true,
  6579. configurable: true
  6580. });
  6581. /**
  6582. * Call this method to start monitoring a new frame.
  6583. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6584. */
  6585. PerfCounter.prototype.fetchNewFrame = function () {
  6586. this._totalValueCount++;
  6587. this._current = 0;
  6588. this._lastSecValueCount++;
  6589. };
  6590. /**
  6591. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6592. * @param newCount the count value to add to the monitored count
  6593. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6594. */
  6595. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6596. if (!PerfCounter.Enabled) {
  6597. return;
  6598. }
  6599. this._current += newCount;
  6600. if (fetchResult) {
  6601. this._fetchResult();
  6602. }
  6603. };
  6604. /**
  6605. * Start monitoring this performance counter
  6606. */
  6607. PerfCounter.prototype.beginMonitoring = function () {
  6608. if (!PerfCounter.Enabled) {
  6609. return;
  6610. }
  6611. this._startMonitoringTime = Tools.Now;
  6612. };
  6613. /**
  6614. * Compute the time lapsed since the previous beginMonitoring() call.
  6615. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6616. */
  6617. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6618. if (newFrame === void 0) { newFrame = true; }
  6619. if (!PerfCounter.Enabled) {
  6620. return;
  6621. }
  6622. if (newFrame) {
  6623. this.fetchNewFrame();
  6624. }
  6625. var currentTime = Tools.Now;
  6626. this._current = currentTime - this._startMonitoringTime;
  6627. if (newFrame) {
  6628. this._fetchResult();
  6629. }
  6630. };
  6631. PerfCounter.prototype._fetchResult = function () {
  6632. this._totalAccumulated += this._current;
  6633. this._lastSecAccumulated += this._current;
  6634. // Min/Max update
  6635. this._min = Math.min(this._min, this._current);
  6636. this._max = Math.max(this._max, this._current);
  6637. this._average = this._totalAccumulated / this._totalValueCount;
  6638. // Reset last sec?
  6639. var now = Tools.Now;
  6640. if ((now - this._lastSecTime) > 1000) {
  6641. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6642. this._lastSecTime = now;
  6643. this._lastSecAccumulated = 0;
  6644. this._lastSecValueCount = 0;
  6645. }
  6646. };
  6647. PerfCounter.Enabled = true;
  6648. return PerfCounter;
  6649. }());
  6650. BABYLON.PerfCounter = PerfCounter;
  6651. /**
  6652. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6653. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6654. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6655. * @param name The name of the class, case should be preserved
  6656. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6657. */
  6658. function className(name, module) {
  6659. return function (target) {
  6660. target["__bjsclassName__"] = name;
  6661. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6662. };
  6663. }
  6664. BABYLON.className = className;
  6665. /**
  6666. * An implementation of a loop for asynchronous functions.
  6667. */
  6668. var AsyncLoop = (function () {
  6669. /**
  6670. * Constroctor.
  6671. * @param iterations the number of iterations.
  6672. * @param _fn the function to run each iteration
  6673. * @param _successCallback the callback that will be called upon succesful execution
  6674. * @param offset starting offset.
  6675. */
  6676. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6677. if (offset === void 0) { offset = 0; }
  6678. this.iterations = iterations;
  6679. this._fn = _fn;
  6680. this._successCallback = _successCallback;
  6681. this.index = offset - 1;
  6682. this._done = false;
  6683. }
  6684. /**
  6685. * Execute the next iteration. Must be called after the last iteration was finished.
  6686. */
  6687. AsyncLoop.prototype.executeNext = function () {
  6688. if (!this._done) {
  6689. if (this.index + 1 < this.iterations) {
  6690. ++this.index;
  6691. this._fn(this);
  6692. }
  6693. else {
  6694. this.breakLoop();
  6695. }
  6696. }
  6697. };
  6698. /**
  6699. * Break the loop and run the success callback.
  6700. */
  6701. AsyncLoop.prototype.breakLoop = function () {
  6702. this._done = true;
  6703. this._successCallback();
  6704. };
  6705. /**
  6706. * Helper function
  6707. */
  6708. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6709. if (offset === void 0) { offset = 0; }
  6710. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6711. loop.executeNext();
  6712. return loop;
  6713. };
  6714. /**
  6715. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6716. * @param iterations total number of iterations
  6717. * @param syncedIterations number of synchronous iterations in each async iteration.
  6718. * @param fn the function to call each iteration.
  6719. * @param callback a success call back that will be called when iterating stops.
  6720. * @param breakFunction a break condition (optional)
  6721. * @param timeout timeout settings for the setTimeout function. default - 0.
  6722. * @constructor
  6723. */
  6724. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6725. if (timeout === void 0) { timeout = 0; }
  6726. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6727. if (breakFunction && breakFunction())
  6728. loop.breakLoop();
  6729. else {
  6730. setTimeout(function () {
  6731. for (var i = 0; i < syncedIterations; ++i) {
  6732. var iteration = (loop.index * syncedIterations) + i;
  6733. if (iteration >= iterations)
  6734. break;
  6735. fn(iteration);
  6736. if (breakFunction && breakFunction()) {
  6737. loop.breakLoop();
  6738. break;
  6739. }
  6740. }
  6741. loop.executeNext();
  6742. }, timeout);
  6743. }
  6744. }, callback);
  6745. };
  6746. return AsyncLoop;
  6747. }());
  6748. BABYLON.AsyncLoop = AsyncLoop;
  6749. })(BABYLON || (BABYLON = {}));
  6750. //# sourceMappingURL=babylon.tools.js.map
  6751. var BABYLON;
  6752. (function (BABYLON) {
  6753. var Internals;
  6754. (function (Internals) {
  6755. var _AlphaState = (function () {
  6756. /**
  6757. * Initializes the state.
  6758. */
  6759. function _AlphaState() {
  6760. this._isAlphaBlendDirty = false;
  6761. this._isBlendFunctionParametersDirty = false;
  6762. this._isBlendEquationParametersDirty = false;
  6763. this._isBlendConstantsDirty = false;
  6764. this._alphaBlend = false;
  6765. this._blendFunctionParameters = new Array(4);
  6766. this._blendEquationParameters = new Array(2);
  6767. this._blendConstants = new Array(4);
  6768. this.reset();
  6769. }
  6770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6771. get: function () {
  6772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6773. },
  6774. enumerable: true,
  6775. configurable: true
  6776. });
  6777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6778. get: function () {
  6779. return this._alphaBlend;
  6780. },
  6781. set: function (value) {
  6782. if (this._alphaBlend === value) {
  6783. return;
  6784. }
  6785. this._alphaBlend = value;
  6786. this._isAlphaBlendDirty = true;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6792. if (this._blendConstants[0] === r &&
  6793. this._blendConstants[1] === g &&
  6794. this._blendConstants[2] === b &&
  6795. this._blendConstants[3] === a) {
  6796. return;
  6797. }
  6798. this._blendConstants[0] = r;
  6799. this._blendConstants[1] = g;
  6800. this._blendConstants[2] = b;
  6801. this._blendConstants[3] = a;
  6802. this._isBlendConstantsDirty = true;
  6803. };
  6804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6805. if (this._blendFunctionParameters[0] === value0 &&
  6806. this._blendFunctionParameters[1] === value1 &&
  6807. this._blendFunctionParameters[2] === value2 &&
  6808. this._blendFunctionParameters[3] === value3) {
  6809. return;
  6810. }
  6811. this._blendFunctionParameters[0] = value0;
  6812. this._blendFunctionParameters[1] = value1;
  6813. this._blendFunctionParameters[2] = value2;
  6814. this._blendFunctionParameters[3] = value3;
  6815. this._isBlendFunctionParametersDirty = true;
  6816. };
  6817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6818. if (this._blendEquationParameters[0] === rgb &&
  6819. this._blendEquationParameters[1] === alpha) {
  6820. return;
  6821. }
  6822. this._blendEquationParameters[0] = rgb;
  6823. this._blendEquationParameters[1] = alpha;
  6824. this._isBlendEquationParametersDirty = true;
  6825. };
  6826. _AlphaState.prototype.reset = function () {
  6827. this._alphaBlend = false;
  6828. this._blendFunctionParameters[0] = null;
  6829. this._blendFunctionParameters[1] = null;
  6830. this._blendFunctionParameters[2] = null;
  6831. this._blendFunctionParameters[3] = null;
  6832. this._blendEquationParameters[0] = null;
  6833. this._blendEquationParameters[1] = null;
  6834. this._blendConstants[0] = null;
  6835. this._blendConstants[1] = null;
  6836. this._blendConstants[2] = null;
  6837. this._blendConstants[3] = null;
  6838. this._isAlphaBlendDirty = true;
  6839. this._isBlendFunctionParametersDirty = false;
  6840. this._isBlendEquationParametersDirty = false;
  6841. this._isBlendConstantsDirty = false;
  6842. };
  6843. _AlphaState.prototype.apply = function (gl) {
  6844. if (!this.isDirty) {
  6845. return;
  6846. }
  6847. // Alpha blend
  6848. if (this._isAlphaBlendDirty) {
  6849. if (this._alphaBlend) {
  6850. gl.enable(gl.BLEND);
  6851. }
  6852. else {
  6853. gl.disable(gl.BLEND);
  6854. }
  6855. this._isAlphaBlendDirty = false;
  6856. }
  6857. // Alpha function
  6858. if (this._isBlendFunctionParametersDirty) {
  6859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6860. this._isBlendFunctionParametersDirty = false;
  6861. }
  6862. // Alpha equation
  6863. if (this._isBlendEquationParametersDirty) {
  6864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6865. this._isBlendEquationParametersDirty = false;
  6866. }
  6867. // Constants
  6868. if (this._isBlendConstantsDirty) {
  6869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6870. this._isBlendConstantsDirty = false;
  6871. }
  6872. };
  6873. return _AlphaState;
  6874. }());
  6875. Internals._AlphaState = _AlphaState;
  6876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. var Internals;
  6882. (function (Internals) {
  6883. var _DepthCullingState = (function () {
  6884. /**
  6885. * Initializes the state.
  6886. */
  6887. function _DepthCullingState() {
  6888. this._isDepthTestDirty = false;
  6889. this._isDepthMaskDirty = false;
  6890. this._isDepthFuncDirty = false;
  6891. this._isCullFaceDirty = false;
  6892. this._isCullDirty = false;
  6893. this._isZOffsetDirty = false;
  6894. this.reset();
  6895. }
  6896. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6897. get: function () {
  6898. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6899. },
  6900. enumerable: true,
  6901. configurable: true
  6902. });
  6903. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6904. get: function () {
  6905. return this._zOffset;
  6906. },
  6907. set: function (value) {
  6908. if (this._zOffset === value) {
  6909. return;
  6910. }
  6911. this._zOffset = value;
  6912. this._isZOffsetDirty = true;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6918. get: function () {
  6919. return this._cullFace;
  6920. },
  6921. set: function (value) {
  6922. if (this._cullFace === value) {
  6923. return;
  6924. }
  6925. this._cullFace = value;
  6926. this._isCullFaceDirty = true;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6932. get: function () {
  6933. return this._cull;
  6934. },
  6935. set: function (value) {
  6936. if (this._cull === value) {
  6937. return;
  6938. }
  6939. this._cull = value;
  6940. this._isCullDirty = true;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6946. get: function () {
  6947. return this._depthFunc;
  6948. },
  6949. set: function (value) {
  6950. if (this._depthFunc === value) {
  6951. return;
  6952. }
  6953. this._depthFunc = value;
  6954. this._isDepthFuncDirty = true;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6960. get: function () {
  6961. return this._depthMask;
  6962. },
  6963. set: function (value) {
  6964. if (this._depthMask === value) {
  6965. return;
  6966. }
  6967. this._depthMask = value;
  6968. this._isDepthMaskDirty = true;
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6974. get: function () {
  6975. return this._depthTest;
  6976. },
  6977. set: function (value) {
  6978. if (this._depthTest === value) {
  6979. return;
  6980. }
  6981. this._depthTest = value;
  6982. this._isDepthTestDirty = true;
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. _DepthCullingState.prototype.reset = function () {
  6988. this._depthMask = true;
  6989. this._depthTest = true;
  6990. this._depthFunc = null;
  6991. this._cullFace = null;
  6992. this._cull = null;
  6993. this._zOffset = 0;
  6994. this._isDepthTestDirty = true;
  6995. this._isDepthMaskDirty = true;
  6996. this._isDepthFuncDirty = false;
  6997. this._isCullFaceDirty = false;
  6998. this._isCullDirty = false;
  6999. this._isZOffsetDirty = false;
  7000. };
  7001. _DepthCullingState.prototype.apply = function (gl) {
  7002. if (!this.isDirty) {
  7003. return;
  7004. }
  7005. // Cull
  7006. if (this._isCullDirty) {
  7007. if (this.cull) {
  7008. gl.enable(gl.CULL_FACE);
  7009. }
  7010. else {
  7011. gl.disable(gl.CULL_FACE);
  7012. }
  7013. this._isCullDirty = false;
  7014. }
  7015. // Cull face
  7016. if (this._isCullFaceDirty) {
  7017. gl.cullFace(this.cullFace);
  7018. this._isCullFaceDirty = false;
  7019. }
  7020. // Depth mask
  7021. if (this._isDepthMaskDirty) {
  7022. gl.depthMask(this.depthMask);
  7023. this._isDepthMaskDirty = false;
  7024. }
  7025. // Depth test
  7026. if (this._isDepthTestDirty) {
  7027. if (this.depthTest) {
  7028. gl.enable(gl.DEPTH_TEST);
  7029. }
  7030. else {
  7031. gl.disable(gl.DEPTH_TEST);
  7032. }
  7033. this._isDepthTestDirty = false;
  7034. }
  7035. // Depth func
  7036. if (this._isDepthFuncDirty) {
  7037. gl.depthFunc(this.depthFunc);
  7038. this._isDepthFuncDirty = false;
  7039. }
  7040. // zOffset
  7041. if (this._isZOffsetDirty) {
  7042. if (this.zOffset) {
  7043. gl.enable(gl.POLYGON_OFFSET_FILL);
  7044. gl.polygonOffset(this.zOffset, 0);
  7045. }
  7046. else {
  7047. gl.disable(gl.POLYGON_OFFSET_FILL);
  7048. }
  7049. this._isZOffsetDirty = false;
  7050. }
  7051. };
  7052. return _DepthCullingState;
  7053. }());
  7054. Internals._DepthCullingState = _DepthCullingState;
  7055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7056. })(BABYLON || (BABYLON = {}));
  7057. //# sourceMappingURL=babylon.depthCullingState.js.map
  7058. var BABYLON;
  7059. (function (BABYLON) {
  7060. var Internals;
  7061. (function (Internals) {
  7062. var _StencilState = (function () {
  7063. function _StencilState() {
  7064. this._isStencilTestDirty = false;
  7065. this._isStencilMaskDirty = false;
  7066. this._isStencilFuncDirty = false;
  7067. this._isStencilOpDirty = false;
  7068. this.reset();
  7069. }
  7070. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7071. get: function () {
  7072. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7078. get: function () {
  7079. return this._stencilFunc;
  7080. },
  7081. set: function (value) {
  7082. if (this._stencilFunc === value) {
  7083. return;
  7084. }
  7085. this._stencilFunc = value;
  7086. this._isStencilFuncDirty = true;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7092. get: function () {
  7093. return this._stencilFuncRef;
  7094. },
  7095. set: function (value) {
  7096. if (this._stencilFuncRef === value) {
  7097. return;
  7098. }
  7099. this._stencilFuncRef = value;
  7100. this._isStencilFuncDirty = true;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7106. get: function () {
  7107. return this._stencilFuncMask;
  7108. },
  7109. set: function (value) {
  7110. if (this._stencilFuncMask === value) {
  7111. return;
  7112. }
  7113. this._stencilFuncMask = value;
  7114. this._isStencilFuncDirty = true;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7120. get: function () {
  7121. return this._stencilOpStencilFail;
  7122. },
  7123. set: function (value) {
  7124. if (this._stencilOpStencilFail === value) {
  7125. return;
  7126. }
  7127. this._stencilOpStencilFail = value;
  7128. this._isStencilOpDirty = true;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7134. get: function () {
  7135. return this._stencilOpDepthFail;
  7136. },
  7137. set: function (value) {
  7138. if (this._stencilOpDepthFail === value) {
  7139. return;
  7140. }
  7141. this._stencilOpDepthFail = value;
  7142. this._isStencilOpDirty = true;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7148. get: function () {
  7149. return this._stencilOpStencilDepthPass;
  7150. },
  7151. set: function (value) {
  7152. if (this._stencilOpStencilDepthPass === value) {
  7153. return;
  7154. }
  7155. this._stencilOpStencilDepthPass = value;
  7156. this._isStencilOpDirty = true;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7162. get: function () {
  7163. return this._stencilMask;
  7164. },
  7165. set: function (value) {
  7166. if (this._stencilMask === value) {
  7167. return;
  7168. }
  7169. this._stencilMask = value;
  7170. this._isStencilMaskDirty = true;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7176. get: function () {
  7177. return this._stencilTest;
  7178. },
  7179. set: function (value) {
  7180. if (this._stencilTest === value) {
  7181. return;
  7182. }
  7183. this._stencilTest = value;
  7184. this._isStencilTestDirty = true;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. _StencilState.prototype.reset = function () {
  7190. this._stencilTest = false;
  7191. this._stencilMask = 0xFF;
  7192. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7193. this._stencilFuncRef = 1;
  7194. this._stencilFuncMask = 0xFF;
  7195. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7196. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7197. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7198. this._isStencilTestDirty = true;
  7199. this._isStencilMaskDirty = true;
  7200. this._isStencilFuncDirty = true;
  7201. this._isStencilOpDirty = true;
  7202. };
  7203. _StencilState.prototype.apply = function (gl) {
  7204. if (!this.isDirty) {
  7205. return;
  7206. }
  7207. // Stencil test
  7208. if (this._isStencilTestDirty) {
  7209. if (this.stencilTest) {
  7210. gl.enable(gl.STENCIL_TEST);
  7211. }
  7212. else {
  7213. gl.disable(gl.STENCIL_TEST);
  7214. }
  7215. this._isStencilTestDirty = false;
  7216. }
  7217. // Stencil mask
  7218. if (this._isStencilMaskDirty) {
  7219. gl.stencilMask(this.stencilMask);
  7220. this._isStencilMaskDirty = false;
  7221. }
  7222. // Stencil func
  7223. if (this._isStencilFuncDirty) {
  7224. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7225. this._isStencilFuncDirty = false;
  7226. }
  7227. // Stencil op
  7228. if (this._isStencilOpDirty) {
  7229. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7230. this._isStencilOpDirty = false;
  7231. }
  7232. };
  7233. return _StencilState;
  7234. }());
  7235. Internals._StencilState = _StencilState;
  7236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7237. })(BABYLON || (BABYLON = {}));
  7238. //# sourceMappingURL=babylon.stencilState.js.map
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7242. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7243. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7244. gl.compileShader(shader);
  7245. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7246. throw new Error(gl.getShaderInfoLog(shader));
  7247. }
  7248. return shader;
  7249. };
  7250. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7251. var magFilter = gl.NEAREST;
  7252. var minFilter = gl.NEAREST;
  7253. switch (samplingMode) {
  7254. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7255. magFilter = gl.LINEAR;
  7256. if (generateMipMaps) {
  7257. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7258. }
  7259. else {
  7260. minFilter = gl.LINEAR;
  7261. }
  7262. break;
  7263. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7264. magFilter = gl.LINEAR;
  7265. if (generateMipMaps) {
  7266. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7267. }
  7268. else {
  7269. minFilter = gl.LINEAR;
  7270. }
  7271. break;
  7272. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7273. magFilter = gl.NEAREST;
  7274. if (generateMipMaps) {
  7275. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7276. }
  7277. else {
  7278. minFilter = gl.NEAREST;
  7279. }
  7280. break;
  7281. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7282. magFilter = gl.NEAREST;
  7283. if (generateMipMaps) {
  7284. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7285. }
  7286. else {
  7287. minFilter = gl.NEAREST;
  7288. }
  7289. break;
  7290. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7291. magFilter = gl.NEAREST;
  7292. if (generateMipMaps) {
  7293. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7294. }
  7295. else {
  7296. minFilter = gl.LINEAR;
  7297. }
  7298. break;
  7299. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7300. magFilter = gl.NEAREST;
  7301. if (generateMipMaps) {
  7302. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7303. }
  7304. else {
  7305. minFilter = gl.LINEAR;
  7306. }
  7307. break;
  7308. case BABYLON.Texture.NEAREST_LINEAR:
  7309. magFilter = gl.NEAREST;
  7310. minFilter = gl.LINEAR;
  7311. break;
  7312. case BABYLON.Texture.NEAREST_NEAREST:
  7313. magFilter = gl.NEAREST;
  7314. minFilter = gl.NEAREST;
  7315. break;
  7316. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7317. magFilter = gl.LINEAR;
  7318. if (generateMipMaps) {
  7319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7320. }
  7321. else {
  7322. minFilter = gl.NEAREST;
  7323. }
  7324. break;
  7325. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7326. magFilter = gl.LINEAR;
  7327. if (generateMipMaps) {
  7328. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7329. }
  7330. else {
  7331. minFilter = gl.NEAREST;
  7332. }
  7333. break;
  7334. case BABYLON.Texture.LINEAR_LINEAR:
  7335. magFilter = gl.LINEAR;
  7336. minFilter = gl.LINEAR;
  7337. break;
  7338. case BABYLON.Texture.LINEAR_NEAREST:
  7339. magFilter = gl.LINEAR;
  7340. minFilter = gl.NEAREST;
  7341. break;
  7342. }
  7343. return {
  7344. min: minFilter,
  7345. mag: magFilter
  7346. };
  7347. };
  7348. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7349. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7350. var img;
  7351. var onload = function () {
  7352. loadedImages[index] = img;
  7353. loadedImages._internalCount++;
  7354. scene._removePendingData(img);
  7355. if (loadedImages._internalCount === 6) {
  7356. onfinish(loadedImages);
  7357. }
  7358. };
  7359. var onerror = function () {
  7360. scene._removePendingData(img);
  7361. if (onErrorCallBack) {
  7362. onErrorCallBack();
  7363. }
  7364. };
  7365. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7366. scene._addPendingData(img);
  7367. };
  7368. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7369. if (onError === void 0) { onError = null; }
  7370. var loadedImages = [];
  7371. loadedImages._internalCount = 0;
  7372. for (var index = 0; index < 6; index++) {
  7373. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7374. }
  7375. };
  7376. var BufferPointer = (function () {
  7377. function BufferPointer() {
  7378. }
  7379. return BufferPointer;
  7380. }());
  7381. var InstancingAttributeInfo = (function () {
  7382. function InstancingAttributeInfo() {
  7383. }
  7384. return InstancingAttributeInfo;
  7385. }());
  7386. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7387. /**
  7388. * Regroup several parameters relative to the browser in use
  7389. */
  7390. var EngineCapabilities = (function () {
  7391. function EngineCapabilities() {
  7392. }
  7393. return EngineCapabilities;
  7394. }());
  7395. BABYLON.EngineCapabilities = EngineCapabilities;
  7396. /**
  7397. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7398. */
  7399. var Engine = (function () {
  7400. /**
  7401. * @constructor
  7402. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7403. * @param {boolean} [antialias] - enable antialias
  7404. * @param options - further options to be sent to the getContext function
  7405. */
  7406. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7407. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7408. var _this = this;
  7409. // Public members
  7410. this.forcePOTTextures = false;
  7411. this.isFullscreen = false;
  7412. this.isPointerLock = false;
  7413. this.cullBackFaces = true;
  7414. this.renderEvenInBackground = true;
  7415. this.preventCacheWipeBetweenFrames = false;
  7416. // To enable/disable IDB support and avoid XHR on .manifest
  7417. this.enableOfflineSupport = false;
  7418. this.scenes = new Array();
  7419. // Observables
  7420. /**
  7421. * Observable event triggered each time the rendering canvas is resized
  7422. */
  7423. this.onResizeObservable = new BABYLON.Observable();
  7424. /**
  7425. * Observable event triggered each time the canvas lost focus
  7426. */
  7427. this.onCanvasBlurObservable = new BABYLON.Observable();
  7428. this._windowIsBackground = false;
  7429. this._webGLVersion = 1.0;
  7430. this._badOS = false;
  7431. this._badDesktopOS = false;
  7432. this._drawCalls = new BABYLON.PerfCounter();
  7433. this._renderingQueueLaunched = false;
  7434. this._activeRenderLoops = [];
  7435. // Deterministic lockstepMaxSteps
  7436. this._deterministicLockstep = false;
  7437. this._lockstepMaxSteps = 4;
  7438. // FPS
  7439. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7440. this._fps = 60;
  7441. this._deltaTime = 0;
  7442. /**
  7443. * Turn this value on if you want to pause FPS computation when in background
  7444. */
  7445. this.disablePerformanceMonitorInBackground = false;
  7446. // States
  7447. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7448. this._stencilState = new BABYLON.Internals._StencilState();
  7449. this._alphaState = new BABYLON.Internals._AlphaState();
  7450. this._alphaMode = Engine.ALPHA_DISABLE;
  7451. // Cache
  7452. this._loadedTexturesCache = new Array();
  7453. this._maxTextureChannels = 16;
  7454. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7455. this._compiledEffects = {};
  7456. this._vertexAttribArraysEnabled = [];
  7457. this._uintIndicesCurrentlySet = false;
  7458. this._currentBoundBuffer = new Array();
  7459. this._currentBufferPointers = new Array();
  7460. this._currentInstanceLocations = new Array();
  7461. this._currentInstanceBuffers = new Array();
  7462. this._vaoRecordInProgress = false;
  7463. this._mustWipeVertexAttributes = false;
  7464. // Hardware supported Compressed Textures
  7465. this._texturesSupported = new Array();
  7466. this._onVRFullScreenTriggered = function () {
  7467. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7468. //get the old size before we change
  7469. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7470. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7471. //get the width and height, change the render size
  7472. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7473. var width, height;
  7474. _this.setHardwareScalingLevel(1);
  7475. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7476. }
  7477. else {
  7478. //When the specs are implemented, need to uncomment this.
  7479. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7480. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7481. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7482. _this._vrDisplayEnabled = undefined;
  7483. }
  7484. };
  7485. var canvas;
  7486. Engine.Instances.push(this);
  7487. options = options || {};
  7488. if (canvasOrContext.getContext) {
  7489. canvas = canvasOrContext;
  7490. this._renderingCanvas = canvas;
  7491. if (antialias != null) {
  7492. options.antialias = antialias;
  7493. }
  7494. if (options.deterministicLockstep === undefined) {
  7495. options.deterministicLockstep = false;
  7496. }
  7497. if (options.lockstepMaxSteps === undefined) {
  7498. options.lockstepMaxSteps = 4;
  7499. }
  7500. if (options.preserveDrawingBuffer === undefined) {
  7501. options.preserveDrawingBuffer = false;
  7502. }
  7503. if (options.audioEngine === undefined) {
  7504. options.audioEngine = true;
  7505. }
  7506. if (options.stencil === undefined) {
  7507. options.stencil = true;
  7508. }
  7509. this._deterministicLockstep = options.deterministicLockstep;
  7510. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7511. // GL
  7512. if (!options.disableWebGL2Support) {
  7513. try {
  7514. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7515. if (this._gl) {
  7516. this._webGLVersion = 2.0;
  7517. }
  7518. }
  7519. catch (e) {
  7520. // Do nothing
  7521. }
  7522. }
  7523. if (!this._gl) {
  7524. if (!canvas) {
  7525. throw new Error("The provided canvas is null or undefined.");
  7526. }
  7527. try {
  7528. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7529. }
  7530. catch (e) {
  7531. throw new Error("WebGL not supported");
  7532. }
  7533. }
  7534. if (!this._gl) {
  7535. throw new Error("WebGL not supported");
  7536. }
  7537. this._onBlur = function () {
  7538. if (_this.disablePerformanceMonitorInBackground) {
  7539. _this._performanceMonitor.disable();
  7540. }
  7541. _this._windowIsBackground = true;
  7542. };
  7543. this._onFocus = function () {
  7544. if (_this.disablePerformanceMonitorInBackground) {
  7545. _this._performanceMonitor.enable();
  7546. }
  7547. _this._windowIsBackground = false;
  7548. };
  7549. this._onCanvasBlur = function () {
  7550. _this.onCanvasBlurObservable.notifyObservers(_this);
  7551. };
  7552. window.addEventListener("blur", this._onBlur);
  7553. window.addEventListener("focus", this._onFocus);
  7554. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7555. }
  7556. else {
  7557. this._gl = canvasOrContext;
  7558. this._renderingCanvas = this._gl.canvas;
  7559. if (this._gl.renderbufferStorageMultisample) {
  7560. this._webGLVersion = 2.0;
  7561. }
  7562. options.stencil = this._gl.getContextAttributes().stencil;
  7563. }
  7564. // Viewport
  7565. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7566. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7567. this.resize();
  7568. // Caps
  7569. this._isStencilEnable = options.stencil;
  7570. this._caps = new EngineCapabilities();
  7571. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7572. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7573. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7574. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7575. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7576. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7577. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7578. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7579. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7580. // Infos
  7581. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7582. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7583. if (rendererInfo != null) {
  7584. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7585. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7586. }
  7587. if (!this._glVendor) {
  7588. this._glVendor = "Unknown vendor";
  7589. }
  7590. if (!this._glRenderer) {
  7591. this._glRenderer = "Unknown renderer";
  7592. }
  7593. // Constants
  7594. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7595. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7596. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7597. this._gl.DEPTH24_STENCIL8 = 35056;
  7598. // Extensions
  7599. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7600. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7601. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7602. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7603. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7604. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7605. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7606. 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');
  7607. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7608. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7609. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7610. this._caps.highPrecisionShaderSupported = true;
  7611. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7612. // Checks if some of the format renders first to allow the use of webgl inspector.
  7613. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7614. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7615. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7616. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7617. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7618. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7619. if (this._webGLVersion > 1) {
  7620. this._gl.HALF_FLOAT_OES = 0x140B;
  7621. }
  7622. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7623. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7624. // Vertex array object
  7625. if (this._webGLVersion > 1) {
  7626. this._caps.vertexArrayObject = true;
  7627. }
  7628. else {
  7629. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7630. if (vertexArrayObjectExtension != null) {
  7631. this._caps.vertexArrayObject = true;
  7632. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7633. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7634. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7635. }
  7636. else {
  7637. this._caps.vertexArrayObject = false;
  7638. }
  7639. }
  7640. // Instances count
  7641. if (this._webGLVersion > 1) {
  7642. this._caps.instancedArrays = true;
  7643. }
  7644. else {
  7645. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7646. if (instanceExtension != null) {
  7647. this._caps.instancedArrays = true;
  7648. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7649. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7650. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7651. }
  7652. else {
  7653. this._caps.instancedArrays = false;
  7654. }
  7655. }
  7656. // Intelligently add supported compressed formats in order to check for.
  7657. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7658. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7659. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7660. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7661. if (this._caps.astc)
  7662. this.texturesSupported.push('-astc.ktx');
  7663. if (this._caps.s3tc)
  7664. this.texturesSupported.push('-dxt.ktx');
  7665. if (this._caps.pvrtc)
  7666. this.texturesSupported.push('-pvrtc.ktx');
  7667. if (this._caps.etc2)
  7668. this.texturesSupported.push('-etc2.ktx');
  7669. if (this._caps.etc1)
  7670. this.texturesSupported.push('-etc1.ktx');
  7671. if (this._gl.getShaderPrecisionFormat) {
  7672. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7673. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7674. }
  7675. // Depth buffer
  7676. this.setDepthBuffer(true);
  7677. this.setDepthFunctionToLessOrEqual();
  7678. this.setDepthWrite(true);
  7679. if (canvas) {
  7680. // Fullscreen
  7681. this._onFullscreenChange = function () {
  7682. if (document.fullscreen !== undefined) {
  7683. _this.isFullscreen = document.fullscreen;
  7684. }
  7685. else if (document.mozFullScreen !== undefined) {
  7686. _this.isFullscreen = document.mozFullScreen;
  7687. }
  7688. else if (document.webkitIsFullScreen !== undefined) {
  7689. _this.isFullscreen = document.webkitIsFullScreen;
  7690. }
  7691. else if (document.msIsFullScreen !== undefined) {
  7692. _this.isFullscreen = document.msIsFullScreen;
  7693. }
  7694. // Pointer lock
  7695. if (_this.isFullscreen && _this._pointerLockRequested) {
  7696. canvas.requestPointerLock = canvas.requestPointerLock ||
  7697. canvas.msRequestPointerLock ||
  7698. canvas.mozRequestPointerLock ||
  7699. canvas.webkitRequestPointerLock;
  7700. if (canvas.requestPointerLock) {
  7701. canvas.requestPointerLock();
  7702. }
  7703. }
  7704. };
  7705. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7706. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7707. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7708. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7709. // Pointer lock
  7710. this._onPointerLockChange = function () {
  7711. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7712. document.webkitPointerLockElement === canvas ||
  7713. document.msPointerLockElement === canvas ||
  7714. document.pointerLockElement === canvas);
  7715. };
  7716. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7717. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7718. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7719. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7720. }
  7721. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7722. Engine.audioEngine = new BABYLON.AudioEngine();
  7723. }
  7724. // Prepare buffer pointers
  7725. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7726. this._currentBufferPointers[i] = new BufferPointer();
  7727. }
  7728. // Load WebVR Devices
  7729. if (options.autoEnableWebVR) {
  7730. this.initWebVR();
  7731. }
  7732. // Detect if we are running on a faulty buggy OS.
  7733. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7734. // Detect if we are running on a faulty buggy desktop OS.
  7735. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7736. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7737. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7738. }
  7739. Object.defineProperty(Engine, "LastCreatedEngine", {
  7740. get: function () {
  7741. if (Engine.Instances.length === 0) {
  7742. return null;
  7743. }
  7744. return Engine.Instances[Engine.Instances.length - 1];
  7745. },
  7746. enumerable: true,
  7747. configurable: true
  7748. });
  7749. Object.defineProperty(Engine, "LastCreatedScene", {
  7750. get: function () {
  7751. var lastCreatedEngine = Engine.LastCreatedEngine;
  7752. if (!lastCreatedEngine) {
  7753. return null;
  7754. }
  7755. if (lastCreatedEngine.scenes.length === 0) {
  7756. return null;
  7757. }
  7758. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7759. },
  7760. enumerable: true,
  7761. configurable: true
  7762. });
  7763. /**
  7764. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7765. */
  7766. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7767. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7768. var engine = Engine.Instances[engineIndex];
  7769. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7770. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7771. }
  7772. }
  7773. };
  7774. Object.defineProperty(Engine, "NEVER", {
  7775. get: function () {
  7776. return Engine._NEVER;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(Engine, "ALWAYS", {
  7782. get: function () {
  7783. return Engine._ALWAYS;
  7784. },
  7785. enumerable: true,
  7786. configurable: true
  7787. });
  7788. Object.defineProperty(Engine, "LESS", {
  7789. get: function () {
  7790. return Engine._LESS;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine, "EQUAL", {
  7796. get: function () {
  7797. return Engine._EQUAL;
  7798. },
  7799. enumerable: true,
  7800. configurable: true
  7801. });
  7802. Object.defineProperty(Engine, "LEQUAL", {
  7803. get: function () {
  7804. return Engine._LEQUAL;
  7805. },
  7806. enumerable: true,
  7807. configurable: true
  7808. });
  7809. Object.defineProperty(Engine, "GREATER", {
  7810. get: function () {
  7811. return Engine._GREATER;
  7812. },
  7813. enumerable: true,
  7814. configurable: true
  7815. });
  7816. Object.defineProperty(Engine, "GEQUAL", {
  7817. get: function () {
  7818. return Engine._GEQUAL;
  7819. },
  7820. enumerable: true,
  7821. configurable: true
  7822. });
  7823. Object.defineProperty(Engine, "NOTEQUAL", {
  7824. get: function () {
  7825. return Engine._NOTEQUAL;
  7826. },
  7827. enumerable: true,
  7828. configurable: true
  7829. });
  7830. Object.defineProperty(Engine, "KEEP", {
  7831. get: function () {
  7832. return Engine._KEEP;
  7833. },
  7834. enumerable: true,
  7835. configurable: true
  7836. });
  7837. Object.defineProperty(Engine, "REPLACE", {
  7838. get: function () {
  7839. return Engine._REPLACE;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Object.defineProperty(Engine, "INCR", {
  7845. get: function () {
  7846. return Engine._INCR;
  7847. },
  7848. enumerable: true,
  7849. configurable: true
  7850. });
  7851. Object.defineProperty(Engine, "DECR", {
  7852. get: function () {
  7853. return Engine._DECR;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. Object.defineProperty(Engine, "INVERT", {
  7859. get: function () {
  7860. return Engine._INVERT;
  7861. },
  7862. enumerable: true,
  7863. configurable: true
  7864. });
  7865. Object.defineProperty(Engine, "INCR_WRAP", {
  7866. get: function () {
  7867. return Engine._INCR_WRAP;
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. Object.defineProperty(Engine, "DECR_WRAP", {
  7873. get: function () {
  7874. return Engine._DECR_WRAP;
  7875. },
  7876. enumerable: true,
  7877. configurable: true
  7878. });
  7879. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7880. get: function () {
  7881. return Engine._ALPHA_DISABLE;
  7882. },
  7883. enumerable: true,
  7884. configurable: true
  7885. });
  7886. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7887. get: function () {
  7888. return Engine._ALPHA_ONEONE;
  7889. },
  7890. enumerable: true,
  7891. configurable: true
  7892. });
  7893. Object.defineProperty(Engine, "ALPHA_ADD", {
  7894. get: function () {
  7895. return Engine._ALPHA_ADD;
  7896. },
  7897. enumerable: true,
  7898. configurable: true
  7899. });
  7900. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7901. get: function () {
  7902. return Engine._ALPHA_COMBINE;
  7903. },
  7904. enumerable: true,
  7905. configurable: true
  7906. });
  7907. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7908. get: function () {
  7909. return Engine._ALPHA_SUBTRACT;
  7910. },
  7911. enumerable: true,
  7912. configurable: true
  7913. });
  7914. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7915. get: function () {
  7916. return Engine._ALPHA_MULTIPLY;
  7917. },
  7918. enumerable: true,
  7919. configurable: true
  7920. });
  7921. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7922. get: function () {
  7923. return Engine._ALPHA_MAXIMIZED;
  7924. },
  7925. enumerable: true,
  7926. configurable: true
  7927. });
  7928. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7929. get: function () {
  7930. return Engine._ALPHA_PREMULTIPLIED;
  7931. },
  7932. enumerable: true,
  7933. configurable: true
  7934. });
  7935. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7936. get: function () {
  7937. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7943. get: function () {
  7944. return Engine._ALPHA_INTERPOLATE;
  7945. },
  7946. enumerable: true,
  7947. configurable: true
  7948. });
  7949. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7950. get: function () {
  7951. return Engine._ALPHA_SCREENMODE;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7957. get: function () {
  7958. return Engine._DELAYLOADSTATE_NONE;
  7959. },
  7960. enumerable: true,
  7961. configurable: true
  7962. });
  7963. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7964. get: function () {
  7965. return Engine._DELAYLOADSTATE_LOADED;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7971. get: function () {
  7972. return Engine._DELAYLOADSTATE_LOADING;
  7973. },
  7974. enumerable: true,
  7975. configurable: true
  7976. });
  7977. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7978. get: function () {
  7979. return Engine._DELAYLOADSTATE_NOTLOADED;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7985. get: function () {
  7986. return Engine._TEXTUREFORMAT_ALPHA;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7992. get: function () {
  7993. return Engine._TEXTUREFORMAT_LUMINANCE;
  7994. },
  7995. enumerable: true,
  7996. configurable: true
  7997. });
  7998. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7999. get: function () {
  8000. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8006. get: function () {
  8007. return Engine._TEXTUREFORMAT_RGB;
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8013. get: function () {
  8014. return Engine._TEXTUREFORMAT_RGBA;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8020. get: function () {
  8021. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8027. get: function () {
  8028. return Engine._TEXTURETYPE_FLOAT;
  8029. },
  8030. enumerable: true,
  8031. configurable: true
  8032. });
  8033. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8034. get: function () {
  8035. return Engine._TEXTURETYPE_HALF_FLOAT;
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8041. get: function () {
  8042. return Engine._SCALEMODE_FLOOR;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8048. get: function () {
  8049. return Engine._SCALEMODE_NEAREST;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8055. get: function () {
  8056. return Engine._SCALEMODE_CEILING;
  8057. },
  8058. enumerable: true,
  8059. configurable: true
  8060. });
  8061. Object.defineProperty(Engine, "Version", {
  8062. get: function () {
  8063. return "3.1-alpha";
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8069. get: function () {
  8070. return this._webGLVersion < 2 || this.forcePOTTextures;
  8071. },
  8072. enumerable: true,
  8073. configurable: true
  8074. });
  8075. Object.defineProperty(Engine.prototype, "badOS", {
  8076. get: function () {
  8077. return this._badOS;
  8078. },
  8079. enumerable: true,
  8080. configurable: true
  8081. });
  8082. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8083. get: function () {
  8084. return this._badDesktopOS;
  8085. },
  8086. enumerable: true,
  8087. configurable: true
  8088. });
  8089. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8090. get: function () {
  8091. return this._performanceMonitor;
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8097. get: function () {
  8098. return this._texturesSupported;
  8099. },
  8100. enumerable: true,
  8101. configurable: true
  8102. });
  8103. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8104. get: function () {
  8105. return this._textureFormatInUse;
  8106. },
  8107. enumerable: true,
  8108. configurable: true
  8109. });
  8110. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8111. // Empty texture
  8112. get: function () {
  8113. if (!this._emptyTexture) {
  8114. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8115. }
  8116. return this._emptyTexture;
  8117. },
  8118. enumerable: true,
  8119. configurable: true
  8120. });
  8121. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8122. get: function () {
  8123. if (!this._emptyCubeTexture) {
  8124. var faceData = new Uint8Array(4);
  8125. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8126. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8127. }
  8128. return this._emptyCubeTexture;
  8129. },
  8130. enumerable: true,
  8131. configurable: true
  8132. });
  8133. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8134. get: function () {
  8135. return this._webGLVersion;
  8136. },
  8137. enumerable: true,
  8138. configurable: true
  8139. });
  8140. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8141. /**
  8142. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8143. */
  8144. get: function () {
  8145. return this._isStencilEnable;
  8146. },
  8147. enumerable: true,
  8148. configurable: true
  8149. });
  8150. Engine.prototype._prepareWorkingCanvas = function () {
  8151. if (this._workingCanvas) {
  8152. return;
  8153. }
  8154. this._workingCanvas = document.createElement("canvas");
  8155. this._workingContext = this._workingCanvas.getContext("2d");
  8156. };
  8157. Engine.prototype.resetTextureCache = function () {
  8158. for (var index = 0; index < this._maxTextureChannels; index++) {
  8159. this._activeTexturesCache[index] = null;
  8160. }
  8161. };
  8162. Engine.prototype.isDeterministicLockStep = function () {
  8163. return this._deterministicLockstep;
  8164. };
  8165. Engine.prototype.getLockstepMaxSteps = function () {
  8166. return this._lockstepMaxSteps;
  8167. };
  8168. Engine.prototype.getGlInfo = function () {
  8169. return {
  8170. vendor: this._glVendor,
  8171. renderer: this._glRenderer,
  8172. version: this._glVersion
  8173. };
  8174. };
  8175. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8176. if (useScreen === void 0) { useScreen = false; }
  8177. var viewport = camera.viewport;
  8178. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8179. };
  8180. Engine.prototype.getRenderWidth = function (useScreen) {
  8181. if (useScreen === void 0) { useScreen = false; }
  8182. if (!useScreen && this._currentRenderTarget) {
  8183. return this._currentRenderTarget._width;
  8184. }
  8185. return this._gl.drawingBufferWidth;
  8186. };
  8187. Engine.prototype.getRenderHeight = function (useScreen) {
  8188. if (useScreen === void 0) { useScreen = false; }
  8189. if (!useScreen && this._currentRenderTarget) {
  8190. return this._currentRenderTarget._height;
  8191. }
  8192. return this._gl.drawingBufferHeight;
  8193. };
  8194. Engine.prototype.getRenderingCanvas = function () {
  8195. return this._renderingCanvas;
  8196. };
  8197. Engine.prototype.getRenderingCanvasClientRect = function () {
  8198. return this._renderingCanvas.getBoundingClientRect();
  8199. };
  8200. Engine.prototype.setHardwareScalingLevel = function (level) {
  8201. this._hardwareScalingLevel = level;
  8202. this.resize();
  8203. };
  8204. Engine.prototype.getHardwareScalingLevel = function () {
  8205. return this._hardwareScalingLevel;
  8206. };
  8207. Engine.prototype.getLoadedTexturesCache = function () {
  8208. return this._loadedTexturesCache;
  8209. };
  8210. Engine.prototype.getCaps = function () {
  8211. return this._caps;
  8212. };
  8213. Object.defineProperty(Engine.prototype, "drawCalls", {
  8214. /** The number of draw calls submitted last frame */
  8215. get: function () {
  8216. return this._drawCalls.current;
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8222. get: function () {
  8223. return this._drawCalls;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Engine.prototype.getDepthFunction = function () {
  8229. return this._depthCullingState.depthFunc;
  8230. };
  8231. Engine.prototype.setDepthFunction = function (depthFunc) {
  8232. this._depthCullingState.depthFunc = depthFunc;
  8233. };
  8234. Engine.prototype.setDepthFunctionToGreater = function () {
  8235. this._depthCullingState.depthFunc = this._gl.GREATER;
  8236. };
  8237. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8238. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8239. };
  8240. Engine.prototype.setDepthFunctionToLess = function () {
  8241. this._depthCullingState.depthFunc = this._gl.LESS;
  8242. };
  8243. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8244. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8245. };
  8246. Engine.prototype.getStencilBuffer = function () {
  8247. return this._stencilState.stencilTest;
  8248. };
  8249. Engine.prototype.setStencilBuffer = function (enable) {
  8250. this._stencilState.stencilTest = enable;
  8251. };
  8252. Engine.prototype.getStencilMask = function () {
  8253. return this._stencilState.stencilMask;
  8254. };
  8255. Engine.prototype.setStencilMask = function (mask) {
  8256. this._stencilState.stencilMask = mask;
  8257. };
  8258. Engine.prototype.getStencilFunction = function () {
  8259. return this._stencilState.stencilFunc;
  8260. };
  8261. Engine.prototype.getStencilFunctionReference = function () {
  8262. return this._stencilState.stencilFuncRef;
  8263. };
  8264. Engine.prototype.getStencilFunctionMask = function () {
  8265. return this._stencilState.stencilFuncMask;
  8266. };
  8267. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8268. this._stencilState.stencilFunc = stencilFunc;
  8269. };
  8270. Engine.prototype.setStencilFunctionReference = function (reference) {
  8271. this._stencilState.stencilFuncRef = reference;
  8272. };
  8273. Engine.prototype.setStencilFunctionMask = function (mask) {
  8274. this._stencilState.stencilFuncMask = mask;
  8275. };
  8276. Engine.prototype.getStencilOperationFail = function () {
  8277. return this._stencilState.stencilOpStencilFail;
  8278. };
  8279. Engine.prototype.getStencilOperationDepthFail = function () {
  8280. return this._stencilState.stencilOpDepthFail;
  8281. };
  8282. Engine.prototype.getStencilOperationPass = function () {
  8283. return this._stencilState.stencilOpStencilDepthPass;
  8284. };
  8285. Engine.prototype.setStencilOperationFail = function (operation) {
  8286. this._stencilState.stencilOpStencilFail = operation;
  8287. };
  8288. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8289. this._stencilState.stencilOpDepthFail = operation;
  8290. };
  8291. Engine.prototype.setStencilOperationPass = function (operation) {
  8292. this._stencilState.stencilOpStencilDepthPass = operation;
  8293. };
  8294. Engine.prototype.setDitheringState = function (value) {
  8295. if (value) {
  8296. this._gl.enable(this._gl.DITHER);
  8297. }
  8298. else {
  8299. this._gl.disable(this._gl.DITHER);
  8300. }
  8301. };
  8302. /**
  8303. * stop executing a render loop function and remove it from the execution array
  8304. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8305. */
  8306. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8307. if (!renderFunction) {
  8308. this._activeRenderLoops = [];
  8309. return;
  8310. }
  8311. var index = this._activeRenderLoops.indexOf(renderFunction);
  8312. if (index >= 0) {
  8313. this._activeRenderLoops.splice(index, 1);
  8314. }
  8315. };
  8316. Engine.prototype._renderLoop = function () {
  8317. var shouldRender = true;
  8318. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8319. shouldRender = false;
  8320. }
  8321. if (shouldRender) {
  8322. // Start new frame
  8323. this.beginFrame();
  8324. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8325. var renderFunction = this._activeRenderLoops[index];
  8326. renderFunction();
  8327. }
  8328. // Present
  8329. this.endFrame();
  8330. }
  8331. if (this._activeRenderLoops.length > 0) {
  8332. // Register new frame
  8333. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8334. }
  8335. else {
  8336. this._renderingQueueLaunched = false;
  8337. }
  8338. };
  8339. /**
  8340. * Register and execute a render loop. The engine can have more than one render function.
  8341. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8342. * @example
  8343. * engine.runRenderLoop(function () {
  8344. * scene.render()
  8345. * })
  8346. */
  8347. Engine.prototype.runRenderLoop = function (renderFunction) {
  8348. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8349. return;
  8350. }
  8351. this._activeRenderLoops.push(renderFunction);
  8352. if (!this._renderingQueueLaunched) {
  8353. this._renderingQueueLaunched = true;
  8354. this._bindedRenderFunction = this._renderLoop.bind(this);
  8355. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8356. }
  8357. };
  8358. /**
  8359. * Toggle full screen mode.
  8360. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8361. * @param {any} options - an options object to be sent to the requestFullscreen function
  8362. */
  8363. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8364. if (this.isFullscreen) {
  8365. BABYLON.Tools.ExitFullscreen();
  8366. }
  8367. else {
  8368. this._pointerLockRequested = requestPointerLock;
  8369. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8370. }
  8371. };
  8372. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8373. if (stencil === void 0) { stencil = false; }
  8374. this.applyStates();
  8375. var mode = 0;
  8376. if (backBuffer && color) {
  8377. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8378. mode |= this._gl.COLOR_BUFFER_BIT;
  8379. }
  8380. if (depth) {
  8381. this._gl.clearDepth(1.0);
  8382. mode |= this._gl.DEPTH_BUFFER_BIT;
  8383. }
  8384. if (stencil) {
  8385. this._gl.clearStencil(0);
  8386. mode |= this._gl.STENCIL_BUFFER_BIT;
  8387. }
  8388. this._gl.clear(mode);
  8389. };
  8390. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8391. var gl = this._gl;
  8392. // Save state
  8393. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8394. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8395. // Change state
  8396. gl.enable(gl.SCISSOR_TEST);
  8397. gl.scissor(x, y, width, height);
  8398. // Clear
  8399. this.clear(clearColor, true, true, true);
  8400. // Restore state
  8401. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8402. if (curScissor === true) {
  8403. gl.enable(gl.SCISSOR_TEST);
  8404. }
  8405. else {
  8406. gl.disable(gl.SCISSOR_TEST);
  8407. }
  8408. };
  8409. /**
  8410. * Set the WebGL's viewport
  8411. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8412. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8413. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8414. */
  8415. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8416. var width = requiredWidth || this.getRenderWidth();
  8417. var height = requiredHeight || this.getRenderHeight();
  8418. var x = viewport.x || 0;
  8419. var y = viewport.y || 0;
  8420. this._cachedViewport = viewport;
  8421. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8422. };
  8423. /**
  8424. * Directly set the WebGL Viewport
  8425. * The x, y, width & height are directly passed to the WebGL call
  8426. * @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.
  8427. */
  8428. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8429. var currentViewport = this._cachedViewport;
  8430. this._cachedViewport = null;
  8431. this._gl.viewport(x, y, width, height);
  8432. return currentViewport;
  8433. };
  8434. Engine.prototype.beginFrame = function () {
  8435. this._measureFps();
  8436. };
  8437. Engine.prototype.endFrame = function () {
  8438. //force a flush in case we are using a bad OS.
  8439. if (this._badOS) {
  8440. this.flushFramebuffer();
  8441. }
  8442. //submit frame to the vr device, if enabled
  8443. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8444. this._vrDisplayEnabled.submitFrame();
  8445. }
  8446. };
  8447. /**
  8448. * resize the view according to the canvas' size.
  8449. * @example
  8450. * window.addEventListener("resize", function () {
  8451. * engine.resize();
  8452. * });
  8453. */
  8454. Engine.prototype.resize = function () {
  8455. // We're not resizing the size of the canvas while in VR mode & presenting
  8456. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8457. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8458. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8459. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8460. }
  8461. };
  8462. /**
  8463. * force a specific size of the canvas
  8464. * @param {number} width - the new canvas' width
  8465. * @param {number} height - the new canvas' height
  8466. */
  8467. Engine.prototype.setSize = function (width, height) {
  8468. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8469. return;
  8470. }
  8471. this._renderingCanvas.width = width;
  8472. this._renderingCanvas.height = height;
  8473. for (var index = 0; index < this.scenes.length; index++) {
  8474. var scene = this.scenes[index];
  8475. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8476. var cam = scene.cameras[camIndex];
  8477. cam._currentRenderId = 0;
  8478. }
  8479. }
  8480. if (this.onResizeObservable.hasObservers) {
  8481. this.onResizeObservable.notifyObservers(this);
  8482. }
  8483. };
  8484. //WebVR functions
  8485. Engine.prototype.isVRDevicePresent = function (callback) {
  8486. this.getVRDevice(null, function (device) {
  8487. callback(device !== null);
  8488. });
  8489. };
  8490. Engine.prototype.getVRDevice = function (name, callback) {
  8491. if (!this.vrDisplaysPromise) {
  8492. callback(null);
  8493. return;
  8494. }
  8495. this.vrDisplaysPromise.then(function (devices) {
  8496. if (devices.length > 0) {
  8497. if (name) {
  8498. var found = devices.some(function (device) {
  8499. if (device.displayName === name) {
  8500. callback(device);
  8501. return true;
  8502. }
  8503. else {
  8504. return false;
  8505. }
  8506. });
  8507. if (!found) {
  8508. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8509. callback(devices[0]);
  8510. }
  8511. }
  8512. else {
  8513. //choose the first one
  8514. callback(devices[0]);
  8515. }
  8516. }
  8517. else {
  8518. BABYLON.Tools.Error("No WebVR devices found!");
  8519. callback(null);
  8520. }
  8521. });
  8522. };
  8523. Engine.prototype.initWebVR = function () {
  8524. if (!this.vrDisplaysPromise) {
  8525. this._getVRDisplays();
  8526. }
  8527. };
  8528. Engine.prototype.enableVR = function (vrDevice) {
  8529. this._vrDisplayEnabled = vrDevice;
  8530. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8531. };
  8532. Engine.prototype.disableVR = function () {
  8533. if (this._vrDisplayEnabled) {
  8534. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8535. }
  8536. };
  8537. Engine.prototype._getVRDisplays = function () {
  8538. var _this = this;
  8539. var getWebVRDevices = function (devices) {
  8540. var size = devices.length;
  8541. var i = 0;
  8542. _this._vrDisplays = devices.filter(function (device) {
  8543. return devices[i] instanceof VRDisplay;
  8544. });
  8545. return _this._vrDisplays;
  8546. };
  8547. //using a key due to typescript
  8548. if (navigator.getVRDisplays) {
  8549. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8550. }
  8551. };
  8552. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8553. if (this._currentRenderTarget) {
  8554. this.unBindFramebuffer(this._currentRenderTarget);
  8555. }
  8556. this._currentRenderTarget = texture;
  8557. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8558. var gl = this._gl;
  8559. if (texture.isCube) {
  8560. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8561. }
  8562. if (this._cachedViewport && !forceFullscreenViewport) {
  8563. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8564. }
  8565. else {
  8566. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8567. }
  8568. this.wipeCaches();
  8569. };
  8570. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8571. if (this._currentFramebuffer !== framebuffer) {
  8572. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8573. this._currentFramebuffer = framebuffer;
  8574. }
  8575. };
  8576. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8577. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8578. this._currentRenderTarget = null;
  8579. // If MSAA, we need to bitblt back to main texture
  8580. var gl = this._gl;
  8581. if (texture._MSAAFramebuffer) {
  8582. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8583. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8584. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8585. }
  8586. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8587. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8588. gl.generateMipmap(gl.TEXTURE_2D);
  8589. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8590. }
  8591. if (onBeforeUnbind) {
  8592. if (texture._MSAAFramebuffer) {
  8593. // Bind the correct framebuffer
  8594. this.bindUnboundFramebuffer(texture._framebuffer);
  8595. }
  8596. onBeforeUnbind();
  8597. }
  8598. this.bindUnboundFramebuffer(null);
  8599. };
  8600. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8601. if (texture.generateMipMaps) {
  8602. var gl = this._gl;
  8603. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8604. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8605. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8606. }
  8607. };
  8608. Engine.prototype.flushFramebuffer = function () {
  8609. this._gl.flush();
  8610. };
  8611. Engine.prototype.restoreDefaultFramebuffer = function () {
  8612. if (this._currentRenderTarget) {
  8613. this.unBindFramebuffer(this._currentRenderTarget);
  8614. }
  8615. else {
  8616. this.bindUnboundFramebuffer(null);
  8617. }
  8618. if (this._cachedViewport) {
  8619. this.setViewport(this._cachedViewport);
  8620. }
  8621. this.wipeCaches();
  8622. };
  8623. // UBOs
  8624. Engine.prototype.createUniformBuffer = function (elements) {
  8625. var ubo = this._gl.createBuffer();
  8626. this.bindUniformBuffer(ubo);
  8627. if (elements instanceof Float32Array) {
  8628. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8629. }
  8630. else {
  8631. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8632. }
  8633. this.bindUniformBuffer(null);
  8634. ubo.references = 1;
  8635. return ubo;
  8636. };
  8637. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8638. var ubo = this._gl.createBuffer();
  8639. this.bindUniformBuffer(ubo);
  8640. if (elements instanceof Float32Array) {
  8641. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8642. }
  8643. else {
  8644. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8645. }
  8646. this.bindUniformBuffer(null);
  8647. ubo.references = 1;
  8648. return ubo;
  8649. };
  8650. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8651. this.bindUniformBuffer(uniformBuffer);
  8652. if (offset === undefined) {
  8653. offset = 0;
  8654. }
  8655. if (count === undefined) {
  8656. if (elements instanceof Float32Array) {
  8657. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8658. }
  8659. else {
  8660. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8661. }
  8662. }
  8663. else {
  8664. if (elements instanceof Float32Array) {
  8665. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8666. }
  8667. else {
  8668. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8669. }
  8670. }
  8671. this.bindUniformBuffer(null);
  8672. };
  8673. // VBOs
  8674. Engine.prototype._resetVertexBufferBinding = function () {
  8675. this.bindArrayBuffer(null);
  8676. this._cachedVertexBuffers = null;
  8677. };
  8678. Engine.prototype.createVertexBuffer = function (vertices) {
  8679. var vbo = this._gl.createBuffer();
  8680. this.bindArrayBuffer(vbo);
  8681. if (vertices instanceof Float32Array) {
  8682. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8683. }
  8684. else {
  8685. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8686. }
  8687. this._resetVertexBufferBinding();
  8688. vbo.references = 1;
  8689. return vbo;
  8690. };
  8691. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8692. var vbo = this._gl.createBuffer();
  8693. this.bindArrayBuffer(vbo);
  8694. if (vertices instanceof Float32Array) {
  8695. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8696. }
  8697. else {
  8698. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8699. }
  8700. this._resetVertexBufferBinding();
  8701. vbo.references = 1;
  8702. return vbo;
  8703. };
  8704. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8705. this.bindArrayBuffer(vertexBuffer);
  8706. if (offset === undefined) {
  8707. offset = 0;
  8708. }
  8709. if (count === undefined) {
  8710. if (vertices instanceof Float32Array) {
  8711. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8712. }
  8713. else {
  8714. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8715. }
  8716. }
  8717. else {
  8718. if (vertices instanceof Float32Array) {
  8719. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8720. }
  8721. else {
  8722. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8723. }
  8724. }
  8725. this._resetVertexBufferBinding();
  8726. };
  8727. Engine.prototype._resetIndexBufferBinding = function () {
  8728. this.bindIndexBuffer(null);
  8729. this._cachedIndexBuffer = null;
  8730. };
  8731. Engine.prototype.createIndexBuffer = function (indices) {
  8732. var vbo = this._gl.createBuffer();
  8733. this.bindIndexBuffer(vbo);
  8734. // Check for 32 bits indices
  8735. var arrayBuffer;
  8736. var need32Bits = false;
  8737. if (indices instanceof Uint16Array) {
  8738. arrayBuffer = indices;
  8739. }
  8740. else {
  8741. //check 32 bit support
  8742. if (this._caps.uintIndices) {
  8743. if (indices instanceof Uint32Array) {
  8744. arrayBuffer = indices;
  8745. need32Bits = true;
  8746. }
  8747. else {
  8748. //number[] or Int32Array, check if 32 bit is necessary
  8749. for (var index = 0; index < indices.length; index++) {
  8750. if (indices[index] > 65535) {
  8751. need32Bits = true;
  8752. break;
  8753. }
  8754. }
  8755. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8756. }
  8757. }
  8758. else {
  8759. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8760. arrayBuffer = new Uint16Array(indices);
  8761. }
  8762. }
  8763. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8764. this._resetIndexBufferBinding();
  8765. vbo.references = 1;
  8766. vbo.is32Bits = need32Bits;
  8767. return vbo;
  8768. };
  8769. Engine.prototype.bindArrayBuffer = function (buffer) {
  8770. if (!this._vaoRecordInProgress) {
  8771. this._unbindVertexArrayObject();
  8772. }
  8773. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8774. };
  8775. Engine.prototype.bindUniformBuffer = function (buffer) {
  8776. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8777. };
  8778. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8779. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8780. };
  8781. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8782. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8783. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8784. };
  8785. ;
  8786. Engine.prototype.bindIndexBuffer = function (buffer) {
  8787. if (!this._vaoRecordInProgress) {
  8788. this._unbindVertexArrayObject();
  8789. }
  8790. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8791. };
  8792. Engine.prototype.bindBuffer = function (buffer, target) {
  8793. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8794. this._gl.bindBuffer(target, buffer);
  8795. this._currentBoundBuffer[target] = buffer;
  8796. }
  8797. };
  8798. Engine.prototype.updateArrayBuffer = function (data) {
  8799. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8800. };
  8801. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8802. var pointer = this._currentBufferPointers[indx];
  8803. var changed = false;
  8804. if (!pointer.active) {
  8805. changed = true;
  8806. pointer.active = true;
  8807. pointer.index = indx;
  8808. pointer.size = size;
  8809. pointer.type = type;
  8810. pointer.normalized = normalized;
  8811. pointer.stride = stride;
  8812. pointer.offset = offset;
  8813. pointer.buffer = buffer;
  8814. }
  8815. else {
  8816. if (pointer.buffer !== buffer) {
  8817. pointer.buffer = buffer;
  8818. changed = true;
  8819. }
  8820. if (pointer.size !== size) {
  8821. pointer.size = size;
  8822. changed = true;
  8823. }
  8824. if (pointer.type !== type) {
  8825. pointer.type = type;
  8826. changed = true;
  8827. }
  8828. if (pointer.normalized !== normalized) {
  8829. pointer.normalized = normalized;
  8830. changed = true;
  8831. }
  8832. if (pointer.stride !== stride) {
  8833. pointer.stride = stride;
  8834. changed = true;
  8835. }
  8836. if (pointer.offset !== offset) {
  8837. pointer.offset = offset;
  8838. changed = true;
  8839. }
  8840. }
  8841. if (changed || this._vaoRecordInProgress) {
  8842. this.bindArrayBuffer(buffer);
  8843. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8844. }
  8845. };
  8846. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8847. if (indexBuffer == null) {
  8848. return;
  8849. }
  8850. if (this._cachedIndexBuffer !== indexBuffer) {
  8851. this._cachedIndexBuffer = indexBuffer;
  8852. this.bindIndexBuffer(indexBuffer);
  8853. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8854. }
  8855. };
  8856. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8857. var attributes = effect.getAttributesNames();
  8858. if (!this._vaoRecordInProgress) {
  8859. this._unbindVertexArrayObject();
  8860. }
  8861. this.unbindAllAttributes();
  8862. for (var index = 0; index < attributes.length; index++) {
  8863. var order = effect.getAttributeLocation(index);
  8864. if (order >= 0) {
  8865. var vertexBuffer = vertexBuffers[attributes[index]];
  8866. if (!vertexBuffer) {
  8867. continue;
  8868. }
  8869. this._gl.enableVertexAttribArray(order);
  8870. if (!this._vaoRecordInProgress) {
  8871. this._vertexAttribArraysEnabled[order] = true;
  8872. }
  8873. var buffer = vertexBuffer.getBuffer();
  8874. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8875. if (vertexBuffer.getIsInstanced()) {
  8876. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8877. if (!this._vaoRecordInProgress) {
  8878. this._currentInstanceLocations.push(order);
  8879. this._currentInstanceBuffers.push(buffer);
  8880. }
  8881. }
  8882. }
  8883. }
  8884. };
  8885. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8886. var vao = this._gl.createVertexArray();
  8887. this._vaoRecordInProgress = true;
  8888. this._gl.bindVertexArray(vao);
  8889. this._mustWipeVertexAttributes = true;
  8890. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8891. this.bindIndexBuffer(indexBuffer);
  8892. this._vaoRecordInProgress = false;
  8893. this._gl.bindVertexArray(null);
  8894. return vao;
  8895. };
  8896. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8897. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8898. this._cachedVertexArrayObject = vertexArrayObject;
  8899. this._gl.bindVertexArray(vertexArrayObject);
  8900. this._cachedVertexBuffers = null;
  8901. this._cachedIndexBuffer = null;
  8902. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8903. this._mustWipeVertexAttributes = true;
  8904. }
  8905. };
  8906. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8907. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8908. this._cachedVertexBuffers = vertexBuffer;
  8909. this._cachedEffectForVertexBuffers = effect;
  8910. var attributesCount = effect.getAttributesCount();
  8911. this._unbindVertexArrayObject();
  8912. this.unbindAllAttributes();
  8913. var offset = 0;
  8914. for (var index = 0; index < attributesCount; index++) {
  8915. if (index < vertexDeclaration.length) {
  8916. var order = effect.getAttributeLocation(index);
  8917. if (order >= 0) {
  8918. this._gl.enableVertexAttribArray(order);
  8919. this._vertexAttribArraysEnabled[order] = true;
  8920. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8921. }
  8922. offset += vertexDeclaration[index] * 4;
  8923. }
  8924. }
  8925. }
  8926. this._bindIndexBufferWithCache(indexBuffer);
  8927. };
  8928. Engine.prototype._unbindVertexArrayObject = function () {
  8929. if (!this._cachedVertexArrayObject) {
  8930. return;
  8931. }
  8932. this._cachedVertexArrayObject = null;
  8933. this._gl.bindVertexArray(null);
  8934. };
  8935. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8936. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8937. this._cachedVertexBuffers = vertexBuffers;
  8938. this._cachedEffectForVertexBuffers = effect;
  8939. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8940. }
  8941. this._bindIndexBufferWithCache(indexBuffer);
  8942. };
  8943. Engine.prototype.unbindInstanceAttributes = function () {
  8944. var boundBuffer;
  8945. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8946. var instancesBuffer = this._currentInstanceBuffers[i];
  8947. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8948. boundBuffer = instancesBuffer;
  8949. this.bindArrayBuffer(instancesBuffer);
  8950. }
  8951. var offsetLocation = this._currentInstanceLocations[i];
  8952. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8953. }
  8954. this._currentInstanceBuffers.length = 0;
  8955. this._currentInstanceLocations.length = 0;
  8956. };
  8957. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8958. this._gl.deleteVertexArray(vao);
  8959. };
  8960. Engine.prototype._releaseBuffer = function (buffer) {
  8961. buffer.references--;
  8962. if (buffer.references === 0) {
  8963. this._gl.deleteBuffer(buffer);
  8964. return true;
  8965. }
  8966. return false;
  8967. };
  8968. Engine.prototype.createInstancesBuffer = function (capacity) {
  8969. var buffer = this._gl.createBuffer();
  8970. buffer.capacity = capacity;
  8971. this.bindArrayBuffer(buffer);
  8972. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8973. return buffer;
  8974. };
  8975. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8976. this._gl.deleteBuffer(buffer);
  8977. };
  8978. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8979. this.bindArrayBuffer(instancesBuffer);
  8980. if (data) {
  8981. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8982. }
  8983. if (offsetLocations[0].index !== undefined) {
  8984. var stride = 0;
  8985. for (var i = 0; i < offsetLocations.length; i++) {
  8986. var ai = offsetLocations[i];
  8987. stride += ai.attributeSize * 4;
  8988. }
  8989. for (var i = 0; i < offsetLocations.length; i++) {
  8990. var ai = offsetLocations[i];
  8991. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8992. this._gl.enableVertexAttribArray(ai.index);
  8993. this._vertexAttribArraysEnabled[ai.index] = true;
  8994. }
  8995. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8996. this._gl.vertexAttribDivisor(ai.index, 1);
  8997. this._currentInstanceLocations.push(ai.index);
  8998. this._currentInstanceBuffers.push(instancesBuffer);
  8999. }
  9000. }
  9001. else {
  9002. for (var index = 0; index < 4; index++) {
  9003. var offsetLocation = offsetLocations[index];
  9004. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9005. this._gl.enableVertexAttribArray(offsetLocation);
  9006. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9007. }
  9008. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9009. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9010. this._currentInstanceLocations.push(offsetLocation);
  9011. this._currentInstanceBuffers.push(instancesBuffer);
  9012. }
  9013. }
  9014. };
  9015. Engine.prototype.applyStates = function () {
  9016. this._depthCullingState.apply(this._gl);
  9017. this._stencilState.apply(this._gl);
  9018. this._alphaState.apply(this._gl);
  9019. };
  9020. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9021. // Apply states
  9022. this.applyStates();
  9023. this._drawCalls.addCount(1, false);
  9024. // Render
  9025. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9026. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9027. if (instancesCount) {
  9028. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9029. return;
  9030. }
  9031. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9032. };
  9033. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9034. // Apply states
  9035. this.applyStates();
  9036. this._drawCalls.addCount(1, false);
  9037. if (instancesCount) {
  9038. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9039. return;
  9040. }
  9041. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9042. };
  9043. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9044. // Apply states
  9045. this.applyStates();
  9046. this._drawCalls.addCount(1, false);
  9047. if (instancesCount) {
  9048. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9049. return;
  9050. }
  9051. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9052. };
  9053. // Shaders
  9054. Engine.prototype._releaseEffect = function (effect) {
  9055. if (this._compiledEffects[effect._key]) {
  9056. delete this._compiledEffects[effect._key];
  9057. if (effect.getProgram()) {
  9058. this._gl.deleteProgram(effect.getProgram());
  9059. }
  9060. }
  9061. };
  9062. /**
  9063. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9064. * @param samplers An array of string used to represent textures
  9065. */
  9066. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9067. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9068. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9069. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9070. if (this._compiledEffects[name]) {
  9071. var compiledEffect = this._compiledEffects[name];
  9072. if (onCompiled && compiledEffect.isReady()) {
  9073. onCompiled(compiledEffect);
  9074. }
  9075. return compiledEffect;
  9076. }
  9077. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9078. effect._key = name;
  9079. this._compiledEffects[name] = effect;
  9080. return effect;
  9081. };
  9082. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9083. if (uniformsNames === void 0) { uniformsNames = []; }
  9084. if (samplers === void 0) { samplers = []; }
  9085. if (defines === void 0) { defines = ""; }
  9086. return this.createEffect({
  9087. vertex: "particles",
  9088. fragmentElement: fragmentName
  9089. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9090. };
  9091. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9092. context = context || this._gl;
  9093. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9094. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9095. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9096. var shaderProgram = context.createProgram();
  9097. context.attachShader(shaderProgram, vertexShader);
  9098. context.attachShader(shaderProgram, fragmentShader);
  9099. context.linkProgram(shaderProgram);
  9100. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9101. if (!linked) {
  9102. context.validateProgram(shaderProgram);
  9103. var error = context.getProgramInfoLog(shaderProgram);
  9104. if (error) {
  9105. throw new Error(error);
  9106. }
  9107. }
  9108. context.deleteShader(vertexShader);
  9109. context.deleteShader(fragmentShader);
  9110. return shaderProgram;
  9111. };
  9112. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9113. var results = [];
  9114. for (var index = 0; index < uniformsNames.length; index++) {
  9115. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9116. }
  9117. return results;
  9118. };
  9119. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9120. var results = [];
  9121. for (var index = 0; index < attributesNames.length; index++) {
  9122. try {
  9123. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9124. }
  9125. catch (e) {
  9126. results.push(-1);
  9127. }
  9128. }
  9129. return results;
  9130. };
  9131. Engine.prototype.enableEffect = function (effect) {
  9132. // Use program
  9133. this.setProgram(effect.getProgram());
  9134. this._currentEffect = effect;
  9135. if (effect.onBind) {
  9136. effect.onBind(effect);
  9137. }
  9138. effect.onBindObservable.notifyObservers(effect);
  9139. };
  9140. Engine.prototype.setIntArray = function (uniform, array) {
  9141. if (!uniform)
  9142. return;
  9143. this._gl.uniform1iv(uniform, array);
  9144. };
  9145. Engine.prototype.setIntArray2 = function (uniform, array) {
  9146. if (!uniform || array.length % 2 !== 0)
  9147. return;
  9148. this._gl.uniform2iv(uniform, array);
  9149. };
  9150. Engine.prototype.setIntArray3 = function (uniform, array) {
  9151. if (!uniform || array.length % 3 !== 0)
  9152. return;
  9153. this._gl.uniform3iv(uniform, array);
  9154. };
  9155. Engine.prototype.setIntArray4 = function (uniform, array) {
  9156. if (!uniform || array.length % 4 !== 0)
  9157. return;
  9158. this._gl.uniform4iv(uniform, array);
  9159. };
  9160. Engine.prototype.setFloatArray = function (uniform, array) {
  9161. if (!uniform)
  9162. return;
  9163. this._gl.uniform1fv(uniform, array);
  9164. };
  9165. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9166. if (!uniform || array.length % 2 !== 0)
  9167. return;
  9168. this._gl.uniform2fv(uniform, array);
  9169. };
  9170. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9171. if (!uniform || array.length % 3 !== 0)
  9172. return;
  9173. this._gl.uniform3fv(uniform, array);
  9174. };
  9175. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9176. if (!uniform || array.length % 4 !== 0)
  9177. return;
  9178. this._gl.uniform4fv(uniform, array);
  9179. };
  9180. Engine.prototype.setArray = function (uniform, array) {
  9181. if (!uniform)
  9182. return;
  9183. this._gl.uniform1fv(uniform, array);
  9184. };
  9185. Engine.prototype.setArray2 = function (uniform, array) {
  9186. if (!uniform || array.length % 2 !== 0)
  9187. return;
  9188. this._gl.uniform2fv(uniform, array);
  9189. };
  9190. Engine.prototype.setArray3 = function (uniform, array) {
  9191. if (!uniform || array.length % 3 !== 0)
  9192. return;
  9193. this._gl.uniform3fv(uniform, array);
  9194. };
  9195. Engine.prototype.setArray4 = function (uniform, array) {
  9196. if (!uniform || array.length % 4 !== 0)
  9197. return;
  9198. this._gl.uniform4fv(uniform, array);
  9199. };
  9200. Engine.prototype.setMatrices = function (uniform, matrices) {
  9201. if (!uniform)
  9202. return;
  9203. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9204. };
  9205. Engine.prototype.setMatrix = function (uniform, matrix) {
  9206. if (!uniform)
  9207. return;
  9208. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9209. };
  9210. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9211. if (!uniform)
  9212. return;
  9213. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9214. };
  9215. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9216. if (!uniform)
  9217. return;
  9218. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9219. };
  9220. Engine.prototype.setFloat = function (uniform, value) {
  9221. if (!uniform)
  9222. return;
  9223. this._gl.uniform1f(uniform, value);
  9224. };
  9225. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9226. if (!uniform)
  9227. return;
  9228. this._gl.uniform2f(uniform, x, y);
  9229. };
  9230. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9231. if (!uniform)
  9232. return;
  9233. this._gl.uniform3f(uniform, x, y, z);
  9234. };
  9235. Engine.prototype.setBool = function (uniform, bool) {
  9236. if (!uniform)
  9237. return;
  9238. this._gl.uniform1i(uniform, bool);
  9239. };
  9240. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9241. if (!uniform)
  9242. return;
  9243. this._gl.uniform4f(uniform, x, y, z, w);
  9244. };
  9245. Engine.prototype.setColor3 = function (uniform, color3) {
  9246. if (!uniform)
  9247. return;
  9248. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9249. };
  9250. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9251. if (!uniform)
  9252. return;
  9253. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9254. };
  9255. // States
  9256. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9257. if (zOffset === void 0) { zOffset = 0; }
  9258. if (reverseSide === void 0) { reverseSide = false; }
  9259. // Culling
  9260. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9261. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9262. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9263. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9264. if (culling) {
  9265. this._depthCullingState.cullFace = cullFace;
  9266. this._depthCullingState.cull = true;
  9267. }
  9268. else {
  9269. this._depthCullingState.cull = false;
  9270. }
  9271. }
  9272. // Z offset
  9273. this.setZOffset(zOffset);
  9274. };
  9275. Engine.prototype.setZOffset = function (value) {
  9276. this._depthCullingState.zOffset = value;
  9277. };
  9278. Engine.prototype.getZOffset = function () {
  9279. return this._depthCullingState.zOffset;
  9280. };
  9281. Engine.prototype.setDepthBuffer = function (enable) {
  9282. this._depthCullingState.depthTest = enable;
  9283. };
  9284. Engine.prototype.getDepthWrite = function () {
  9285. return this._depthCullingState.depthMask;
  9286. };
  9287. Engine.prototype.setDepthWrite = function (enable) {
  9288. this._depthCullingState.depthMask = enable;
  9289. };
  9290. Engine.prototype.setColorWrite = function (enable) {
  9291. this._gl.colorMask(enable, enable, enable, enable);
  9292. };
  9293. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9294. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9295. };
  9296. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9297. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9298. if (this._alphaMode === mode) {
  9299. return;
  9300. }
  9301. switch (mode) {
  9302. case Engine.ALPHA_DISABLE:
  9303. this._alphaState.alphaBlend = false;
  9304. break;
  9305. case Engine.ALPHA_PREMULTIPLIED:
  9306. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9307. this._alphaState.alphaBlend = true;
  9308. break;
  9309. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9310. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9311. this._alphaState.alphaBlend = true;
  9312. break;
  9313. case Engine.ALPHA_COMBINE:
  9314. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9315. this._alphaState.alphaBlend = true;
  9316. break;
  9317. case Engine.ALPHA_ONEONE:
  9318. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9319. this._alphaState.alphaBlend = true;
  9320. break;
  9321. case Engine.ALPHA_ADD:
  9322. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9323. this._alphaState.alphaBlend = true;
  9324. break;
  9325. case Engine.ALPHA_SUBTRACT:
  9326. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9327. this._alphaState.alphaBlend = true;
  9328. break;
  9329. case Engine.ALPHA_MULTIPLY:
  9330. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9331. this._alphaState.alphaBlend = true;
  9332. break;
  9333. case Engine.ALPHA_MAXIMIZED:
  9334. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9335. this._alphaState.alphaBlend = true;
  9336. break;
  9337. case Engine.ALPHA_INTERPOLATE:
  9338. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9339. this._alphaState.alphaBlend = true;
  9340. break;
  9341. case Engine.ALPHA_SCREENMODE:
  9342. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9343. this._alphaState.alphaBlend = true;
  9344. break;
  9345. }
  9346. if (!noDepthWriteChange) {
  9347. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9348. }
  9349. this._alphaMode = mode;
  9350. };
  9351. Engine.prototype.getAlphaMode = function () {
  9352. return this._alphaMode;
  9353. };
  9354. Engine.prototype.setAlphaTesting = function (enable) {
  9355. this._alphaTest = enable;
  9356. };
  9357. Engine.prototype.getAlphaTesting = function () {
  9358. return !!this._alphaTest;
  9359. };
  9360. // Textures
  9361. Engine.prototype.wipeCaches = function (bruteForce) {
  9362. if (this.preventCacheWipeBetweenFrames) {
  9363. return;
  9364. }
  9365. this.resetTextureCache();
  9366. this._currentEffect = null;
  9367. // 6/8/2017: deltakosh: Should not be required anymore.
  9368. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9369. if (bruteForce) {
  9370. this._currentProgram = null;
  9371. this._stencilState.reset();
  9372. this._depthCullingState.reset();
  9373. this.setDepthFunctionToLessOrEqual();
  9374. this._alphaState.reset();
  9375. }
  9376. this._cachedVertexBuffers = null;
  9377. this._cachedIndexBuffer = null;
  9378. this._cachedEffectForVertexBuffers = null;
  9379. this._unbindVertexArrayObject();
  9380. this.bindIndexBuffer(null);
  9381. this.bindArrayBuffer(null);
  9382. };
  9383. /**
  9384. * Set the compressed texture format to use, based on the formats you have, and the formats
  9385. * supported by the hardware / browser.
  9386. *
  9387. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9388. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9389. * to API arguments needed to compressed textures. This puts the burden on the container
  9390. * generator to house the arcane code for determining these for current & future formats.
  9391. *
  9392. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9393. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9394. *
  9395. * Note: The result of this call is not taken into account when a texture is base64.
  9396. *
  9397. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9398. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9399. *
  9400. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9401. * @returns The extension selected.
  9402. */
  9403. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9404. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9405. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9406. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9407. return this._textureFormatInUse = this._texturesSupported[i];
  9408. }
  9409. }
  9410. }
  9411. // actively set format to nothing, to allow this to be called more than once
  9412. // and possibly fail the 2nd time
  9413. return this._textureFormatInUse = null;
  9414. };
  9415. /**
  9416. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9417. * @param {string} urlArg- This contains one of the following:
  9418. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9419. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9420. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9421. *
  9422. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9423. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9424. * @param {Scene} scene- Needed for loading to the correct scene.
  9425. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9426. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9427. * @param {callback} onError- Optional callback to be called upon failure.
  9428. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9429. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9430. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9431. *
  9432. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9433. */
  9434. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9435. var _this = this;
  9436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9437. if (onLoad === void 0) { onLoad = null; }
  9438. if (onError === void 0) { onError = null; }
  9439. if (buffer === void 0) { buffer = null; }
  9440. var texture = fallBack ? fallBack : this._gl.createTexture();
  9441. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9442. var fromData = url.substr(0, 5) === "data:";
  9443. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9444. // establish the file extension, if possible
  9445. var lastDot = url.lastIndexOf('.');
  9446. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9447. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9448. var isTGA = (extension === ".tga");
  9449. // determine if a ktx file should be substituted
  9450. var isKTX = false;
  9451. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9452. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9453. isKTX = true;
  9454. }
  9455. scene._addPendingData(texture);
  9456. texture.url = url;
  9457. texture.generateMipMaps = !noMipmap;
  9458. texture.references = 1;
  9459. texture.samplingMode = samplingMode;
  9460. texture.onLoadedCallbacks = [];
  9461. if (onLoad) {
  9462. texture.onLoadedCallbacks.push(onLoad);
  9463. }
  9464. if (!fallBack)
  9465. this._loadedTexturesCache.push(texture);
  9466. var onerror = function () {
  9467. scene._removePendingData(texture);
  9468. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9469. if (isKTX) {
  9470. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9471. }
  9472. else if (onError) {
  9473. onError();
  9474. }
  9475. };
  9476. var callback;
  9477. // processing for non-image formats
  9478. if (isKTX || isTGA || isDDS) {
  9479. if (isKTX) {
  9480. callback = function (data) {
  9481. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9482. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9483. ktx.uploadLevels(_this._gl, !noMipmap);
  9484. return false;
  9485. }, samplingMode);
  9486. };
  9487. }
  9488. else if (isTGA) {
  9489. callback = function (arrayBuffer) {
  9490. var data = new Uint8Array(arrayBuffer);
  9491. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9492. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9493. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9494. return false;
  9495. }, samplingMode);
  9496. };
  9497. }
  9498. else if (isDDS) {
  9499. callback = function (data) {
  9500. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9501. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9502. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9503. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 1);
  9504. return false;
  9505. }, samplingMode);
  9506. };
  9507. }
  9508. if (!buffer) {
  9509. BABYLON.Tools.LoadFile(url, function (data) {
  9510. callback(data);
  9511. }, null, scene.database, true, onerror);
  9512. }
  9513. else {
  9514. callback(buffer);
  9515. }
  9516. // image format processing
  9517. }
  9518. else {
  9519. var onload = function (img) {
  9520. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9521. var gl = _this._gl;
  9522. var isPot = (img.width === potWidth && img.height === potHeight);
  9523. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9524. if (isPot) {
  9525. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9526. return false;
  9527. }
  9528. // Using shaders to rescale because canvas.drawImage is lossy
  9529. var source = gl.createTexture();
  9530. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9531. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9533. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9534. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9535. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9536. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9537. _this._releaseTexture(source);
  9538. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9539. continuationCallback();
  9540. });
  9541. return true;
  9542. }, samplingMode);
  9543. };
  9544. if (!fromData || isBase64)
  9545. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9546. else if (buffer instanceof Array || typeof buffer === "string")
  9547. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9548. else
  9549. onload(buffer);
  9550. }
  9551. return texture;
  9552. };
  9553. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9554. var _this = this;
  9555. var rtt = this.createRenderTargetTexture({
  9556. width: destination._width,
  9557. height: destination._height,
  9558. }, {
  9559. generateMipMaps: false,
  9560. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9561. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9562. generateDepthBuffer: false,
  9563. generateStencilBuffer: false
  9564. });
  9565. if (!this._rescalePostProcess) {
  9566. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9567. }
  9568. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9569. _this._rescalePostProcess.onApply = function (effect) {
  9570. effect._bindTexture("textureSampler", source);
  9571. };
  9572. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9573. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9574. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination._width, destination._height, 0);
  9575. _this.unBindFramebuffer(rtt);
  9576. _this._releaseTexture(rtt);
  9577. if (onComplete) {
  9578. onComplete();
  9579. }
  9580. });
  9581. };
  9582. Engine.prototype._getInternalFormat = function (format) {
  9583. var internalFormat = this._gl.RGBA;
  9584. switch (format) {
  9585. case Engine.TEXTUREFORMAT_ALPHA:
  9586. internalFormat = this._gl.ALPHA;
  9587. break;
  9588. case Engine.TEXTUREFORMAT_LUMINANCE:
  9589. internalFormat = this._gl.LUMINANCE;
  9590. break;
  9591. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9592. internalFormat = this._gl.LUMINANCE_ALPHA;
  9593. break;
  9594. case Engine.TEXTUREFORMAT_RGB:
  9595. internalFormat = this._gl.RGB;
  9596. break;
  9597. case Engine.TEXTUREFORMAT_RGBA:
  9598. internalFormat = this._gl.RGBA;
  9599. break;
  9600. }
  9601. return internalFormat;
  9602. };
  9603. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9604. if (compression === void 0) { compression = null; }
  9605. var internalFormat = this._getInternalFormat(format);
  9606. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9607. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9608. if (texture._width % 4 !== 0) {
  9609. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9610. }
  9611. if (compression) {
  9612. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9613. }
  9614. else {
  9615. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9616. }
  9617. if (texture.generateMipMaps) {
  9618. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9619. }
  9620. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9621. this.resetTextureCache();
  9622. texture.isReady = true;
  9623. };
  9624. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9625. if (compression === void 0) { compression = null; }
  9626. var texture = this._gl.createTexture();
  9627. texture._baseWidth = width;
  9628. texture._baseHeight = height;
  9629. texture._width = width;
  9630. texture._height = height;
  9631. texture.references = 1;
  9632. this.updateRawTexture(texture, data, format, invertY, compression);
  9633. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9634. // Filters
  9635. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9636. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9637. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9638. if (generateMipMaps) {
  9639. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9640. }
  9641. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9642. texture.samplingMode = samplingMode;
  9643. this._loadedTexturesCache.push(texture);
  9644. return texture;
  9645. };
  9646. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9647. var texture = this._gl.createTexture();
  9648. texture._baseWidth = width;
  9649. texture._baseHeight = height;
  9650. if (generateMipMaps) {
  9651. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9652. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9653. }
  9654. this.resetTextureCache();
  9655. texture._width = width;
  9656. texture._height = height;
  9657. texture.isReady = false;
  9658. texture.generateMipMaps = generateMipMaps;
  9659. texture.references = 1;
  9660. texture.samplingMode = samplingMode;
  9661. this.updateTextureSamplingMode(samplingMode, texture);
  9662. this._loadedTexturesCache.push(texture);
  9663. return texture;
  9664. };
  9665. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9666. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9667. if (texture.isCube) {
  9668. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9669. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9670. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9671. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9672. }
  9673. else {
  9674. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9675. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9676. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9677. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9678. }
  9679. texture.samplingMode = samplingMode;
  9680. };
  9681. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9682. if (premulAlpha === void 0) { premulAlpha = false; }
  9683. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9684. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9685. if (premulAlpha) {
  9686. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9687. }
  9688. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9689. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9690. if (texture.generateMipMaps) {
  9691. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9692. }
  9693. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9694. if (premulAlpha) {
  9695. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9696. }
  9697. this.resetTextureCache();
  9698. texture.isReady = true;
  9699. };
  9700. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9701. if (texture._isDisabled) {
  9702. return;
  9703. }
  9704. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9705. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9706. try {
  9707. // Testing video texture support
  9708. if (this._videoTextureSupported === undefined) {
  9709. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9710. if (this._gl.getError() !== 0) {
  9711. this._videoTextureSupported = false;
  9712. }
  9713. else {
  9714. this._videoTextureSupported = true;
  9715. }
  9716. }
  9717. // Copy video through the current working canvas if video texture is not supported
  9718. if (!this._videoTextureSupported) {
  9719. if (!texture._workingCanvas) {
  9720. texture._workingCanvas = document.createElement("canvas");
  9721. texture._workingContext = texture._workingCanvas.getContext("2d");
  9722. texture._workingCanvas.width = texture._width;
  9723. texture._workingCanvas.height = texture._height;
  9724. }
  9725. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9726. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9727. }
  9728. else {
  9729. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9730. }
  9731. if (texture.generateMipMaps) {
  9732. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9733. }
  9734. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9735. this.resetTextureCache();
  9736. texture.isReady = true;
  9737. }
  9738. catch (ex) {
  9739. // Something unexpected
  9740. // Let's disable the texture
  9741. texture._isDisabled = true;
  9742. }
  9743. };
  9744. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9745. // old version had a "generateMipMaps" arg instead of options.
  9746. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9747. // in the same way, generateDepthBuffer is defaulted to true
  9748. var generateMipMaps = false;
  9749. var generateDepthBuffer = true;
  9750. var generateStencilBuffer = false;
  9751. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9752. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9753. if (options !== undefined) {
  9754. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9755. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9756. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9757. type = options.type === undefined ? type : options.type;
  9758. if (options.samplingMode !== undefined) {
  9759. samplingMode = options.samplingMode;
  9760. }
  9761. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9762. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9763. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9764. }
  9765. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9766. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9767. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9768. }
  9769. }
  9770. var gl = this._gl;
  9771. var texture = gl.createTexture();
  9772. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9773. var width = size.width || size;
  9774. var height = size.height || size;
  9775. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9776. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9777. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9778. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9779. }
  9780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9783. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9784. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9785. // Create the framebuffer
  9786. var framebuffer = gl.createFramebuffer();
  9787. this.bindUnboundFramebuffer(framebuffer);
  9788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9789. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9790. if (generateMipMaps) {
  9791. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9792. }
  9793. // Unbind
  9794. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9795. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9796. this.bindUnboundFramebuffer(null);
  9797. texture._framebuffer = framebuffer;
  9798. texture._baseWidth = width;
  9799. texture._baseHeight = height;
  9800. texture._width = width;
  9801. texture._height = height;
  9802. texture.isReady = true;
  9803. texture.samples = 1;
  9804. texture.generateMipMaps = generateMipMaps;
  9805. texture.references = 1;
  9806. texture.samplingMode = samplingMode;
  9807. texture.type = type;
  9808. texture._generateDepthBuffer = generateDepthBuffer;
  9809. texture._generateStencilBuffer = generateStencilBuffer;
  9810. this.resetTextureCache();
  9811. this._loadedTexturesCache.push(texture);
  9812. return texture;
  9813. };
  9814. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9815. var generateMipMaps = false;
  9816. var generateDepthBuffer = true;
  9817. var generateStencilBuffer = false;
  9818. var generateDepthTexture = false;
  9819. var textureCount = 1;
  9820. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9821. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9822. var types = [], samplingModes = [];
  9823. if (options !== undefined) {
  9824. generateMipMaps = options.generateMipMaps;
  9825. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9826. generateStencilBuffer = options.generateStencilBuffer;
  9827. generateDepthTexture = options.generateDepthTexture;
  9828. textureCount = options.textureCount || 1;
  9829. if (options.types) {
  9830. types = options.types;
  9831. }
  9832. if (options.samplingModes) {
  9833. samplingModes = options.samplingModes;
  9834. }
  9835. }
  9836. var gl = this._gl;
  9837. // Create the framebuffer
  9838. var framebuffer = gl.createFramebuffer();
  9839. this.bindUnboundFramebuffer(framebuffer);
  9840. var width = size.width || size;
  9841. var height = size.height || size;
  9842. var textures = [];
  9843. var attachments = [];
  9844. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9845. for (var i = 0; i < textureCount; i++) {
  9846. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9847. var type = types[i] || defaultType;
  9848. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9849. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9850. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9851. }
  9852. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9853. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9854. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9855. }
  9856. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9857. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9858. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9859. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9860. }
  9861. var texture = gl.createTexture();
  9862. var attachment = gl["COLOR_ATTACHMENT" + i];
  9863. textures.push(texture);
  9864. attachments.push(attachment);
  9865. gl.activeTexture(gl["TEXTURE" + i]);
  9866. gl.bindTexture(gl.TEXTURE_2D, texture);
  9867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9871. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9872. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9873. if (generateMipMaps) {
  9874. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9875. }
  9876. // Unbind
  9877. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9878. texture._framebuffer = framebuffer;
  9879. texture._depthStencilBuffer = depthStencilBuffer;
  9880. texture._baseWidth = width;
  9881. texture._baseHeight = height;
  9882. texture._width = width;
  9883. texture._height = height;
  9884. texture.isReady = true;
  9885. texture.samples = 1;
  9886. texture.generateMipMaps = generateMipMaps;
  9887. texture.references = 1;
  9888. texture.samplingMode = samplingMode;
  9889. texture.type = type;
  9890. texture._generateDepthBuffer = generateDepthBuffer;
  9891. texture._generateStencilBuffer = generateStencilBuffer;
  9892. this._loadedTexturesCache.push(texture);
  9893. }
  9894. if (generateDepthTexture) {
  9895. // Depth texture
  9896. var depthTexture = gl.createTexture();
  9897. gl.activeTexture(gl.TEXTURE0);
  9898. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9902. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9903. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9904. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9905. depthTexture._framebuffer = framebuffer;
  9906. depthTexture._baseWidth = width;
  9907. depthTexture._baseHeight = height;
  9908. depthTexture._width = width;
  9909. depthTexture._height = height;
  9910. depthTexture.isReady = true;
  9911. depthTexture.samples = 1;
  9912. depthTexture.generateMipMaps = generateMipMaps;
  9913. depthTexture.references = 1;
  9914. depthTexture.samplingMode = gl.NEAREST;
  9915. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9916. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9917. textures.push(depthTexture);
  9918. this._loadedTexturesCache.push(depthTexture);
  9919. }
  9920. gl.drawBuffers(attachments);
  9921. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9922. this.bindUnboundFramebuffer(null);
  9923. this.resetTextureCache();
  9924. return textures;
  9925. };
  9926. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9927. if (samples === void 0) { samples = 1; }
  9928. var depthStencilBuffer = null;
  9929. var gl = this._gl;
  9930. // Create the depth/stencil buffer
  9931. if (generateStencilBuffer) {
  9932. depthStencilBuffer = gl.createRenderbuffer();
  9933. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9934. if (samples > 1) {
  9935. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  9936. }
  9937. else {
  9938. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9939. }
  9940. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9941. }
  9942. else if (generateDepthBuffer) {
  9943. depthStencilBuffer = gl.createRenderbuffer();
  9944. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9945. if (samples > 1) {
  9946. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9947. }
  9948. else {
  9949. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9950. }
  9951. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9952. }
  9953. return depthStencilBuffer;
  9954. };
  9955. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9956. if (this.webGLVersion < 2) {
  9957. return 1;
  9958. }
  9959. if (texture.samples === samples) {
  9960. return samples;
  9961. }
  9962. var gl = this._gl;
  9963. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9964. // Dispose previous render buffers
  9965. if (texture._depthStencilBuffer) {
  9966. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9967. }
  9968. if (texture._MSAAFramebuffer) {
  9969. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9970. }
  9971. if (texture._MSAARenderBuffer) {
  9972. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9973. }
  9974. if (samples > 1) {
  9975. texture._MSAAFramebuffer = gl.createFramebuffer();
  9976. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9977. var colorRenderbuffer = gl.createRenderbuffer();
  9978. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9979. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9980. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9981. texture._MSAARenderBuffer = colorRenderbuffer;
  9982. }
  9983. else {
  9984. this.bindUnboundFramebuffer(texture._framebuffer);
  9985. }
  9986. texture.samples = samples;
  9987. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9988. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9989. this.bindUnboundFramebuffer(null);
  9990. return samples;
  9991. };
  9992. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  9993. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  9994. };
  9995. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  9996. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  9997. };
  9998. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9999. var gl = this._gl;
  10000. var texture = gl.createTexture();
  10001. var generateMipMaps = true;
  10002. var generateDepthBuffer = true;
  10003. var generateStencilBuffer = false;
  10004. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10005. if (options !== undefined) {
  10006. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  10007. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10008. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10009. if (options.samplingMode !== undefined) {
  10010. samplingMode = options.samplingMode;
  10011. }
  10012. }
  10013. texture.isCube = true;
  10014. texture.references = 1;
  10015. texture.generateMipMaps = generateMipMaps;
  10016. texture.references = 1;
  10017. texture.samples = 1;
  10018. texture.samplingMode = samplingMode;
  10019. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10020. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10021. for (var face = 0; face < 6; face++) {
  10022. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10023. }
  10024. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10025. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10026. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10027. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10028. // Create the framebuffer
  10029. var framebuffer = gl.createFramebuffer();
  10030. this.bindUnboundFramebuffer(framebuffer);
  10031. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10032. // Mipmaps
  10033. if (texture.generateMipMaps) {
  10034. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10035. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10036. }
  10037. // Unbind
  10038. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10039. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10040. this.bindUnboundFramebuffer(null);
  10041. texture._framebuffer = framebuffer;
  10042. texture._width = size;
  10043. texture._height = size;
  10044. texture.isReady = true;
  10045. this.resetTextureCache();
  10046. this._loadedTexturesCache.push(texture);
  10047. return texture;
  10048. };
  10049. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10050. var _this = this;
  10051. if (onError === void 0) { onError = null; }
  10052. if (forcedExtension === void 0) { forcedExtension = null; }
  10053. var callback = function (loadData) {
  10054. if (_this._caps.textureLOD || !loadData) {
  10055. // Do not add extra process if texture lod is supported.
  10056. if (onLoad) {
  10057. onLoad();
  10058. }
  10059. return;
  10060. }
  10061. var mipSlices = 3;
  10062. var gl = _this._gl;
  10063. var width = loadData.width;
  10064. if (!width) {
  10065. return;
  10066. }
  10067. var textures = [];
  10068. for (var i = 0; i < mipSlices; i++) {
  10069. //compute LOD from even spacing in smoothness (matching shader calculation)
  10070. var smoothness = i / (mipSlices - 1);
  10071. var roughness = 1 - smoothness;
  10072. var minLODIndex = offset; // roughness = 0
  10073. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10074. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10075. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10076. var glTextureFromLod = gl.createTexture();
  10077. glTextureFromLod.isCube = true;
  10078. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10080. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10081. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10083. if (loadData.isDDS) {
  10084. var info = loadData.info;
  10085. var data = loadData.data;
  10086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10087. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, true, 6, mipmapIndex);
  10088. }
  10089. else {
  10090. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10091. }
  10092. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10093. // Wrap in a base texture for easy binding.
  10094. var lodTexture = new BABYLON.BaseTexture(scene);
  10095. lodTexture.isCube = true;
  10096. lodTexture._texture = glTextureFromLod;
  10097. glTextureFromLod.isReady = true;
  10098. textures.push(lodTexture);
  10099. }
  10100. loadData.texture._lodTextureHigh = textures[2];
  10101. loadData.texture._lodTextureMid = textures[1];
  10102. loadData.texture._lodTextureLow = textures[0];
  10103. if (onLoad) {
  10104. onLoad();
  10105. }
  10106. };
  10107. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10108. };
  10109. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10110. var _this = this;
  10111. if (onLoad === void 0) { onLoad = null; }
  10112. if (onError === void 0) { onError = null; }
  10113. if (forcedExtension === void 0) { forcedExtension = null; }
  10114. var gl = this._gl;
  10115. var texture = gl.createTexture();
  10116. texture.isCube = true;
  10117. texture.url = rootUrl;
  10118. texture.references = 1;
  10119. texture.onLoadedCallbacks = [];
  10120. texture.generateMipMaps = !noMipmap;
  10121. var isKTX = false;
  10122. var isDDS = false;
  10123. var lastDot = rootUrl.lastIndexOf('.');
  10124. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10125. if (this._textureFormatInUse) {
  10126. extension = this._textureFormatInUse;
  10127. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10128. isKTX = true;
  10129. }
  10130. else {
  10131. isDDS = (extension === ".dds");
  10132. }
  10133. if (isKTX) {
  10134. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10135. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10136. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10137. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10138. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10139. ktx.uploadLevels(_this._gl, !noMipmap);
  10140. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10141. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10142. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10143. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10144. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10145. _this.resetTextureCache();
  10146. texture._width = ktx.pixelWidth;
  10147. texture._height = ktx.pixelHeight;
  10148. texture.isReady = true;
  10149. }, null, null, true, onError);
  10150. }
  10151. else if (isDDS) {
  10152. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10153. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10154. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10155. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10156. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10157. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  10158. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10159. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10160. }
  10161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10163. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10165. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10166. _this.resetTextureCache();
  10167. texture._width = info.width;
  10168. texture._height = info.height;
  10169. texture.isReady = true;
  10170. texture.type = info.textureType;
  10171. if (onLoad) {
  10172. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10173. }
  10174. }, null, null, true, onError);
  10175. }
  10176. else {
  10177. cascadeLoad(rootUrl, scene, function (imgs) {
  10178. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10179. var height = width;
  10180. _this._prepareWorkingCanvas();
  10181. _this._workingCanvas.width = width;
  10182. _this._workingCanvas.height = height;
  10183. var faces = [
  10184. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10185. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10186. ];
  10187. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10188. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10189. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10190. for (var index = 0; index < faces.length; index++) {
  10191. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10192. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10193. }
  10194. if (!noMipmap) {
  10195. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10196. }
  10197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10198. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10199. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10200. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10201. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10202. _this.resetTextureCache();
  10203. texture._width = width;
  10204. texture._height = height;
  10205. texture.isReady = true;
  10206. texture.onLoadedCallbacks.forEach(function (callback) {
  10207. callback();
  10208. });
  10209. if (onLoad) {
  10210. onLoad();
  10211. }
  10212. }, files, onError);
  10213. }
  10214. this._loadedTexturesCache.push(texture);
  10215. return texture;
  10216. };
  10217. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10218. texture._width = width;
  10219. texture._height = height;
  10220. texture._size = width * height;
  10221. texture._baseWidth = width;
  10222. texture._baseHeight = height;
  10223. };
  10224. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10225. if (compression === void 0) { compression = null; }
  10226. if (level === void 0) { level = 0; }
  10227. var gl = this._gl;
  10228. var textureType = this._getWebGLTextureType(type);
  10229. var internalFormat = this._getInternalFormat(format);
  10230. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10231. var needConversion = false;
  10232. if (internalFormat === gl.RGB) {
  10233. internalFormat = gl.RGBA;
  10234. needConversion = true;
  10235. }
  10236. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10237. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10238. if (texture._width % 4 !== 0) {
  10239. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10240. }
  10241. // Data are known to be in +X +Y +Z -X -Y -Z
  10242. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10243. var faceData = data[faceIndex];
  10244. if (compression) {
  10245. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  10246. }
  10247. else {
  10248. if (needConversion) {
  10249. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  10250. }
  10251. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  10252. }
  10253. }
  10254. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10255. if (isPot && texture.generateMipMaps && level === 0) {
  10256. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10257. }
  10258. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10259. this.resetTextureCache();
  10260. texture.isReady = true;
  10261. };
  10262. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10263. if (compression === void 0) { compression = null; }
  10264. var gl = this._gl;
  10265. var texture = gl.createTexture();
  10266. texture.isCube = true;
  10267. texture.references = 1;
  10268. texture.generateMipMaps = generateMipMaps;
  10269. texture.format = format;
  10270. texture.type = type;
  10271. var textureType = this._getWebGLTextureType(type);
  10272. var internalFormat = this._getInternalFormat(format);
  10273. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10274. var needConversion = false;
  10275. if (internalFormat === gl.RGB) {
  10276. internalFormat = gl.RGBA;
  10277. needConversion = true;
  10278. }
  10279. var width = size;
  10280. var height = width;
  10281. texture._width = width;
  10282. texture._height = height;
  10283. // Double check on POT to generate Mips.
  10284. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  10285. if (!isPot) {
  10286. generateMipMaps = false;
  10287. }
  10288. // Upload data if needed. The texture won t be ready until then.
  10289. if (data) {
  10290. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10291. }
  10292. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10293. // Filters
  10294. if (data && generateMipMaps) {
  10295. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10296. }
  10297. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10300. }
  10301. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10302. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10303. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10304. }
  10305. else {
  10306. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10307. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10308. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10309. }
  10310. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10312. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10313. return texture;
  10314. };
  10315. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10316. var _this = this;
  10317. if (onLoad === void 0) { onLoad = null; }
  10318. if (onError === void 0) { onError = null; }
  10319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10320. if (invertY === void 0) { invertY = false; }
  10321. var gl = this._gl;
  10322. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10323. scene._addPendingData(texture);
  10324. texture.url = url;
  10325. this._loadedTexturesCache.push(texture);
  10326. var onerror = function () {
  10327. scene._removePendingData(texture);
  10328. if (onError) {
  10329. onError();
  10330. }
  10331. };
  10332. var internalCallback = function (data) {
  10333. var width = texture._width;
  10334. var height = texture._height;
  10335. var faceDataArrays = callback(data);
  10336. if (mipmmapGenerator) {
  10337. var textureType = _this._getWebGLTextureType(type);
  10338. var internalFormat = _this._getInternalFormat(format);
  10339. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10340. var needConversion = false;
  10341. if (internalFormat === gl.RGB) {
  10342. internalFormat = gl.RGBA;
  10343. needConversion = true;
  10344. }
  10345. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10346. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10347. var mipData = mipmmapGenerator(faceDataArrays);
  10348. for (var level = 0; level < mipData.length; level++) {
  10349. var mipSize = width >> level;
  10350. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10351. var mipFaceData = mipData[level][faceIndex];
  10352. if (needConversion) {
  10353. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10354. }
  10355. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10356. }
  10357. }
  10358. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10359. }
  10360. else {
  10361. texture.generateMipMaps = !noMipmap;
  10362. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10363. }
  10364. texture.isReady = true;
  10365. _this.resetTextureCache();
  10366. scene._removePendingData(texture);
  10367. if (onLoad) {
  10368. onLoad();
  10369. }
  10370. };
  10371. BABYLON.Tools.LoadFile(url, function (data) {
  10372. internalCallback(data);
  10373. }, onerror, scene.database, true);
  10374. return texture;
  10375. };
  10376. ;
  10377. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10378. var gl = this._gl;
  10379. if (!gl) {
  10380. return;
  10381. }
  10382. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10383. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10384. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10385. if (!noMipmap && !isCompressed) {
  10386. gl.generateMipmap(gl.TEXTURE_2D);
  10387. }
  10388. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10389. this.resetTextureCache();
  10390. scene._removePendingData(texture);
  10391. texture.onLoadedCallbacks.forEach(function (callback) {
  10392. callback();
  10393. });
  10394. texture.onLoadedCallbacks = [];
  10395. };
  10396. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10397. var _this = this;
  10398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10399. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10400. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10401. var gl = this._gl;
  10402. if (!gl) {
  10403. return;
  10404. }
  10405. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10406. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10407. texture._baseWidth = width;
  10408. texture._baseHeight = height;
  10409. texture._width = potWidth;
  10410. texture._height = potHeight;
  10411. texture.isReady = true;
  10412. if (processFunction(potWidth, potHeight, function () {
  10413. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10414. })) {
  10415. // Returning as texture needs extra async steps
  10416. return;
  10417. }
  10418. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10419. };
  10420. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10421. // Create new RGBA data container.
  10422. var rgbaData;
  10423. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10424. rgbaData = new Float32Array(width * height * 4);
  10425. }
  10426. else {
  10427. rgbaData = new Uint32Array(width * height * 4);
  10428. }
  10429. // Convert each pixel.
  10430. for (var x = 0; x < width; x++) {
  10431. for (var y = 0; y < height; y++) {
  10432. var index = (y * width + x) * 3;
  10433. var newIndex = (y * width + x) * 4;
  10434. // Map Old Value to new value.
  10435. rgbaData[newIndex + 0] = rgbData[index + 0];
  10436. rgbaData[newIndex + 1] = rgbData[index + 1];
  10437. rgbaData[newIndex + 2] = rgbData[index + 2];
  10438. // Add fully opaque alpha channel.
  10439. rgbaData[newIndex + 3] = 1;
  10440. }
  10441. }
  10442. return rgbaData;
  10443. };
  10444. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10445. var gl = this._gl;
  10446. if (texture._framebuffer) {
  10447. gl.deleteFramebuffer(texture._framebuffer);
  10448. texture._framebuffer = null;
  10449. }
  10450. if (texture._depthStencilBuffer) {
  10451. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10452. texture._depthStencilBuffer = null;
  10453. }
  10454. if (texture._MSAAFramebuffer) {
  10455. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10456. texture._MSAAFramebuffer = null;
  10457. }
  10458. if (texture._MSAARenderBuffer) {
  10459. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10460. texture._MSAARenderBuffer = null;
  10461. }
  10462. };
  10463. Engine.prototype._releaseTexture = function (texture) {
  10464. var gl = this._gl;
  10465. this._releaseFramebufferObjects(texture);
  10466. gl.deleteTexture(texture);
  10467. // Unbind channels
  10468. this.unbindAllTextures();
  10469. var index = this._loadedTexturesCache.indexOf(texture);
  10470. if (index !== -1) {
  10471. this._loadedTexturesCache.splice(index, 1);
  10472. }
  10473. // Integrated fixed lod samplers.
  10474. if (texture._lodTextureHigh) {
  10475. texture._lodTextureHigh.dispose();
  10476. }
  10477. if (texture._lodTextureMid) {
  10478. texture._lodTextureMid.dispose();
  10479. }
  10480. if (texture._lodTextureLow) {
  10481. texture._lodTextureLow.dispose();
  10482. }
  10483. };
  10484. Engine.prototype.setProgram = function (program) {
  10485. if (this._currentProgram !== program) {
  10486. this._gl.useProgram(program);
  10487. this._currentProgram = program;
  10488. }
  10489. };
  10490. Engine.prototype.bindSamplers = function (effect) {
  10491. this.setProgram(effect.getProgram());
  10492. var samplers = effect.getSamplers();
  10493. for (var index = 0; index < samplers.length; index++) {
  10494. var uniform = effect.getUniform(samplers[index]);
  10495. this._gl.uniform1i(uniform, index);
  10496. }
  10497. this._currentEffect = null;
  10498. };
  10499. Engine.prototype.activateTexture = function (texture) {
  10500. if (this._activeTexture !== texture) {
  10501. this._gl.activeTexture(texture);
  10502. this._activeTexture = texture;
  10503. }
  10504. };
  10505. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10506. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10507. this._gl.bindTexture(target, texture);
  10508. this._activeTexturesCache[this._activeTexture] = texture;
  10509. }
  10510. };
  10511. Engine.prototype._bindTexture = function (channel, texture) {
  10512. if (channel < 0) {
  10513. return;
  10514. }
  10515. this.activateTexture(this._gl.TEXTURE0 + channel);
  10516. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10517. };
  10518. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10519. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10520. };
  10521. Engine.prototype.unbindAllTextures = function () {
  10522. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10523. this.activateTexture(this._gl["TEXTURE" + channel]);
  10524. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10525. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10526. }
  10527. };
  10528. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10529. if (channel < 0) {
  10530. return;
  10531. }
  10532. this._gl.uniform1i(uniform, channel);
  10533. this._setTexture(channel, texture);
  10534. };
  10535. Engine.prototype._setTexture = function (channel, texture) {
  10536. // Not ready?
  10537. if (!texture) {
  10538. if (this._activeTexturesCache[channel] != null) {
  10539. this.activateTexture(this._gl["TEXTURE" + channel]);
  10540. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10541. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10542. }
  10543. return;
  10544. }
  10545. // Video
  10546. var alreadyActivated = false;
  10547. if (texture.video) {
  10548. this.activateTexture(this._gl["TEXTURE" + channel]);
  10549. alreadyActivated = true;
  10550. texture.update();
  10551. }
  10552. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10553. texture.delayLoad();
  10554. return;
  10555. }
  10556. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10557. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10558. if (this._activeTexturesCache[channel] === internalTexture) {
  10559. return;
  10560. }
  10561. if (!alreadyActivated) {
  10562. this.activateTexture(this._gl["TEXTURE" + channel]);
  10563. }
  10564. if (internalTexture.isCube) {
  10565. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10566. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10567. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10568. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10569. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10570. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10571. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10572. }
  10573. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10574. }
  10575. else {
  10576. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10577. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10578. internalTexture._cachedWrapU = texture.wrapU;
  10579. switch (texture.wrapU) {
  10580. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10581. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10582. break;
  10583. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10584. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10585. break;
  10586. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10587. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10588. break;
  10589. }
  10590. }
  10591. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10592. internalTexture._cachedWrapV = texture.wrapV;
  10593. switch (texture.wrapV) {
  10594. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10595. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10596. break;
  10597. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10599. break;
  10600. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10601. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10602. break;
  10603. }
  10604. }
  10605. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10606. }
  10607. };
  10608. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10609. if (channel < 0) {
  10610. return;
  10611. }
  10612. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10613. this._textureUnits = new Int32Array(textures.length);
  10614. }
  10615. for (var i = 0; i < textures.length; i++) {
  10616. this._textureUnits[i] = channel + i;
  10617. }
  10618. this._gl.uniform1iv(uniform, this._textureUnits);
  10619. for (var index = 0; index < textures.length; index++) {
  10620. this._setTexture(channel + index, textures[index]);
  10621. }
  10622. };
  10623. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10624. var internalTexture = texture.getInternalTexture();
  10625. if (!internalTexture) {
  10626. return;
  10627. }
  10628. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10629. var value = texture.anisotropicFilteringLevel;
  10630. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10631. value = 1;
  10632. }
  10633. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10634. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10635. texture._cachedAnisotropicFilteringLevel = value;
  10636. }
  10637. };
  10638. Engine.prototype.readPixels = function (x, y, width, height) {
  10639. var data = new Uint8Array(height * width * 4);
  10640. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10641. return data;
  10642. };
  10643. /**
  10644. * Add an externaly attached data from its key.
  10645. * This method call will fail and return false, if such key already exists.
  10646. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10647. * @param key the unique key that identifies the data
  10648. * @param data the data object to associate to the key for this Engine instance
  10649. * @return true if no such key were already present and the data was added successfully, false otherwise
  10650. */
  10651. Engine.prototype.addExternalData = function (key, data) {
  10652. if (!this._externalData) {
  10653. this._externalData = new BABYLON.StringDictionary();
  10654. }
  10655. return this._externalData.add(key, data);
  10656. };
  10657. /**
  10658. * Get an externaly attached data from its key
  10659. * @param key the unique key that identifies the data
  10660. * @return the associated data, if present (can be null), or undefined if not present
  10661. */
  10662. Engine.prototype.getExternalData = function (key) {
  10663. if (!this._externalData) {
  10664. this._externalData = new BABYLON.StringDictionary();
  10665. }
  10666. return this._externalData.get(key);
  10667. };
  10668. /**
  10669. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10670. * @param key the unique key that identifies the data
  10671. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10672. * @return the associated data, can be null if the factory returned null.
  10673. */
  10674. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10675. if (!this._externalData) {
  10676. this._externalData = new BABYLON.StringDictionary();
  10677. }
  10678. return this._externalData.getOrAddWithFactory(key, factory);
  10679. };
  10680. /**
  10681. * Remove an externaly attached data from the Engine instance
  10682. * @param key the unique key that identifies the data
  10683. * @return true if the data was successfully removed, false if it doesn't exist
  10684. */
  10685. Engine.prototype.removeExternalData = function (key) {
  10686. if (!this._externalData) {
  10687. this._externalData = new BABYLON.StringDictionary();
  10688. }
  10689. return this._externalData.remove(key);
  10690. };
  10691. Engine.prototype.releaseInternalTexture = function (texture) {
  10692. if (!texture) {
  10693. return;
  10694. }
  10695. texture.references--;
  10696. // Final reference ?
  10697. if (texture.references === 0) {
  10698. var texturesCache = this.getLoadedTexturesCache();
  10699. var index = texturesCache.indexOf(texture);
  10700. if (index > -1) {
  10701. texturesCache.splice(index, 1);
  10702. }
  10703. this._releaseTexture(texture);
  10704. }
  10705. };
  10706. Engine.prototype.unbindAllAttributes = function () {
  10707. if (this._mustWipeVertexAttributes) {
  10708. this._mustWipeVertexAttributes = false;
  10709. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10710. this._gl.disableVertexAttribArray(i);
  10711. this._vertexAttribArraysEnabled[i] = false;
  10712. this._currentBufferPointers[i].active = false;
  10713. }
  10714. return;
  10715. }
  10716. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10717. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10718. continue;
  10719. }
  10720. this._gl.disableVertexAttribArray(i);
  10721. this._vertexAttribArraysEnabled[i] = false;
  10722. this._currentBufferPointers[i].active = false;
  10723. }
  10724. };
  10725. Engine.prototype.releaseEffects = function () {
  10726. for (var name in this._compiledEffects) {
  10727. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10728. }
  10729. this._compiledEffects = {};
  10730. };
  10731. // Dispose
  10732. Engine.prototype.dispose = function () {
  10733. this.hideLoadingUI();
  10734. this.stopRenderLoop();
  10735. // Empty texture
  10736. if (this._emptyTexture) {
  10737. this._releaseTexture(this._emptyTexture);
  10738. this._emptyTexture = null;
  10739. }
  10740. if (this._emptyCubeTexture) {
  10741. this._releaseTexture(this._emptyCubeTexture);
  10742. this._emptyCubeTexture = null;
  10743. }
  10744. // Rescale PP
  10745. if (this._rescalePostProcess) {
  10746. this._rescalePostProcess.dispose();
  10747. }
  10748. // Release scenes
  10749. while (this.scenes.length) {
  10750. this.scenes[0].dispose();
  10751. }
  10752. // Release audio engine
  10753. if (Engine.audioEngine) {
  10754. Engine.audioEngine.dispose();
  10755. }
  10756. // Release effects
  10757. this.releaseEffects();
  10758. // Unbind
  10759. this.unbindAllAttributes();
  10760. if (this._dummyFramebuffer) {
  10761. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10762. }
  10763. this._gl = null;
  10764. //WebVR
  10765. this.disableVR();
  10766. // Events
  10767. window.removeEventListener("blur", this._onBlur);
  10768. window.removeEventListener("focus", this._onFocus);
  10769. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10770. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10771. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10772. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10773. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10774. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10775. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10776. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10777. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10778. // Remove from Instances
  10779. var index = Engine.Instances.indexOf(this);
  10780. if (index >= 0) {
  10781. Engine.Instances.splice(index, 1);
  10782. }
  10783. this._workingCanvas = null;
  10784. this._workingContext = null;
  10785. this._currentBufferPointers = null;
  10786. this._renderingCanvas = null;
  10787. this._currentProgram = null;
  10788. this.onResizeObservable.clear();
  10789. this.onCanvasBlurObservable.clear();
  10790. BABYLON.Effect.ResetCache();
  10791. };
  10792. // Loading screen
  10793. Engine.prototype.displayLoadingUI = function () {
  10794. var loadingScreen = this.loadingScreen;
  10795. if (loadingScreen) {
  10796. loadingScreen.displayLoadingUI();
  10797. }
  10798. };
  10799. Engine.prototype.hideLoadingUI = function () {
  10800. var loadingScreen = this.loadingScreen;
  10801. if (loadingScreen) {
  10802. loadingScreen.hideLoadingUI();
  10803. }
  10804. };
  10805. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10806. get: function () {
  10807. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10808. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10809. return this._loadingScreen;
  10810. },
  10811. set: function (loadingScreen) {
  10812. this._loadingScreen = loadingScreen;
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10818. set: function (text) {
  10819. this.loadingScreen.loadingUIText = text;
  10820. },
  10821. enumerable: true,
  10822. configurable: true
  10823. });
  10824. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10825. set: function (color) {
  10826. this.loadingScreen.loadingUIBackgroundColor = color;
  10827. },
  10828. enumerable: true,
  10829. configurable: true
  10830. });
  10831. Engine.prototype.attachContextLostEvent = function (callback) {
  10832. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10833. };
  10834. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10835. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10836. };
  10837. Engine.prototype.getVertexShaderSource = function (program) {
  10838. var shaders = this._gl.getAttachedShaders(program);
  10839. return this._gl.getShaderSource(shaders[0]);
  10840. };
  10841. Engine.prototype.getFragmentShaderSource = function (program) {
  10842. var shaders = this._gl.getAttachedShaders(program);
  10843. return this._gl.getShaderSource(shaders[1]);
  10844. };
  10845. Engine.prototype.getError = function () {
  10846. return this._gl.getError();
  10847. };
  10848. // FPS
  10849. Engine.prototype.getFps = function () {
  10850. return this._fps;
  10851. };
  10852. Engine.prototype.getDeltaTime = function () {
  10853. return this._deltaTime;
  10854. };
  10855. Engine.prototype._measureFps = function () {
  10856. this._performanceMonitor.sampleFrame();
  10857. this._fps = this._performanceMonitor.averageFPS;
  10858. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10859. };
  10860. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10861. if (faceIndex === void 0) { faceIndex = -1; }
  10862. var gl = this._gl;
  10863. if (!this._dummyFramebuffer) {
  10864. this._dummyFramebuffer = gl.createFramebuffer();
  10865. }
  10866. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10867. if (faceIndex > -1) {
  10868. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10869. }
  10870. else {
  10871. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10872. }
  10873. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10874. var buffer;
  10875. switch (readType) {
  10876. case gl.UNSIGNED_BYTE:
  10877. buffer = new Uint8Array(4 * width * height);
  10878. readType = gl.UNSIGNED_BYTE;
  10879. break;
  10880. default:
  10881. buffer = new Float32Array(4 * width * height);
  10882. readType = gl.FLOAT;
  10883. break;
  10884. }
  10885. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10886. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  10887. return buffer;
  10888. };
  10889. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10890. if (this._webGLVersion > 1) {
  10891. return this._caps.colorBufferFloat;
  10892. }
  10893. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10894. };
  10895. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10896. if (this._webGLVersion > 1) {
  10897. return this._caps.colorBufferFloat;
  10898. }
  10899. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10900. };
  10901. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10902. Engine.prototype._canRenderToFramebuffer = function (type) {
  10903. var gl = this._gl;
  10904. //clear existing errors
  10905. while (gl.getError() !== gl.NO_ERROR) { }
  10906. var successful = true;
  10907. var texture = gl.createTexture();
  10908. gl.bindTexture(gl.TEXTURE_2D, texture);
  10909. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10910. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10911. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10912. var fb = gl.createFramebuffer();
  10913. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10914. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10915. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10916. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10917. successful = successful && (gl.getError() === gl.NO_ERROR);
  10918. //try render by clearing frame buffer's color buffer
  10919. if (successful) {
  10920. gl.clear(gl.COLOR_BUFFER_BIT);
  10921. successful = successful && (gl.getError() === gl.NO_ERROR);
  10922. }
  10923. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10924. if (successful) {
  10925. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10926. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10927. var readFormat = gl.RGBA;
  10928. var readType = gl.UNSIGNED_BYTE;
  10929. var buffer = new Uint8Array(4);
  10930. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10931. successful = successful && (gl.getError() === gl.NO_ERROR);
  10932. }
  10933. //clean up
  10934. gl.deleteTexture(texture);
  10935. gl.deleteFramebuffer(fb);
  10936. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10937. //clear accumulated errors
  10938. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10939. return successful;
  10940. };
  10941. Engine.prototype._getWebGLTextureType = function (type) {
  10942. if (type === Engine.TEXTURETYPE_FLOAT) {
  10943. return this._gl.FLOAT;
  10944. }
  10945. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10946. // Add Half Float Constant.
  10947. return this._gl.HALF_FLOAT_OES;
  10948. }
  10949. return this._gl.UNSIGNED_BYTE;
  10950. };
  10951. ;
  10952. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10953. if (this._webGLVersion === 1) {
  10954. return this._gl.RGBA;
  10955. }
  10956. if (type === Engine.TEXTURETYPE_FLOAT) {
  10957. return this._gl.RGBA32F;
  10958. }
  10959. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10960. return this._gl.RGBA16F;
  10961. }
  10962. return this._gl.RGBA;
  10963. };
  10964. ;
  10965. Engine.prototype.createQuery = function () {
  10966. return this._gl.createQuery();
  10967. };
  10968. Engine.prototype.deleteQuery = function (query) {
  10969. this.deleteQuery(query);
  10970. return this;
  10971. };
  10972. Engine.prototype.isQueryResultAvailable = function (query) {
  10973. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  10974. };
  10975. Engine.prototype.getQueryResult = function (query) {
  10976. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  10977. };
  10978. Engine.prototype.beginQuery = function (algorithmType, query) {
  10979. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  10980. this._gl.beginQuery(glAlgorithm, query);
  10981. };
  10982. Engine.prototype.endQuery = function (algorithmType) {
  10983. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  10984. this._gl.endQuery(glAlgorithm);
  10985. return this;
  10986. };
  10987. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  10988. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  10989. };
  10990. // Statics
  10991. Engine.isSupported = function () {
  10992. try {
  10993. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10994. if (navigator.isCocoonJS) {
  10995. return true;
  10996. }
  10997. var tempcanvas = document.createElement("canvas");
  10998. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10999. return gl != null && !!window.WebGLRenderingContext;
  11000. }
  11001. catch (e) {
  11002. return false;
  11003. }
  11004. };
  11005. Engine.Instances = new Array();
  11006. // Const statics
  11007. Engine._ALPHA_DISABLE = 0;
  11008. Engine._ALPHA_ADD = 1;
  11009. Engine._ALPHA_COMBINE = 2;
  11010. Engine._ALPHA_SUBTRACT = 3;
  11011. Engine._ALPHA_MULTIPLY = 4;
  11012. Engine._ALPHA_MAXIMIZED = 5;
  11013. Engine._ALPHA_ONEONE = 6;
  11014. Engine._ALPHA_PREMULTIPLIED = 7;
  11015. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11016. Engine._ALPHA_INTERPOLATE = 9;
  11017. Engine._ALPHA_SCREENMODE = 10;
  11018. Engine._DELAYLOADSTATE_NONE = 0;
  11019. Engine._DELAYLOADSTATE_LOADED = 1;
  11020. Engine._DELAYLOADSTATE_LOADING = 2;
  11021. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11022. Engine._TEXTUREFORMAT_ALPHA = 0;
  11023. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11024. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11025. Engine._TEXTUREFORMAT_RGB = 4;
  11026. Engine._TEXTUREFORMAT_RGBA = 5;
  11027. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11028. Engine._TEXTURETYPE_FLOAT = 1;
  11029. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11030. // Depht or Stencil test Constants.
  11031. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11032. 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.
  11033. 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.
  11034. 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.
  11035. 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.
  11036. 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.
  11037. 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.
  11038. 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.
  11039. // Stencil Actions Constants.
  11040. Engine._KEEP = 0x1E00;
  11041. Engine._REPLACE = 0x1E01;
  11042. Engine._INCR = 0x1E02;
  11043. Engine._DECR = 0x1E03;
  11044. Engine._INVERT = 0x150A;
  11045. Engine._INCR_WRAP = 0x8507;
  11046. Engine._DECR_WRAP = 0x8508;
  11047. // Texture rescaling mode
  11048. Engine._SCALEMODE_FLOOR = 1;
  11049. Engine._SCALEMODE_NEAREST = 2;
  11050. Engine._SCALEMODE_CEILING = 3;
  11051. // Updatable statics so stick with vars here
  11052. Engine.CollisionsEpsilon = 0.001;
  11053. Engine.CodeRepository = "src/";
  11054. Engine.ShadersRepository = "src/Shaders/";
  11055. return Engine;
  11056. }());
  11057. BABYLON.Engine = Engine;
  11058. })(BABYLON || (BABYLON = {}));
  11059. //# sourceMappingURL=babylon.engine.js.map
  11060. /// <reference path="Tools\babylon.decorators.ts" />
  11061. var BABYLON;
  11062. (function (BABYLON) {
  11063. /**
  11064. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11065. */
  11066. var Node = (function () {
  11067. /**
  11068. * @constructor
  11069. * @param {string} name - the name and id to be given to this node
  11070. * @param {BABYLON.Scene} the scene this node will be added to
  11071. */
  11072. function Node(name, scene) {
  11073. this.state = "";
  11074. this.metadata = null;
  11075. this.doNotSerialize = false;
  11076. this.animations = new Array();
  11077. this._ranges = {};
  11078. this._childrenFlag = -1;
  11079. this._isEnabled = true;
  11080. this._isReady = true;
  11081. this._currentRenderId = -1;
  11082. this._parentRenderId = -1;
  11083. /**
  11084. * An event triggered when the mesh is disposed.
  11085. * @type {BABYLON.Observable}
  11086. */
  11087. this.onDisposeObservable = new BABYLON.Observable();
  11088. // Behaviors
  11089. this._behaviors = new Array();
  11090. this.name = name;
  11091. this.id = name;
  11092. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11093. this._initCache();
  11094. }
  11095. Object.defineProperty(Node.prototype, "parent", {
  11096. get: function () {
  11097. return this._parentNode;
  11098. },
  11099. set: function (parent) {
  11100. if (this._parentNode === parent) {
  11101. return;
  11102. }
  11103. if (this._parentNode) {
  11104. var index = this._parentNode._children.indexOf(this);
  11105. if (index !== -1) {
  11106. this._parentNode._children.splice(index, 1);
  11107. }
  11108. }
  11109. this._parentNode = parent;
  11110. if (this._parentNode) {
  11111. if (!this._parentNode._children) {
  11112. this._parentNode._children = new Array();
  11113. }
  11114. this._parentNode._children.push(this);
  11115. }
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Node.prototype.getClassName = function () {
  11121. return "Node";
  11122. };
  11123. Object.defineProperty(Node.prototype, "onDispose", {
  11124. set: function (callback) {
  11125. if (this._onDisposeObserver) {
  11126. this.onDisposeObservable.remove(this._onDisposeObserver);
  11127. }
  11128. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. Node.prototype.getScene = function () {
  11134. return this._scene;
  11135. };
  11136. Node.prototype.getEngine = function () {
  11137. return this._scene.getEngine();
  11138. };
  11139. Node.prototype.addBehavior = function (behavior) {
  11140. var index = this._behaviors.indexOf(behavior);
  11141. if (index !== -1) {
  11142. return;
  11143. }
  11144. behavior.attach(this);
  11145. this._behaviors.push(behavior);
  11146. return this;
  11147. };
  11148. Node.prototype.removeBehavior = function (behavior) {
  11149. var index = this._behaviors.indexOf(behavior);
  11150. if (index === -1) {
  11151. return;
  11152. }
  11153. this._behaviors[index].detach(this);
  11154. this._behaviors.splice(index, 1);
  11155. return this;
  11156. };
  11157. Object.defineProperty(Node.prototype, "behaviors", {
  11158. get: function () {
  11159. return this._behaviors;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Node.prototype.getBehaviorByName = function (name) {
  11165. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11166. var behavior = _a[_i];
  11167. if (behavior.name === name) {
  11168. return behavior;
  11169. }
  11170. }
  11171. return null;
  11172. };
  11173. // override it in derived class
  11174. Node.prototype.getWorldMatrix = function () {
  11175. return BABYLON.Matrix.Identity();
  11176. };
  11177. // override it in derived class if you add new variables to the cache
  11178. // and call the parent class method
  11179. Node.prototype._initCache = function () {
  11180. this._cache = {};
  11181. this._cache.parent = undefined;
  11182. };
  11183. Node.prototype.updateCache = function (force) {
  11184. if (!force && this.isSynchronized())
  11185. return;
  11186. this._cache.parent = this.parent;
  11187. this._updateCache();
  11188. };
  11189. // override it in derived class if you add new variables to the cache
  11190. // and call the parent class method if !ignoreParentClass
  11191. Node.prototype._updateCache = function (ignoreParentClass) {
  11192. };
  11193. // override it in derived class if you add new variables to the cache
  11194. Node.prototype._isSynchronized = function () {
  11195. return true;
  11196. };
  11197. Node.prototype._markSyncedWithParent = function () {
  11198. this._parentRenderId = this.parent._currentRenderId;
  11199. };
  11200. Node.prototype.isSynchronizedWithParent = function () {
  11201. if (!this.parent) {
  11202. return true;
  11203. }
  11204. if (this._parentRenderId !== this.parent._currentRenderId) {
  11205. return false;
  11206. }
  11207. return this.parent.isSynchronized();
  11208. };
  11209. Node.prototype.isSynchronized = function (updateCache) {
  11210. var check = this.hasNewParent();
  11211. check = check || !this.isSynchronizedWithParent();
  11212. check = check || !this._isSynchronized();
  11213. if (updateCache)
  11214. this.updateCache(true);
  11215. return !check;
  11216. };
  11217. Node.prototype.hasNewParent = function (update) {
  11218. if (this._cache.parent === this.parent)
  11219. return false;
  11220. if (update)
  11221. this._cache.parent = this.parent;
  11222. return true;
  11223. };
  11224. /**
  11225. * Is this node ready to be used/rendered
  11226. * @return {boolean} is it ready
  11227. */
  11228. Node.prototype.isReady = function () {
  11229. return this._isReady;
  11230. };
  11231. /**
  11232. * Is this node enabled.
  11233. * If the node has a parent and is enabled, the parent will be inspected as well.
  11234. * @return {boolean} whether this node (and its parent) is enabled.
  11235. * @see setEnabled
  11236. */
  11237. Node.prototype.isEnabled = function () {
  11238. if (!this._isEnabled) {
  11239. return false;
  11240. }
  11241. if (this.parent) {
  11242. return this.parent.isEnabled();
  11243. }
  11244. return true;
  11245. };
  11246. /**
  11247. * Set the enabled state of this node.
  11248. * @param {boolean} value - the new enabled state
  11249. * @see isEnabled
  11250. */
  11251. Node.prototype.setEnabled = function (value) {
  11252. this._isEnabled = value;
  11253. };
  11254. /**
  11255. * Is this node a descendant of the given node.
  11256. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11257. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11258. * @see parent
  11259. */
  11260. Node.prototype.isDescendantOf = function (ancestor) {
  11261. if (this.parent) {
  11262. if (this.parent === ancestor) {
  11263. return true;
  11264. }
  11265. return this.parent.isDescendantOf(ancestor);
  11266. }
  11267. return false;
  11268. };
  11269. /**
  11270. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11271. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11272. * @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.
  11273. * @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.
  11274. */
  11275. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11276. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11277. if (!this._children) {
  11278. return;
  11279. }
  11280. for (var index = 0; index < this._children.length; index++) {
  11281. var item = this._children[index];
  11282. if (!predicate || predicate(item)) {
  11283. results.push(item);
  11284. }
  11285. if (!directDescendantsOnly) {
  11286. item._getDescendants(results, false, predicate);
  11287. }
  11288. }
  11289. };
  11290. /**
  11291. * Will return all nodes that have this node as ascendant.
  11292. * @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.
  11293. * @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.
  11294. * @return {BABYLON.Node[]} all children nodes of all types.
  11295. */
  11296. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11297. var results = [];
  11298. this._getDescendants(results, directDescendantsOnly, predicate);
  11299. return results;
  11300. };
  11301. /**
  11302. * Get all child-meshes of this node.
  11303. */
  11304. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11305. var results = [];
  11306. this._getDescendants(results, directDecendantsOnly, function (node) {
  11307. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11308. });
  11309. return results;
  11310. };
  11311. /**
  11312. * Get all direct children of this node.
  11313. */
  11314. Node.prototype.getChildren = function (predicate) {
  11315. return this.getDescendants(true, predicate);
  11316. };
  11317. Node.prototype._setReady = function (state) {
  11318. if (state === this._isReady) {
  11319. return;
  11320. }
  11321. if (!state) {
  11322. this._isReady = false;
  11323. return;
  11324. }
  11325. this._isReady = true;
  11326. if (this.onReady) {
  11327. this.onReady(this);
  11328. }
  11329. };
  11330. Node.prototype.getAnimationByName = function (name) {
  11331. for (var i = 0; i < this.animations.length; i++) {
  11332. var animation = this.animations[i];
  11333. if (animation.name === name) {
  11334. return animation;
  11335. }
  11336. }
  11337. return null;
  11338. };
  11339. Node.prototype.createAnimationRange = function (name, from, to) {
  11340. // check name not already in use
  11341. if (!this._ranges[name]) {
  11342. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11343. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11344. if (this.animations[i]) {
  11345. this.animations[i].createRange(name, from, to);
  11346. }
  11347. }
  11348. }
  11349. };
  11350. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11351. if (deleteFrames === void 0) { deleteFrames = true; }
  11352. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11353. if (this.animations[i]) {
  11354. this.animations[i].deleteRange(name, deleteFrames);
  11355. }
  11356. }
  11357. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11358. };
  11359. Node.prototype.getAnimationRange = function (name) {
  11360. return this._ranges[name];
  11361. };
  11362. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11363. var range = this.getAnimationRange(name);
  11364. if (!range) {
  11365. return null;
  11366. }
  11367. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11368. };
  11369. Node.prototype.serializeAnimationRanges = function () {
  11370. var serializationRanges = [];
  11371. for (var name in this._ranges) {
  11372. var range = {};
  11373. range.name = name;
  11374. range.from = this._ranges[name].from;
  11375. range.to = this._ranges[name].to;
  11376. serializationRanges.push(range);
  11377. }
  11378. return serializationRanges;
  11379. };
  11380. Node.prototype.dispose = function () {
  11381. this.parent = null;
  11382. // Callback
  11383. this.onDisposeObservable.notifyObservers(this);
  11384. this.onDisposeObservable.clear();
  11385. // Behaviors
  11386. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11387. var behavior = _a[_i];
  11388. behavior.detach(this);
  11389. }
  11390. };
  11391. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11392. if (parsedNode.ranges) {
  11393. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11394. var data = parsedNode.ranges[index];
  11395. node.createAnimationRange(data.name, data.from, data.to);
  11396. }
  11397. }
  11398. };
  11399. __decorate([
  11400. BABYLON.serialize()
  11401. ], Node.prototype, "name", void 0);
  11402. __decorate([
  11403. BABYLON.serialize()
  11404. ], Node.prototype, "id", void 0);
  11405. __decorate([
  11406. BABYLON.serialize()
  11407. ], Node.prototype, "uniqueId", void 0);
  11408. __decorate([
  11409. BABYLON.serialize()
  11410. ], Node.prototype, "state", void 0);
  11411. __decorate([
  11412. BABYLON.serialize()
  11413. ], Node.prototype, "metadata", void 0);
  11414. return Node;
  11415. }());
  11416. BABYLON.Node = Node;
  11417. })(BABYLON || (BABYLON = {}));
  11418. //# sourceMappingURL=babylon.node.js.map
  11419. var BABYLON;
  11420. (function (BABYLON) {
  11421. var BoundingSphere = (function () {
  11422. function BoundingSphere(minimum, maximum) {
  11423. this.minimum = minimum;
  11424. this.maximum = maximum;
  11425. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11426. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11427. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11428. this.radius = distance * 0.5;
  11429. this.centerWorld = BABYLON.Vector3.Zero();
  11430. this._update(BABYLON.Matrix.Identity());
  11431. }
  11432. // Methods
  11433. BoundingSphere.prototype._update = function (world) {
  11434. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11435. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11436. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11437. };
  11438. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11439. for (var i = 0; i < 6; i++) {
  11440. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11441. return false;
  11442. }
  11443. return true;
  11444. };
  11445. BoundingSphere.prototype.intersectsPoint = function (point) {
  11446. var x = this.centerWorld.x - point.x;
  11447. var y = this.centerWorld.y - point.y;
  11448. var z = this.centerWorld.z - point.z;
  11449. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11450. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11451. return false;
  11452. return true;
  11453. };
  11454. // Statics
  11455. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11456. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11457. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11458. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11459. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11460. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11461. return false;
  11462. return true;
  11463. };
  11464. return BoundingSphere;
  11465. }());
  11466. BABYLON.BoundingSphere = BoundingSphere;
  11467. })(BABYLON || (BABYLON = {}));
  11468. //# sourceMappingURL=babylon.boundingSphere.js.map
  11469. var BABYLON;
  11470. (function (BABYLON) {
  11471. var BoundingBox = (function () {
  11472. function BoundingBox(minimum, maximum) {
  11473. this.minimum = minimum;
  11474. this.maximum = maximum;
  11475. this.vectors = new Array();
  11476. this.vectorsWorld = new Array();
  11477. // Bounding vectors
  11478. this.vectors.push(this.minimum.clone());
  11479. this.vectors.push(this.maximum.clone());
  11480. this.vectors.push(this.minimum.clone());
  11481. this.vectors[2].x = this.maximum.x;
  11482. this.vectors.push(this.minimum.clone());
  11483. this.vectors[3].y = this.maximum.y;
  11484. this.vectors.push(this.minimum.clone());
  11485. this.vectors[4].z = this.maximum.z;
  11486. this.vectors.push(this.maximum.clone());
  11487. this.vectors[5].z = this.minimum.z;
  11488. this.vectors.push(this.maximum.clone());
  11489. this.vectors[6].x = this.minimum.x;
  11490. this.vectors.push(this.maximum.clone());
  11491. this.vectors[7].y = this.minimum.y;
  11492. // OBB
  11493. this.center = this.maximum.add(this.minimum).scale(0.5);
  11494. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11495. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11496. // World
  11497. for (var index = 0; index < this.vectors.length; index++) {
  11498. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11499. }
  11500. this.minimumWorld = BABYLON.Vector3.Zero();
  11501. this.maximumWorld = BABYLON.Vector3.Zero();
  11502. this.centerWorld = BABYLON.Vector3.Zero();
  11503. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11504. this._update(BABYLON.Matrix.Identity());
  11505. }
  11506. // Methods
  11507. BoundingBox.prototype.getWorldMatrix = function () {
  11508. return this._worldMatrix;
  11509. };
  11510. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11511. this._worldMatrix.copyFrom(matrix);
  11512. return this;
  11513. };
  11514. BoundingBox.prototype._update = function (world) {
  11515. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11516. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11517. for (var index = 0; index < this.vectors.length; index++) {
  11518. var v = this.vectorsWorld[index];
  11519. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11520. if (v.x < this.minimumWorld.x)
  11521. this.minimumWorld.x = v.x;
  11522. if (v.y < this.minimumWorld.y)
  11523. this.minimumWorld.y = v.y;
  11524. if (v.z < this.minimumWorld.z)
  11525. this.minimumWorld.z = v.z;
  11526. if (v.x > this.maximumWorld.x)
  11527. this.maximumWorld.x = v.x;
  11528. if (v.y > this.maximumWorld.y)
  11529. this.maximumWorld.y = v.y;
  11530. if (v.z > this.maximumWorld.z)
  11531. this.maximumWorld.z = v.z;
  11532. }
  11533. // Extend
  11534. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11535. this.extendSizeWorld.scaleInPlace(0.5);
  11536. // OBB
  11537. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11538. this.centerWorld.scaleInPlace(0.5);
  11539. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11540. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11541. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11542. this._worldMatrix = world;
  11543. };
  11544. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11545. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11546. };
  11547. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11548. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11549. };
  11550. BoundingBox.prototype.intersectsPoint = function (point) {
  11551. var delta = -BABYLON.Epsilon;
  11552. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11553. return false;
  11554. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11555. return false;
  11556. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11557. return false;
  11558. return true;
  11559. };
  11560. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11561. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11562. };
  11563. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11564. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11565. return false;
  11566. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11567. return false;
  11568. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11569. return false;
  11570. return true;
  11571. };
  11572. // Statics
  11573. BoundingBox.Intersects = function (box0, box1) {
  11574. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11575. return false;
  11576. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11577. return false;
  11578. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11579. return false;
  11580. return true;
  11581. };
  11582. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11583. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11584. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11585. return (num <= (sphereRadius * sphereRadius));
  11586. };
  11587. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11588. for (var p = 0; p < 6; p++) {
  11589. for (var i = 0; i < 8; i++) {
  11590. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11591. return false;
  11592. }
  11593. }
  11594. }
  11595. return true;
  11596. };
  11597. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11598. for (var p = 0; p < 6; p++) {
  11599. var inCount = 8;
  11600. for (var i = 0; i < 8; i++) {
  11601. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11602. --inCount;
  11603. }
  11604. else {
  11605. break;
  11606. }
  11607. }
  11608. if (inCount === 0)
  11609. return false;
  11610. }
  11611. return true;
  11612. };
  11613. return BoundingBox;
  11614. }());
  11615. BABYLON.BoundingBox = BoundingBox;
  11616. })(BABYLON || (BABYLON = {}));
  11617. //# sourceMappingURL=babylon.boundingBox.js.map
  11618. var BABYLON;
  11619. (function (BABYLON) {
  11620. var computeBoxExtents = function (axis, box) {
  11621. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11622. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11623. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11624. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11625. var r = r0 + r1 + r2;
  11626. return {
  11627. min: p - r,
  11628. max: p + r
  11629. };
  11630. };
  11631. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11632. var axisOverlap = function (axis, box0, box1) {
  11633. var result0 = computeBoxExtents(axis, box0);
  11634. var result1 = computeBoxExtents(axis, box1);
  11635. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11636. };
  11637. var BoundingInfo = (function () {
  11638. function BoundingInfo(minimum, maximum) {
  11639. this.minimum = minimum;
  11640. this.maximum = maximum;
  11641. this._isLocked = false;
  11642. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11643. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11644. }
  11645. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11646. get: function () {
  11647. return this._isLocked;
  11648. },
  11649. set: function (value) {
  11650. this._isLocked = value;
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. // Methods
  11656. BoundingInfo.prototype.update = function (world) {
  11657. if (this._isLocked) {
  11658. return;
  11659. }
  11660. this.boundingBox._update(world);
  11661. this.boundingSphere._update(world);
  11662. };
  11663. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11664. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11665. return false;
  11666. return this.boundingBox.isInFrustum(frustumPlanes);
  11667. };
  11668. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11669. /**
  11670. * Gets the world distance between the min and max points of the bounding box
  11671. */
  11672. get: function () {
  11673. var boundingBox = this.boundingBox;
  11674. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11675. return size.length();
  11676. },
  11677. enumerable: true,
  11678. configurable: true
  11679. });
  11680. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11681. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11682. };
  11683. BoundingInfo.prototype._checkCollision = function (collider) {
  11684. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11685. };
  11686. BoundingInfo.prototype.intersectsPoint = function (point) {
  11687. if (!this.boundingSphere.centerWorld) {
  11688. return false;
  11689. }
  11690. if (!this.boundingSphere.intersectsPoint(point)) {
  11691. return false;
  11692. }
  11693. if (!this.boundingBox.intersectsPoint(point)) {
  11694. return false;
  11695. }
  11696. return true;
  11697. };
  11698. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11699. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11700. return false;
  11701. }
  11702. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11703. return false;
  11704. }
  11705. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11706. return false;
  11707. }
  11708. if (!precise) {
  11709. return true;
  11710. }
  11711. var box0 = this.boundingBox;
  11712. var box1 = boundingInfo.boundingBox;
  11713. if (!axisOverlap(box0.directions[0], box0, box1))
  11714. return false;
  11715. if (!axisOverlap(box0.directions[1], box0, box1))
  11716. return false;
  11717. if (!axisOverlap(box0.directions[2], box0, box1))
  11718. return false;
  11719. if (!axisOverlap(box1.directions[0], box0, box1))
  11720. return false;
  11721. if (!axisOverlap(box1.directions[1], box0, box1))
  11722. return false;
  11723. if (!axisOverlap(box1.directions[2], box0, box1))
  11724. return false;
  11725. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11726. return false;
  11727. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11728. return false;
  11729. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11730. return false;
  11731. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11732. return false;
  11733. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11734. return false;
  11735. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11736. return false;
  11737. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11738. return false;
  11739. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11740. return false;
  11741. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11742. return false;
  11743. return true;
  11744. };
  11745. return BoundingInfo;
  11746. }());
  11747. BABYLON.BoundingInfo = BoundingInfo;
  11748. })(BABYLON || (BABYLON = {}));
  11749. //# sourceMappingURL=babylon.boundingInfo.js.map
  11750. var BABYLON;
  11751. (function (BABYLON) {
  11752. var AbstractMesh = (function (_super) {
  11753. __extends(AbstractMesh, _super);
  11754. // Constructor
  11755. function AbstractMesh(name, scene) {
  11756. var _this = _super.call(this, name, scene) || this;
  11757. _this._facetNb = 0; // facet number
  11758. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11759. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11760. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11761. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11762. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11763. _this._subDiv = {
  11764. max: 1,
  11765. X: 1,
  11766. Y: 1,
  11767. Z: 1
  11768. };
  11769. // Events
  11770. /**
  11771. * An event triggered when this mesh collides with another one
  11772. * @type {BABYLON.Observable}
  11773. */
  11774. _this.onCollideObservable = new BABYLON.Observable();
  11775. /**
  11776. * An event triggered when the collision's position changes
  11777. * @type {BABYLON.Observable}
  11778. */
  11779. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11780. /**
  11781. * An event triggered after the world matrix is updated
  11782. * @type {BABYLON.Observable}
  11783. */
  11784. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11785. /**
  11786. * An event triggered when material is changed
  11787. * @type {BABYLON.Observable}
  11788. */
  11789. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11790. // Properties
  11791. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11792. _this.position = BABYLON.Vector3.Zero();
  11793. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  11794. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  11795. _this.occlusionRetryCount = -1;
  11796. _this._occlusionInternalRetryCounter = 0;
  11797. _this._isOccluded = false;
  11798. _this._isOcclusionQueryInProgress = false;
  11799. _this._rotation = BABYLON.Vector3.Zero();
  11800. _this._scaling = BABYLON.Vector3.One();
  11801. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11802. _this.visibility = 1.0;
  11803. _this.alphaIndex = Number.MAX_VALUE;
  11804. _this.infiniteDistance = false;
  11805. _this.isVisible = true;
  11806. _this.isPickable = true;
  11807. _this.showBoundingBox = false;
  11808. _this.showSubMeshesBoundingBox = false;
  11809. _this.isBlocker = false;
  11810. _this.enablePointerMoveEvents = false;
  11811. _this.renderingGroupId = 0;
  11812. _this._receiveShadows = false;
  11813. _this.renderOutline = false;
  11814. _this.outlineColor = BABYLON.Color3.Red();
  11815. _this.outlineWidth = 0.02;
  11816. _this.renderOverlay = false;
  11817. _this.overlayColor = BABYLON.Color3.Red();
  11818. _this.overlayAlpha = 0.5;
  11819. _this._hasVertexAlpha = false;
  11820. _this._useVertexColors = true;
  11821. _this._computeBonesUsingShaders = true;
  11822. _this._numBoneInfluencers = 4;
  11823. _this._applyFog = true;
  11824. _this.scalingDeterminant = 1;
  11825. _this.useOctreeForRenderingSelection = true;
  11826. _this.useOctreeForPicking = true;
  11827. _this.useOctreeForCollisions = true;
  11828. _this._layerMask = 0x0FFFFFFF;
  11829. /**
  11830. * True if the mesh must be rendered in any case.
  11831. */
  11832. _this.alwaysSelectAsActiveMesh = false;
  11833. // Collisions
  11834. _this._checkCollisions = false;
  11835. _this._collisionMask = -1;
  11836. _this._collisionGroup = -1;
  11837. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11838. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11839. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11840. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11841. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11842. // Edges
  11843. _this.edgesWidth = 1;
  11844. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11845. // Cache
  11846. _this._localWorld = BABYLON.Matrix.Zero();
  11847. _this._worldMatrix = BABYLON.Matrix.Zero();
  11848. _this._absolutePosition = BABYLON.Vector3.Zero();
  11849. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11850. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11851. _this._isDirty = false;
  11852. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11853. _this._isDisposed = false;
  11854. _this._renderId = 0;
  11855. _this._intersectionsInProgress = new Array();
  11856. _this._isWorldMatrixFrozen = false;
  11857. _this._unIndexed = false;
  11858. _this._lightSources = new Array();
  11859. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11860. if (collidedMesh === void 0) { collidedMesh = null; }
  11861. //TODO move this to the collision coordinator!
  11862. if (_this.getScene().workerCollisions)
  11863. newPosition.multiplyInPlace(_this._collider.radius);
  11864. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11865. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11866. _this.position.addInPlace(_this._diffPositionForCollisions);
  11867. }
  11868. if (collidedMesh) {
  11869. _this.onCollideObservable.notifyObservers(collidedMesh);
  11870. }
  11871. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11872. };
  11873. _this.getScene().addMesh(_this);
  11874. _this._resyncLightSources();
  11875. return _this;
  11876. }
  11877. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11878. get: function () {
  11879. return AbstractMesh._BILLBOARDMODE_NONE;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11885. get: function () {
  11886. return AbstractMesh._BILLBOARDMODE_X;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11892. get: function () {
  11893. return AbstractMesh._BILLBOARDMODE_Y;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11899. get: function () {
  11900. return AbstractMesh._BILLBOARDMODE_Z;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11906. get: function () {
  11907. return AbstractMesh._BILLBOARDMODE_ALL;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11913. /**
  11914. * Read-only : the number of facets in the mesh
  11915. */
  11916. get: function () {
  11917. return this._facetNb;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11923. /**
  11924. * The number (integer) of subdivisions per axis in the partioning space
  11925. */
  11926. get: function () {
  11927. return this._partitioningSubdivisions;
  11928. },
  11929. set: function (nb) {
  11930. this._partitioningSubdivisions = nb;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11936. /**
  11937. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11938. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11939. */
  11940. get: function () {
  11941. return this._partitioningBBoxRatio;
  11942. },
  11943. set: function (ratio) {
  11944. this._partitioningBBoxRatio = ratio;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11950. /**
  11951. * Read-only boolean : is the feature facetData enabled ?
  11952. */
  11953. get: function () {
  11954. return this._facetDataEnabled;
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11960. set: function (callback) {
  11961. if (this._onCollideObserver) {
  11962. this.onCollideObservable.remove(this._onCollideObserver);
  11963. }
  11964. this._onCollideObserver = this.onCollideObservable.add(callback);
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11970. set: function (callback) {
  11971. if (this._onCollisionPositionChangeObserver) {
  11972. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11973. }
  11974. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  11980. get: function () {
  11981. return this._isOccluded;
  11982. },
  11983. set: function (value) {
  11984. this._isOccluded = value;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  11990. get: function () {
  11991. return this._isOcclusionQueryInProgress;
  11992. },
  11993. enumerable: true,
  11994. configurable: true
  11995. });
  11996. Object.defineProperty(AbstractMesh.prototype, "material", {
  11997. get: function () {
  11998. return this._material;
  11999. },
  12000. set: function (value) {
  12001. if (this._material === value) {
  12002. return;
  12003. }
  12004. this._material = value;
  12005. if (this.onMaterialChangedObservable.hasObservers) {
  12006. this.onMaterialChangedObservable.notifyObservers(this);
  12007. }
  12008. if (!this.subMeshes) {
  12009. return;
  12010. }
  12011. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12012. var subMesh = _a[_i];
  12013. subMesh.setEffect(null);
  12014. }
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12020. get: function () {
  12021. return this._receiveShadows;
  12022. },
  12023. set: function (value) {
  12024. if (this._receiveShadows === value) {
  12025. return;
  12026. }
  12027. this._receiveShadows = value;
  12028. this._markSubMeshesAsLightDirty();
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12034. get: function () {
  12035. return this._hasVertexAlpha;
  12036. },
  12037. set: function (value) {
  12038. if (this._hasVertexAlpha === value) {
  12039. return;
  12040. }
  12041. this._hasVertexAlpha = value;
  12042. this._markSubMeshesAsAttributesDirty();
  12043. },
  12044. enumerable: true,
  12045. configurable: true
  12046. });
  12047. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12048. get: function () {
  12049. return this._useVertexColors;
  12050. },
  12051. set: function (value) {
  12052. if (this._useVertexColors === value) {
  12053. return;
  12054. }
  12055. this._useVertexColors = value;
  12056. this._markSubMeshesAsAttributesDirty();
  12057. },
  12058. enumerable: true,
  12059. configurable: true
  12060. });
  12061. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12062. get: function () {
  12063. return this._computeBonesUsingShaders;
  12064. },
  12065. set: function (value) {
  12066. if (this._computeBonesUsingShaders === value) {
  12067. return;
  12068. }
  12069. this._computeBonesUsingShaders = value;
  12070. this._markSubMeshesAsAttributesDirty();
  12071. },
  12072. enumerable: true,
  12073. configurable: true
  12074. });
  12075. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12076. get: function () {
  12077. return this._numBoneInfluencers;
  12078. },
  12079. set: function (value) {
  12080. if (this._numBoneInfluencers === value) {
  12081. return;
  12082. }
  12083. this._numBoneInfluencers = value;
  12084. this._markSubMeshesAsAttributesDirty();
  12085. },
  12086. enumerable: true,
  12087. configurable: true
  12088. });
  12089. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12090. get: function () {
  12091. return this._applyFog;
  12092. },
  12093. set: function (value) {
  12094. if (this._applyFog === value) {
  12095. return;
  12096. }
  12097. this._applyFog = value;
  12098. this._markSubMeshesAsMiscDirty();
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12104. get: function () {
  12105. return this._layerMask;
  12106. },
  12107. set: function (value) {
  12108. if (value === this._layerMask) {
  12109. return;
  12110. }
  12111. this._layerMask = value;
  12112. this._resyncLightSources();
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12118. get: function () {
  12119. return this._collisionMask;
  12120. },
  12121. set: function (mask) {
  12122. this._collisionMask = !isNaN(mask) ? mask : -1;
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12128. get: function () {
  12129. return this._collisionGroup;
  12130. },
  12131. set: function (mask) {
  12132. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12133. },
  12134. enumerable: true,
  12135. configurable: true
  12136. });
  12137. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12138. get: function () {
  12139. return null;
  12140. },
  12141. enumerable: true,
  12142. configurable: true
  12143. });
  12144. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12145. get: function () {
  12146. return this._skeleton;
  12147. },
  12148. set: function (value) {
  12149. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12150. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12151. }
  12152. if (value && value.needInitialSkinMatrix) {
  12153. value._registerMeshWithPoseMatrix(this);
  12154. }
  12155. this._skeleton = value;
  12156. if (!this._skeleton) {
  12157. this._bonesTransformMatrices = null;
  12158. }
  12159. this._markSubMeshesAsAttributesDirty();
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. /**
  12165. * Boolean : true if the mesh has been disposed.
  12166. */
  12167. AbstractMesh.prototype.isDisposed = function () {
  12168. return this._isDisposed;
  12169. };
  12170. /**
  12171. * Returns the string "AbstractMesh"
  12172. */
  12173. AbstractMesh.prototype.getClassName = function () {
  12174. return "AbstractMesh";
  12175. };
  12176. /**
  12177. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12178. */
  12179. AbstractMesh.prototype.toString = function (fullDetails) {
  12180. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12181. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12182. if (this._skeleton) {
  12183. ret += ", skeleton: " + this._skeleton.name;
  12184. }
  12185. if (fullDetails) {
  12186. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12187. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12188. }
  12189. return ret;
  12190. };
  12191. AbstractMesh.prototype._resyncLightSources = function () {
  12192. this._lightSources.length = 0;
  12193. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12194. var light = _a[_i];
  12195. if (!light.isEnabled()) {
  12196. continue;
  12197. }
  12198. if (light.canAffectMesh(this)) {
  12199. this._lightSources.push(light);
  12200. }
  12201. }
  12202. this._markSubMeshesAsLightDirty();
  12203. };
  12204. AbstractMesh.prototype._resyncLighSource = function (light) {
  12205. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12206. var index = this._lightSources.indexOf(light);
  12207. if (index === -1) {
  12208. if (!isIn) {
  12209. return;
  12210. }
  12211. this._lightSources.push(light);
  12212. }
  12213. else {
  12214. if (isIn) {
  12215. return;
  12216. }
  12217. this._lightSources.splice(index, 1);
  12218. }
  12219. this._markSubMeshesAsLightDirty();
  12220. };
  12221. AbstractMesh.prototype._removeLightSource = function (light) {
  12222. var index = this._lightSources.indexOf(light);
  12223. if (index === -1) {
  12224. return;
  12225. }
  12226. this._lightSources.splice(index, 1);
  12227. };
  12228. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12229. if (!this.subMeshes) {
  12230. return;
  12231. }
  12232. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12233. var subMesh = _a[_i];
  12234. if (subMesh._materialDefines) {
  12235. func(subMesh._materialDefines);
  12236. }
  12237. }
  12238. };
  12239. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12240. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12241. };
  12242. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12243. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12244. };
  12245. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12246. if (!this.subMeshes) {
  12247. return;
  12248. }
  12249. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12250. var subMesh = _a[_i];
  12251. var material = subMesh.getMaterial();
  12252. if (material) {
  12253. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12254. }
  12255. }
  12256. };
  12257. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12258. /**
  12259. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12260. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12261. * Default : (0.0, 0.0, 0.0)
  12262. */
  12263. get: function () {
  12264. return this._rotation;
  12265. },
  12266. set: function (newRotation) {
  12267. this._rotation = newRotation;
  12268. },
  12269. enumerable: true,
  12270. configurable: true
  12271. });
  12272. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12273. /**
  12274. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12275. * Default : (1.0, 1.0, 1.0)
  12276. */
  12277. get: function () {
  12278. return this._scaling;
  12279. },
  12280. set: function (newScaling) {
  12281. this._scaling = newScaling;
  12282. if (this.physicsImpostor) {
  12283. this.physicsImpostor.forceUpdate();
  12284. }
  12285. },
  12286. enumerable: true,
  12287. configurable: true
  12288. });
  12289. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12290. /**
  12291. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12292. * It's null by default.
  12293. * 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)
  12294. */
  12295. get: function () {
  12296. return this._rotationQuaternion;
  12297. },
  12298. set: function (quaternion) {
  12299. this._rotationQuaternion = quaternion;
  12300. //reset the rotation vector.
  12301. if (quaternion && this.rotation.length()) {
  12302. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12303. }
  12304. },
  12305. enumerable: true,
  12306. configurable: true
  12307. });
  12308. // Methods
  12309. /**
  12310. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12311. * Returns the AbstractMesh.
  12312. */
  12313. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12314. this._poseMatrix.copyFrom(matrix);
  12315. return this;
  12316. };
  12317. /**
  12318. * Returns the mesh Pose matrix.
  12319. * Returned object : Matrix
  12320. */
  12321. AbstractMesh.prototype.getPoseMatrix = function () {
  12322. return this._poseMatrix;
  12323. };
  12324. /**
  12325. * Disables the mesh edger rendering mode.
  12326. * Returns the AbstractMesh.
  12327. */
  12328. AbstractMesh.prototype.disableEdgesRendering = function () {
  12329. if (this._edgesRenderer !== undefined) {
  12330. this._edgesRenderer.dispose();
  12331. this._edgesRenderer = undefined;
  12332. }
  12333. return this;
  12334. };
  12335. /**
  12336. * Enables the edge rendering mode on the mesh.
  12337. * This mode makes the mesh edges visible.
  12338. * Returns the AbstractMesh.
  12339. */
  12340. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12341. if (epsilon === void 0) { epsilon = 0.95; }
  12342. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12343. this.disableEdgesRendering();
  12344. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12345. return this;
  12346. };
  12347. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12348. /**
  12349. * Returns true if the mesh is blocked. Used by the class Mesh.
  12350. * Returns the boolean `false` by default.
  12351. */
  12352. get: function () {
  12353. return false;
  12354. },
  12355. enumerable: true,
  12356. configurable: true
  12357. });
  12358. /**
  12359. * Returns the mesh itself by default, used by the class Mesh.
  12360. * Returned type : AbstractMesh
  12361. */
  12362. AbstractMesh.prototype.getLOD = function (camera) {
  12363. return this;
  12364. };
  12365. /**
  12366. * Returns 0 by default, used by the class Mesh.
  12367. * Returns an integer.
  12368. */
  12369. AbstractMesh.prototype.getTotalVertices = function () {
  12370. return 0;
  12371. };
  12372. /**
  12373. * Returns null by default, used by the class Mesh.
  12374. * Returned type : integer array
  12375. */
  12376. AbstractMesh.prototype.getIndices = function () {
  12377. return null;
  12378. };
  12379. /**
  12380. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12381. * Returned type : float array or Float32Array
  12382. */
  12383. AbstractMesh.prototype.getVerticesData = function (kind) {
  12384. return null;
  12385. };
  12386. /**
  12387. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12388. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12389. * The `data` are either a numeric array either a Float32Array.
  12390. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12391. * 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).
  12392. * Note that a new underlying VertexBuffer object is created each call.
  12393. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12394. *
  12395. * Possible `kind` values :
  12396. * - BABYLON.VertexBuffer.PositionKind
  12397. * - BABYLON.VertexBuffer.UVKind
  12398. * - BABYLON.VertexBuffer.UV2Kind
  12399. * - BABYLON.VertexBuffer.UV3Kind
  12400. * - BABYLON.VertexBuffer.UV4Kind
  12401. * - BABYLON.VertexBuffer.UV5Kind
  12402. * - BABYLON.VertexBuffer.UV6Kind
  12403. * - BABYLON.VertexBuffer.ColorKind
  12404. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12405. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12406. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12407. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12408. *
  12409. * Returns the Mesh.
  12410. */
  12411. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12412. return null;
  12413. };
  12414. /**
  12415. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12416. * If the mesh has no geometry, it is simply returned as it is.
  12417. * The `data` are either a numeric array either a Float32Array.
  12418. * No new underlying VertexBuffer object is created.
  12419. * 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.
  12420. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12421. *
  12422. * Possible `kind` values :
  12423. * - BABYLON.VertexBuffer.PositionKind
  12424. * - BABYLON.VertexBuffer.UVKind
  12425. * - BABYLON.VertexBuffer.UV2Kind
  12426. * - BABYLON.VertexBuffer.UV3Kind
  12427. * - BABYLON.VertexBuffer.UV4Kind
  12428. * - BABYLON.VertexBuffer.UV5Kind
  12429. * - BABYLON.VertexBuffer.UV6Kind
  12430. * - BABYLON.VertexBuffer.ColorKind
  12431. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12432. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12433. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12434. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12435. *
  12436. * Returns the Mesh.
  12437. */
  12438. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12439. return null;
  12440. };
  12441. /**
  12442. * Sets the mesh indices.
  12443. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12444. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12445. * This method creates a new index buffer each call.
  12446. * Returns the Mesh.
  12447. */
  12448. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12449. return null;
  12450. };
  12451. /** Returns false by default, used by the class Mesh.
  12452. * Returns a boolean
  12453. */
  12454. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12455. return false;
  12456. };
  12457. /**
  12458. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12459. * Returns a BoundingInfo
  12460. */
  12461. AbstractMesh.prototype.getBoundingInfo = function () {
  12462. if (this._masterMesh) {
  12463. return this._masterMesh.getBoundingInfo();
  12464. }
  12465. if (!this._boundingInfo) {
  12466. this._updateBoundingInfo();
  12467. }
  12468. return this._boundingInfo;
  12469. };
  12470. /**
  12471. * Sets a mesh new object BoundingInfo.
  12472. * Returns the AbstractMesh.
  12473. */
  12474. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12475. this._boundingInfo = boundingInfo;
  12476. return this;
  12477. };
  12478. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12479. get: function () {
  12480. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12481. },
  12482. enumerable: true,
  12483. configurable: true
  12484. });
  12485. AbstractMesh.prototype._preActivate = function () {
  12486. };
  12487. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12488. };
  12489. AbstractMesh.prototype._activate = function (renderId) {
  12490. this._renderId = renderId;
  12491. };
  12492. /**
  12493. * Returns the last update of the World matrix
  12494. * Returns a Matrix.
  12495. */
  12496. AbstractMesh.prototype.getWorldMatrix = function () {
  12497. if (this._masterMesh) {
  12498. return this._masterMesh.getWorldMatrix();
  12499. }
  12500. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12501. this.computeWorldMatrix();
  12502. }
  12503. return this._worldMatrix;
  12504. };
  12505. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12506. /**
  12507. * Returns directly the last state of the mesh World matrix.
  12508. * A Matrix is returned.
  12509. */
  12510. get: function () {
  12511. return this._worldMatrix;
  12512. },
  12513. enumerable: true,
  12514. configurable: true
  12515. });
  12516. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12517. /**
  12518. * Returns the current mesh absolute position.
  12519. * Retuns a Vector3.
  12520. */
  12521. get: function () {
  12522. return this._absolutePosition;
  12523. },
  12524. enumerable: true,
  12525. configurable: true
  12526. });
  12527. /**
  12528. * Prevents the World matrix to be computed any longer.
  12529. * Returns the AbstractMesh.
  12530. */
  12531. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12532. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12533. this.computeWorldMatrix(true);
  12534. this._isWorldMatrixFrozen = true;
  12535. return this;
  12536. };
  12537. /**
  12538. * Allows back the World matrix computation.
  12539. * Returns the AbstractMesh.
  12540. */
  12541. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12542. this._isWorldMatrixFrozen = false;
  12543. this.computeWorldMatrix(true);
  12544. return this;
  12545. };
  12546. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12547. /**
  12548. * True if the World matrix has been frozen.
  12549. * Returns a boolean.
  12550. */
  12551. get: function () {
  12552. return this._isWorldMatrixFrozen;
  12553. },
  12554. enumerable: true,
  12555. configurable: true
  12556. });
  12557. /**
  12558. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12559. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12560. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12561. * The passed axis is also normalized.
  12562. * Returns the AbstractMesh.
  12563. */
  12564. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12565. axis.normalize();
  12566. if (!this.rotationQuaternion) {
  12567. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12568. this.rotation = BABYLON.Vector3.Zero();
  12569. }
  12570. var rotationQuaternion;
  12571. if (!space || space === BABYLON.Space.LOCAL) {
  12572. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12573. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12574. }
  12575. else {
  12576. if (this.parent) {
  12577. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12578. invertParentWorldMatrix.invert();
  12579. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12580. }
  12581. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12582. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12583. }
  12584. return this;
  12585. };
  12586. /**
  12587. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12588. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12589. * The passed axis is also normalized.
  12590. * Returns the AbstractMesh.
  12591. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12592. */
  12593. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12594. axis.normalize();
  12595. if (!this.rotationQuaternion) {
  12596. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12597. this.rotation.copyFromFloats(0, 0, 0);
  12598. }
  12599. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12600. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12601. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12602. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12603. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12604. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12605. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12606. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12607. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12608. return this;
  12609. };
  12610. /**
  12611. * Translates the mesh along the axis vector for the passed distance in the given space.
  12612. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12613. * Returns the AbstractMesh.
  12614. */
  12615. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12616. var displacementVector = axis.scale(distance);
  12617. if (!space || space === BABYLON.Space.LOCAL) {
  12618. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12619. this.setPositionWithLocalVector(tempV3);
  12620. }
  12621. else {
  12622. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12623. }
  12624. return this;
  12625. };
  12626. /**
  12627. * Adds a rotation step to the mesh current rotation.
  12628. * x, y, z are Euler angles expressed in radians.
  12629. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12630. * This means this rotation is made in the mesh local space only.
  12631. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12632. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12633. * ```javascript
  12634. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12635. * ```
  12636. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12637. * 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.
  12638. * Returns the AbstractMesh.
  12639. */
  12640. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12641. var rotationQuaternion;
  12642. if (this.rotationQuaternion) {
  12643. rotationQuaternion = this.rotationQuaternion;
  12644. }
  12645. else {
  12646. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12647. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12648. }
  12649. var accumulation = BABYLON.Tmp.Quaternion[0];
  12650. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12651. rotationQuaternion.multiplyInPlace(accumulation);
  12652. if (!this.rotationQuaternion) {
  12653. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12654. }
  12655. return this;
  12656. };
  12657. /**
  12658. * Retuns the mesh absolute position in the World.
  12659. * Returns a Vector3.
  12660. */
  12661. AbstractMesh.prototype.getAbsolutePosition = function () {
  12662. this.computeWorldMatrix();
  12663. return this._absolutePosition;
  12664. };
  12665. /**
  12666. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12667. * Returns the AbstractMesh.
  12668. */
  12669. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12670. if (!absolutePosition) {
  12671. return;
  12672. }
  12673. var absolutePositionX;
  12674. var absolutePositionY;
  12675. var absolutePositionZ;
  12676. if (absolutePosition.x === undefined) {
  12677. if (arguments.length < 3) {
  12678. return;
  12679. }
  12680. absolutePositionX = arguments[0];
  12681. absolutePositionY = arguments[1];
  12682. absolutePositionZ = arguments[2];
  12683. }
  12684. else {
  12685. absolutePositionX = absolutePosition.x;
  12686. absolutePositionY = absolutePosition.y;
  12687. absolutePositionZ = absolutePosition.z;
  12688. }
  12689. if (this.parent) {
  12690. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12691. invertParentWorldMatrix.invert();
  12692. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12693. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12694. }
  12695. else {
  12696. this.position.x = absolutePositionX;
  12697. this.position.y = absolutePositionY;
  12698. this.position.z = absolutePositionZ;
  12699. }
  12700. return this;
  12701. };
  12702. // ================================== Point of View Movement =================================
  12703. /**
  12704. * Perform relative position change from the point of view of behind the front of the mesh.
  12705. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12706. * Supports definition of mesh facing forward or backward.
  12707. * @param {number} amountRight
  12708. * @param {number} amountUp
  12709. * @param {number} amountForward
  12710. *
  12711. * Returns the AbstractMesh.
  12712. */
  12713. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12714. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12715. return this;
  12716. };
  12717. /**
  12718. * Calculate relative position change from the point of view of behind the front of the mesh.
  12719. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12720. * Supports definition of mesh facing forward or backward.
  12721. * @param {number} amountRight
  12722. * @param {number} amountUp
  12723. * @param {number} amountForward
  12724. *
  12725. * Returns a new Vector3.
  12726. */
  12727. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12728. var rotMatrix = new BABYLON.Matrix();
  12729. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12730. rotQuaternion.toRotationMatrix(rotMatrix);
  12731. var translationDelta = BABYLON.Vector3.Zero();
  12732. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12733. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12734. return translationDelta;
  12735. };
  12736. // ================================== Point of View Rotation =================================
  12737. /**
  12738. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12739. * Supports definition of mesh facing forward or backward.
  12740. * @param {number} flipBack
  12741. * @param {number} twirlClockwise
  12742. * @param {number} tiltRight
  12743. *
  12744. * Returns the AbstractMesh.
  12745. */
  12746. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12747. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12748. return this;
  12749. };
  12750. /**
  12751. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12752. * Supports definition of mesh facing forward or backward.
  12753. * @param {number} flipBack
  12754. * @param {number} twirlClockwise
  12755. * @param {number} tiltRight
  12756. *
  12757. * Returns a new Vector3.
  12758. */
  12759. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12760. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12761. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12762. };
  12763. /**
  12764. * Sets a new pivot matrix to the mesh.
  12765. * Returns the AbstractMesh.
  12766. */
  12767. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12768. this._pivotMatrix = matrix;
  12769. this._cache.pivotMatrixUpdated = true;
  12770. return this;
  12771. };
  12772. /**
  12773. * Returns the mesh pivot matrix.
  12774. * Default : Identity.
  12775. * A Matrix is returned.
  12776. */
  12777. AbstractMesh.prototype.getPivotMatrix = function () {
  12778. return this._pivotMatrix;
  12779. };
  12780. AbstractMesh.prototype._isSynchronized = function () {
  12781. if (this._isDirty) {
  12782. return false;
  12783. }
  12784. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12785. return false;
  12786. if (this._cache.pivotMatrixUpdated) {
  12787. return false;
  12788. }
  12789. if (this.infiniteDistance) {
  12790. return false;
  12791. }
  12792. if (!this._cache.position.equals(this.position))
  12793. return false;
  12794. if (this.rotationQuaternion) {
  12795. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12796. return false;
  12797. }
  12798. if (!this._cache.rotation.equals(this.rotation))
  12799. return false;
  12800. if (!this._cache.scaling.equals(this.scaling))
  12801. return false;
  12802. return true;
  12803. };
  12804. AbstractMesh.prototype._initCache = function () {
  12805. _super.prototype._initCache.call(this);
  12806. this._cache.localMatrixUpdated = false;
  12807. this._cache.position = BABYLON.Vector3.Zero();
  12808. this._cache.scaling = BABYLON.Vector3.Zero();
  12809. this._cache.rotation = BABYLON.Vector3.Zero();
  12810. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12811. this._cache.billboardMode = -1;
  12812. };
  12813. AbstractMesh.prototype.markAsDirty = function (property) {
  12814. if (property === "rotation") {
  12815. this.rotationQuaternion = null;
  12816. }
  12817. this._currentRenderId = Number.MAX_VALUE;
  12818. this._isDirty = true;
  12819. return this;
  12820. };
  12821. /**
  12822. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12823. * Returns the AbstractMesh.
  12824. */
  12825. AbstractMesh.prototype._updateBoundingInfo = function () {
  12826. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12827. this._boundingInfo.update(this.worldMatrixFromCache);
  12828. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12829. return this;
  12830. };
  12831. /**
  12832. * Update a mesh's children BoundingInfo objects only.
  12833. * Returns the AbstractMesh.
  12834. */
  12835. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12836. if (!this.subMeshes) {
  12837. return;
  12838. }
  12839. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12840. var subMesh = this.subMeshes[subIndex];
  12841. if (!subMesh.IsGlobal) {
  12842. subMesh.updateBoundingInfo(matrix);
  12843. }
  12844. }
  12845. return this;
  12846. };
  12847. /**
  12848. * Computes the mesh World matrix and returns it.
  12849. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12850. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12851. * If the parameter `force`is set to `true`, the actual computation is done.
  12852. * Returns the mesh World Matrix.
  12853. */
  12854. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12855. if (this._isWorldMatrixFrozen) {
  12856. return this._worldMatrix;
  12857. }
  12858. if (!force && this.isSynchronized(true)) {
  12859. this._currentRenderId = this.getScene().getRenderId();
  12860. return this._worldMatrix;
  12861. }
  12862. this._cache.position.copyFrom(this.position);
  12863. this._cache.scaling.copyFrom(this.scaling);
  12864. this._cache.pivotMatrixUpdated = false;
  12865. this._cache.billboardMode = this.billboardMode;
  12866. this._currentRenderId = this.getScene().getRenderId();
  12867. this._isDirty = false;
  12868. // Scaling
  12869. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12870. // Rotation
  12871. //rotate, if quaternion is set and rotation was used
  12872. if (this.rotationQuaternion) {
  12873. var len = this.rotation.length();
  12874. if (len) {
  12875. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12876. this.rotation.copyFromFloats(0, 0, 0);
  12877. }
  12878. }
  12879. if (this.rotationQuaternion) {
  12880. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12881. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12882. }
  12883. else {
  12884. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12885. this._cache.rotation.copyFrom(this.rotation);
  12886. }
  12887. // Translation
  12888. if (this.infiniteDistance && !this.parent) {
  12889. var camera = this.getScene().activeCamera;
  12890. if (camera) {
  12891. var cameraWorldMatrix = camera.getWorldMatrix();
  12892. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12893. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12894. }
  12895. }
  12896. else {
  12897. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12898. }
  12899. // Composing transformations
  12900. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12901. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12902. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12903. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12904. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12905. // Need to decompose each rotation here
  12906. var currentPosition = BABYLON.Tmp.Vector3[3];
  12907. if (this.parent && this.parent.getWorldMatrix) {
  12908. if (this._meshToBoneReferal) {
  12909. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12910. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12911. }
  12912. else {
  12913. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12914. }
  12915. }
  12916. else {
  12917. currentPosition.copyFrom(this.position);
  12918. }
  12919. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12920. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12921. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12922. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12923. }
  12924. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12925. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12926. }
  12927. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12928. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12929. }
  12930. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12931. }
  12932. else {
  12933. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12934. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12935. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12936. }
  12937. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12938. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12939. }
  12940. // Local world
  12941. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12942. // Parent
  12943. if (this.parent && this.parent.getWorldMatrix) {
  12944. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12945. if (this._meshToBoneReferal) {
  12946. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12947. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12948. }
  12949. else {
  12950. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12951. }
  12952. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12953. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12954. this._worldMatrix.copyFrom(this._localWorld);
  12955. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12956. }
  12957. else {
  12958. if (this._meshToBoneReferal) {
  12959. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12960. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12961. }
  12962. else {
  12963. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12964. }
  12965. }
  12966. this._markSyncedWithParent();
  12967. }
  12968. else {
  12969. this._worldMatrix.copyFrom(this._localWorld);
  12970. }
  12971. // Bounding info
  12972. this._updateBoundingInfo();
  12973. // Absolute position
  12974. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12975. // Callbacks
  12976. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12977. if (!this._poseMatrix) {
  12978. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12979. }
  12980. return this._worldMatrix;
  12981. };
  12982. /**
  12983. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12984. * @param func: callback function to add
  12985. *
  12986. * Returns the AbstractMesh.
  12987. */
  12988. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12989. this.onAfterWorldMatrixUpdateObservable.add(func);
  12990. return this;
  12991. };
  12992. /**
  12993. * Removes a registered callback function.
  12994. * Returns the AbstractMesh.
  12995. */
  12996. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12997. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12998. return this;
  12999. };
  13000. /**
  13001. * Sets the mesh position in its local space.
  13002. * Returns the AbstractMesh.
  13003. */
  13004. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13005. this.computeWorldMatrix();
  13006. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13007. return this;
  13008. };
  13009. /**
  13010. * Returns the mesh position in the local space from the current World matrix values.
  13011. * Returns a new Vector3.
  13012. */
  13013. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13014. this.computeWorldMatrix();
  13015. var invLocalWorldMatrix = this._localWorld.clone();
  13016. invLocalWorldMatrix.invert();
  13017. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13018. };
  13019. /**
  13020. * Translates the mesh along the passed Vector3 in its local space.
  13021. * Returns the AbstractMesh.
  13022. */
  13023. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13024. this.computeWorldMatrix(true);
  13025. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13026. return this;
  13027. };
  13028. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13029. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13030. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13031. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13032. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13033. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13034. /// <returns>Mesh oriented towards targetMesh</returns>
  13035. if (yawCor === void 0) { yawCor = 0; }
  13036. if (pitchCor === void 0) { pitchCor = 0; }
  13037. if (rollCor === void 0) { rollCor = 0; }
  13038. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13039. var dv = AbstractMesh._lookAtVectorCache;
  13040. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13041. targetPoint.subtractToRef(pos, dv);
  13042. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13043. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13044. var pitch = Math.atan2(dv.y, len);
  13045. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13046. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13047. return this;
  13048. };
  13049. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13050. this._meshToBoneReferal = affectedMesh;
  13051. this.parent = bone;
  13052. if (bone.getWorldMatrix().determinant() < 0) {
  13053. this.scalingDeterminant *= -1;
  13054. }
  13055. return this;
  13056. };
  13057. AbstractMesh.prototype.detachFromBone = function () {
  13058. if (this.parent.getWorldMatrix().determinant() < 0) {
  13059. this.scalingDeterminant *= -1;
  13060. }
  13061. this._meshToBoneReferal = null;
  13062. this.parent = null;
  13063. return this;
  13064. };
  13065. /**
  13066. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13067. * A mesh is in the frustum if its bounding box intersects the frustum.
  13068. * Boolean returned.
  13069. */
  13070. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13071. return this._boundingInfo.isInFrustum(frustumPlanes);
  13072. };
  13073. /**
  13074. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13075. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13076. * Boolean returned.
  13077. */
  13078. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13079. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13080. ;
  13081. };
  13082. /**
  13083. * True if the mesh intersects another mesh or a SolidParticle object.
  13084. * 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)
  13085. * Returns a boolean.
  13086. */
  13087. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13088. if (!this._boundingInfo || !mesh._boundingInfo) {
  13089. return false;
  13090. }
  13091. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13092. };
  13093. /**
  13094. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13095. * Returns a boolean.
  13096. */
  13097. AbstractMesh.prototype.intersectsPoint = function (point) {
  13098. if (!this._boundingInfo) {
  13099. return false;
  13100. }
  13101. return this._boundingInfo.intersectsPoint(point);
  13102. };
  13103. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13104. return this.physicsImpostor;
  13105. };
  13106. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13107. if (!camera) {
  13108. camera = this.getScene().activeCamera;
  13109. }
  13110. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13111. };
  13112. /**
  13113. * Returns the distance from the mesh to the active camera.
  13114. * Returns a float.
  13115. */
  13116. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13117. if (!camera) {
  13118. camera = this.getScene().activeCamera;
  13119. }
  13120. return this.absolutePosition.subtract(camera.position).length();
  13121. };
  13122. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13123. if (!this.physicsImpostor) {
  13124. return;
  13125. }
  13126. this.physicsImpostor.applyImpulse(force, contactPoint);
  13127. return this;
  13128. };
  13129. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13130. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13131. return;
  13132. }
  13133. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13134. mainPivot: pivot1,
  13135. connectedPivot: pivot2,
  13136. nativeParams: options
  13137. });
  13138. return this;
  13139. };
  13140. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13141. // Collisions
  13142. /**
  13143. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13144. * Default `false`.
  13145. */
  13146. get: function () {
  13147. return this._checkCollisions;
  13148. },
  13149. set: function (collisionEnabled) {
  13150. this._checkCollisions = collisionEnabled;
  13151. if (this.getScene().workerCollisions) {
  13152. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13153. }
  13154. },
  13155. enumerable: true,
  13156. configurable: true
  13157. });
  13158. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13159. var globalPosition = this.getAbsolutePosition();
  13160. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13161. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13162. if (!this._collider) {
  13163. this._collider = new BABYLON.Collider();
  13164. }
  13165. this._collider.radius = this.ellipsoid;
  13166. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13167. return this;
  13168. };
  13169. // Submeshes octree
  13170. /**
  13171. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13172. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13173. * Returns an Octree of submeshes.
  13174. */
  13175. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13176. if (maxCapacity === void 0) { maxCapacity = 64; }
  13177. if (maxDepth === void 0) { maxDepth = 2; }
  13178. if (!this._submeshesOctree) {
  13179. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13180. }
  13181. this.computeWorldMatrix(true);
  13182. // Update octree
  13183. var bbox = this.getBoundingInfo().boundingBox;
  13184. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13185. return this._submeshesOctree;
  13186. };
  13187. // Collisions
  13188. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13189. this._generatePointsArray();
  13190. // Transformation
  13191. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13192. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13193. subMesh._lastColliderWorldVertices = [];
  13194. subMesh._trianglePlanes = [];
  13195. var start = subMesh.verticesStart;
  13196. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13197. for (var i = start; i < end; i++) {
  13198. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13199. }
  13200. }
  13201. // Collide
  13202. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13203. if (collider.collisionFound) {
  13204. collider.collidedMesh = this;
  13205. }
  13206. return this;
  13207. };
  13208. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13209. var subMeshes;
  13210. var len;
  13211. // Octrees
  13212. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13213. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13214. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13215. len = intersections.length;
  13216. subMeshes = intersections.data;
  13217. }
  13218. else {
  13219. subMeshes = this.subMeshes;
  13220. len = subMeshes.length;
  13221. }
  13222. for (var index = 0; index < len; index++) {
  13223. var subMesh = subMeshes[index];
  13224. // Bounding test
  13225. if (len > 1 && !subMesh._checkCollision(collider))
  13226. continue;
  13227. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13228. }
  13229. return this;
  13230. };
  13231. AbstractMesh.prototype._checkCollision = function (collider) {
  13232. // Bounding box test
  13233. if (!this._boundingInfo._checkCollision(collider))
  13234. return this;
  13235. // Transformation matrix
  13236. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13237. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13238. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13239. return this;
  13240. };
  13241. // Picking
  13242. AbstractMesh.prototype._generatePointsArray = function () {
  13243. return false;
  13244. };
  13245. /**
  13246. * Checks if the passed Ray intersects with the mesh.
  13247. * Returns an object PickingInfo.
  13248. */
  13249. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13250. var pickingInfo = new BABYLON.PickingInfo();
  13251. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13252. return pickingInfo;
  13253. }
  13254. if (!this._generatePointsArray()) {
  13255. return pickingInfo;
  13256. }
  13257. var intersectInfo = null;
  13258. // Octrees
  13259. var subMeshes;
  13260. var len;
  13261. if (this._submeshesOctree && this.useOctreeForPicking) {
  13262. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13263. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13264. len = intersections.length;
  13265. subMeshes = intersections.data;
  13266. }
  13267. else {
  13268. subMeshes = this.subMeshes;
  13269. len = subMeshes.length;
  13270. }
  13271. for (var index = 0; index < len; index++) {
  13272. var subMesh = subMeshes[index];
  13273. // Bounding test
  13274. if (len > 1 && !subMesh.canIntersects(ray))
  13275. continue;
  13276. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13277. if (currentIntersectInfo) {
  13278. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13279. intersectInfo = currentIntersectInfo;
  13280. intersectInfo.subMeshId = index;
  13281. if (fastCheck) {
  13282. break;
  13283. }
  13284. }
  13285. }
  13286. }
  13287. if (intersectInfo) {
  13288. // Get picked point
  13289. var world = this.getWorldMatrix();
  13290. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13291. var direction = ray.direction.clone();
  13292. direction = direction.scale(intersectInfo.distance);
  13293. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13294. var pickedPoint = worldOrigin.add(worldDirection);
  13295. // Return result
  13296. pickingInfo.hit = true;
  13297. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13298. pickingInfo.pickedPoint = pickedPoint;
  13299. pickingInfo.pickedMesh = this;
  13300. pickingInfo.bu = intersectInfo.bu;
  13301. pickingInfo.bv = intersectInfo.bv;
  13302. pickingInfo.faceId = intersectInfo.faceId;
  13303. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13304. return pickingInfo;
  13305. }
  13306. return pickingInfo;
  13307. };
  13308. /**
  13309. * Clones the mesh, used by the class Mesh.
  13310. * Just returns `null` for an AbstractMesh.
  13311. */
  13312. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13313. return null;
  13314. };
  13315. /**
  13316. * Disposes all the mesh submeshes.
  13317. * Returns the AbstractMesh.
  13318. */
  13319. AbstractMesh.prototype.releaseSubMeshes = function () {
  13320. if (this.subMeshes) {
  13321. while (this.subMeshes.length) {
  13322. this.subMeshes[0].dispose();
  13323. }
  13324. }
  13325. else {
  13326. this.subMeshes = new Array();
  13327. }
  13328. return this;
  13329. };
  13330. /**
  13331. * Disposes the AbstractMesh.
  13332. * Some internal references are kept for further use.
  13333. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13334. * Returns nothing.
  13335. */
  13336. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13337. var _this = this;
  13338. var index;
  13339. // Action manager
  13340. if (this.actionManager) {
  13341. this.actionManager.dispose();
  13342. this.actionManager = null;
  13343. }
  13344. // Skeleton
  13345. this.skeleton = null;
  13346. // Animations
  13347. this.getScene().stopAnimation(this);
  13348. // Physics
  13349. if (this.physicsImpostor) {
  13350. this.physicsImpostor.dispose();
  13351. }
  13352. // Intersections in progress
  13353. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13354. var other = this._intersectionsInProgress[index];
  13355. var pos = other._intersectionsInProgress.indexOf(this);
  13356. other._intersectionsInProgress.splice(pos, 1);
  13357. }
  13358. this._intersectionsInProgress = [];
  13359. // Lights
  13360. var lights = this.getScene().lights;
  13361. lights.forEach(function (light) {
  13362. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13363. if (meshIndex !== -1) {
  13364. light.includedOnlyMeshes.splice(meshIndex, 1);
  13365. }
  13366. meshIndex = light.excludedMeshes.indexOf(_this);
  13367. if (meshIndex !== -1) {
  13368. light.excludedMeshes.splice(meshIndex, 1);
  13369. }
  13370. // Shadow generators
  13371. var generator = light.getShadowGenerator();
  13372. if (generator) {
  13373. var shadowMap = generator.getShadowMap();
  13374. meshIndex = shadowMap.renderList.indexOf(_this);
  13375. if (meshIndex !== -1) {
  13376. shadowMap.renderList.splice(meshIndex, 1);
  13377. }
  13378. }
  13379. });
  13380. // Edges
  13381. if (this._edgesRenderer) {
  13382. this._edgesRenderer.dispose();
  13383. this._edgesRenderer = null;
  13384. }
  13385. // SubMeshes
  13386. if (this.getClassName() !== "InstancedMesh") {
  13387. this.releaseSubMeshes();
  13388. }
  13389. // Octree
  13390. var sceneOctree = this.getScene().selectionOctree;
  13391. if (sceneOctree) {
  13392. var index = sceneOctree.dynamicContent.indexOf(this);
  13393. if (index !== -1) {
  13394. sceneOctree.dynamicContent.splice(index, 1);
  13395. }
  13396. }
  13397. // Query
  13398. var engine = this.getScene().getEngine();
  13399. if (this._occlusionQuery) {
  13400. engine.deleteQuery(this._occlusionQuery);
  13401. this._occlusionQuery = null;
  13402. }
  13403. // Engine
  13404. engine.wipeCaches();
  13405. // Remove from scene
  13406. this.getScene().removeMesh(this);
  13407. if (!doNotRecurse) {
  13408. // Particles
  13409. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13410. if (this.getScene().particleSystems[index].emitter === this) {
  13411. this.getScene().particleSystems[index].dispose();
  13412. index--;
  13413. }
  13414. }
  13415. // Children
  13416. var objects = this.getDescendants(true);
  13417. for (index = 0; index < objects.length; index++) {
  13418. objects[index].dispose();
  13419. }
  13420. }
  13421. else {
  13422. var childMeshes = this.getChildMeshes(true);
  13423. for (index = 0; index < childMeshes.length; index++) {
  13424. var child = childMeshes[index];
  13425. child.parent = null;
  13426. child.computeWorldMatrix(true);
  13427. }
  13428. }
  13429. // facet data
  13430. if (this._facetDataEnabled) {
  13431. this.disableFacetData();
  13432. }
  13433. this.onAfterWorldMatrixUpdateObservable.clear();
  13434. this.onCollideObservable.clear();
  13435. this.onCollisionPositionChangeObservable.clear();
  13436. this._isDisposed = true;
  13437. _super.prototype.dispose.call(this);
  13438. };
  13439. /**
  13440. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13441. * This Vector3 is expressed in the World space.
  13442. */
  13443. AbstractMesh.prototype.getDirection = function (localAxis) {
  13444. var result = BABYLON.Vector3.Zero();
  13445. this.getDirectionToRef(localAxis, result);
  13446. return result;
  13447. };
  13448. /**
  13449. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13450. * localAxis is expressed in the mesh local space.
  13451. * result is computed in the Wordl space from the mesh World matrix.
  13452. * Returns the AbstractMesh.
  13453. */
  13454. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13455. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13456. return this;
  13457. };
  13458. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13459. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13460. if (this.getScene().getRenderId() == 0) {
  13461. this.computeWorldMatrix(true);
  13462. }
  13463. var wm = this.getWorldMatrix();
  13464. if (space == BABYLON.Space.WORLD) {
  13465. var tmat = BABYLON.Tmp.Matrix[0];
  13466. wm.invertToRef(tmat);
  13467. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13468. }
  13469. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13470. this._pivotMatrix.m[12] = -point.x;
  13471. this._pivotMatrix.m[13] = -point.y;
  13472. this._pivotMatrix.m[14] = -point.z;
  13473. this._cache.pivotMatrixUpdated = true;
  13474. return this;
  13475. };
  13476. /**
  13477. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13478. */
  13479. AbstractMesh.prototype.getPivotPoint = function () {
  13480. var point = BABYLON.Vector3.Zero();
  13481. this.getPivotPointToRef(point);
  13482. return point;
  13483. };
  13484. /**
  13485. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13486. * Returns the AbstractMesh.
  13487. */
  13488. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13489. result.x = -this._pivotMatrix.m[12];
  13490. result.y = -this._pivotMatrix.m[13];
  13491. result.z = -this._pivotMatrix.m[14];
  13492. return this;
  13493. };
  13494. /**
  13495. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13496. */
  13497. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13498. var point = BABYLON.Vector3.Zero();
  13499. this.getAbsolutePivotPointToRef(point);
  13500. return point;
  13501. };
  13502. /**
  13503. * Defines the passed mesh as the parent of the current mesh.
  13504. * Returns the AbstractMesh.
  13505. */
  13506. AbstractMesh.prototype.setParent = function (mesh) {
  13507. var child = this;
  13508. var parent = mesh;
  13509. if (mesh == null) {
  13510. var rotation = BABYLON.Tmp.Quaternion[0];
  13511. var position = BABYLON.Tmp.Vector3[0];
  13512. var scale = BABYLON.Tmp.Vector3[1];
  13513. child.getWorldMatrix().decompose(scale, rotation, position);
  13514. if (child.rotationQuaternion) {
  13515. child.rotationQuaternion.copyFrom(rotation);
  13516. }
  13517. else {
  13518. rotation.toEulerAnglesToRef(child.rotation);
  13519. }
  13520. child.position.x = position.x;
  13521. child.position.y = position.y;
  13522. child.position.z = position.z;
  13523. }
  13524. else {
  13525. var rotation = BABYLON.Tmp.Quaternion[0];
  13526. var position = BABYLON.Tmp.Vector3[0];
  13527. var scale = BABYLON.Tmp.Vector3[1];
  13528. var m1 = BABYLON.Tmp.Matrix[0];
  13529. var m2 = BABYLON.Tmp.Matrix[1];
  13530. parent.getWorldMatrix().decompose(scale, rotation, position);
  13531. rotation.toRotationMatrix(m1);
  13532. m2.setTranslation(position);
  13533. m2.multiplyToRef(m1, m1);
  13534. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13535. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13536. m.decompose(scale, rotation, position);
  13537. if (child.rotationQuaternion) {
  13538. child.rotationQuaternion.copyFrom(rotation);
  13539. }
  13540. else {
  13541. rotation.toEulerAnglesToRef(child.rotation);
  13542. }
  13543. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13544. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13545. m.decompose(scale, rotation, position);
  13546. child.position.x = position.x;
  13547. child.position.y = position.y;
  13548. child.position.z = position.z;
  13549. }
  13550. child.parent = parent;
  13551. return this;
  13552. };
  13553. /**
  13554. * Adds the passed mesh as a child to the current mesh.
  13555. * Returns the AbstractMesh.
  13556. */
  13557. AbstractMesh.prototype.addChild = function (mesh) {
  13558. mesh.setParent(this);
  13559. return this;
  13560. };
  13561. /**
  13562. * Removes the passed mesh from the current mesh children list.
  13563. * Returns the AbstractMesh.
  13564. */
  13565. AbstractMesh.prototype.removeChild = function (mesh) {
  13566. mesh.setParent(null);
  13567. return this;
  13568. };
  13569. /**
  13570. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13571. * Returns the AbstractMesh.
  13572. */
  13573. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13574. result.x = this._pivotMatrix.m[12];
  13575. result.y = this._pivotMatrix.m[13];
  13576. result.z = this._pivotMatrix.m[14];
  13577. this.getPivotPointToRef(result);
  13578. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13579. return this;
  13580. };
  13581. // Facet data
  13582. /**
  13583. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13584. * Returns the AbstractMesh.
  13585. */
  13586. AbstractMesh.prototype._initFacetData = function () {
  13587. if (!this._facetNormals) {
  13588. this._facetNormals = new Array();
  13589. }
  13590. if (!this._facetPositions) {
  13591. this._facetPositions = new Array();
  13592. }
  13593. if (!this._facetPartitioning) {
  13594. this._facetPartitioning = new Array();
  13595. }
  13596. this._facetNb = this.getIndices().length / 3;
  13597. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13598. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13599. for (var f = 0; f < this._facetNb; f++) {
  13600. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13601. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13602. }
  13603. this._facetDataEnabled = true;
  13604. return this;
  13605. };
  13606. /**
  13607. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13608. * This method can be called within the render loop.
  13609. * 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.
  13610. * Returns the AbstractMesh.
  13611. */
  13612. AbstractMesh.prototype.updateFacetData = function () {
  13613. if (!this._facetDataEnabled) {
  13614. this._initFacetData();
  13615. }
  13616. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13617. var indices = this.getIndices();
  13618. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13619. var bInfo = this.getBoundingInfo();
  13620. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13621. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13622. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13623. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13624. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13625. this._subDiv.max = this._partitioningSubdivisions;
  13626. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13627. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13628. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13629. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13630. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13631. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13632. // set the parameters for ComputeNormals()
  13633. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13634. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13635. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13636. this._facetParameters.bInfo = bInfo;
  13637. this._facetParameters.bbSize = this._bbSize;
  13638. this._facetParameters.subDiv = this._subDiv;
  13639. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13640. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13641. return this;
  13642. };
  13643. /**
  13644. * Returns the facetLocalNormals array.
  13645. * The normals are expressed in the mesh local space.
  13646. */
  13647. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13648. if (!this._facetNormals) {
  13649. this.updateFacetData();
  13650. }
  13651. return this._facetNormals;
  13652. };
  13653. /**
  13654. * Returns the facetLocalPositions array.
  13655. * The facet positions are expressed in the mesh local space.
  13656. */
  13657. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13658. if (!this._facetPositions) {
  13659. this.updateFacetData();
  13660. }
  13661. return this._facetPositions;
  13662. };
  13663. /**
  13664. * Returns the facetLocalPartioning array.
  13665. */
  13666. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13667. if (!this._facetPartitioning) {
  13668. this.updateFacetData();
  13669. }
  13670. return this._facetPartitioning;
  13671. };
  13672. /**
  13673. * Returns the i-th facet position in the world system.
  13674. * This method allocates a new Vector3 per call.
  13675. */
  13676. AbstractMesh.prototype.getFacetPosition = function (i) {
  13677. var pos = BABYLON.Vector3.Zero();
  13678. this.getFacetPositionToRef(i, pos);
  13679. return pos;
  13680. };
  13681. /**
  13682. * Sets the reference Vector3 with the i-th facet position in the world system.
  13683. * Returns the AbstractMesh.
  13684. */
  13685. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13686. var localPos = (this.getFacetLocalPositions())[i];
  13687. var world = this.getWorldMatrix();
  13688. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13689. return this;
  13690. };
  13691. /**
  13692. * Returns the i-th facet normal in the world system.
  13693. * This method allocates a new Vector3 per call.
  13694. */
  13695. AbstractMesh.prototype.getFacetNormal = function (i) {
  13696. var norm = BABYLON.Vector3.Zero();
  13697. this.getFacetNormalToRef(i, norm);
  13698. return norm;
  13699. };
  13700. /**
  13701. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13702. * Returns the AbstractMesh.
  13703. */
  13704. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13705. var localNorm = (this.getFacetLocalNormals())[i];
  13706. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13707. return this;
  13708. };
  13709. /**
  13710. * 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).
  13711. */
  13712. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13713. var bInfo = this.getBoundingInfo();
  13714. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13715. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13716. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13717. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13718. return null;
  13719. }
  13720. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13721. };
  13722. /**
  13723. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13724. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13725. * 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.
  13726. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13727. * 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.
  13728. */
  13729. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13730. if (checkFace === void 0) { checkFace = false; }
  13731. if (facing === void 0) { facing = true; }
  13732. var world = this.getWorldMatrix();
  13733. var invMat = BABYLON.Tmp.Matrix[5];
  13734. world.invertToRef(invMat);
  13735. var invVect = BABYLON.Tmp.Vector3[8];
  13736. var closest = null;
  13737. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13738. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13739. if (projected) {
  13740. // tranform the local computed projected vector to world coordinates
  13741. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13742. }
  13743. return closest;
  13744. };
  13745. /**
  13746. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13747. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13748. * 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.
  13749. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13750. * 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.
  13751. */
  13752. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13753. if (checkFace === void 0) { checkFace = false; }
  13754. if (facing === void 0) { facing = true; }
  13755. var closest = null;
  13756. var tmpx = 0.0;
  13757. var tmpy = 0.0;
  13758. var tmpz = 0.0;
  13759. var d = 0.0; // tmp dot facet normal * facet position
  13760. var t0 = 0.0;
  13761. var projx = 0.0;
  13762. var projy = 0.0;
  13763. var projz = 0.0;
  13764. // Get all the facets in the same partitioning block than (x, y, z)
  13765. var facetPositions = this.getFacetLocalPositions();
  13766. var facetNormals = this.getFacetLocalNormals();
  13767. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13768. if (!facetsInBlock) {
  13769. return null;
  13770. }
  13771. // Get the closest facet to (x, y, z)
  13772. var shortest = Number.MAX_VALUE; // init distance vars
  13773. var tmpDistance = shortest;
  13774. var fib; // current facet in the block
  13775. var norm; // current facet normal
  13776. var p0; // current facet barycenter position
  13777. // loop on all the facets in the current partitioning block
  13778. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13779. fib = facetsInBlock[idx];
  13780. norm = facetNormals[fib];
  13781. p0 = facetPositions[fib];
  13782. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13783. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13784. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13785. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13786. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13787. projx = x + norm.x * t0;
  13788. projy = y + norm.y * t0;
  13789. projz = z + norm.z * t0;
  13790. tmpx = projx - x;
  13791. tmpy = projy - y;
  13792. tmpz = projz - z;
  13793. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13794. if (tmpDistance < shortest) {
  13795. shortest = tmpDistance;
  13796. closest = fib;
  13797. if (projected) {
  13798. projected.x = projx;
  13799. projected.y = projy;
  13800. projected.z = projz;
  13801. }
  13802. }
  13803. }
  13804. }
  13805. return closest;
  13806. };
  13807. /**
  13808. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13809. */
  13810. AbstractMesh.prototype.getFacetDataParameters = function () {
  13811. return this._facetParameters;
  13812. };
  13813. /**
  13814. * Disables the feature FacetData and frees the related memory.
  13815. * Returns the AbstractMesh.
  13816. */
  13817. AbstractMesh.prototype.disableFacetData = function () {
  13818. if (this._facetDataEnabled) {
  13819. this._facetDataEnabled = false;
  13820. this._facetPositions = null;
  13821. this._facetNormals = null;
  13822. this._facetPartitioning = null;
  13823. this._facetParameters = null;
  13824. }
  13825. return this;
  13826. };
  13827. /**
  13828. * Creates new normals data for the mesh.
  13829. * @param updatable.
  13830. */
  13831. AbstractMesh.prototype.createNormals = function (updatable) {
  13832. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13833. var indices = this.getIndices();
  13834. var normals;
  13835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13836. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13837. }
  13838. else {
  13839. normals = [];
  13840. }
  13841. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13842. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13843. };
  13844. AbstractMesh.prototype.checkOcclusionQuery = function () {
  13845. var engine = this.getEngine();
  13846. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  13847. this._isOccluded = false;
  13848. return;
  13849. }
  13850. if (this.isOcclusionQueryInProgress) {
  13851. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  13852. if (isOcclusionQueryAvailable) {
  13853. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  13854. this._isOcclusionQueryInProgress = false;
  13855. this._occlusionInternalRetryCounter = 0;
  13856. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  13857. }
  13858. else {
  13859. this._occlusionInternalRetryCounter++;
  13860. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  13861. this._isOcclusionQueryInProgress = false;
  13862. this._occlusionInternalRetryCounter = 0;
  13863. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  13864. // if strict continue the last state of the object.
  13865. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISITC ? false : this._isOccluded;
  13866. }
  13867. else {
  13868. return;
  13869. }
  13870. }
  13871. }
  13872. var scene = this.getScene();
  13873. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  13874. if (!this._occlusionQuery) {
  13875. this._occlusionQuery = engine.createQuery();
  13876. }
  13877. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  13878. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  13879. engine.endQuery(this.occlusionQueryAlgorithmType);
  13880. this._isOcclusionQueryInProgress = true;
  13881. };
  13882. // Statics
  13883. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13884. AbstractMesh._BILLBOARDMODE_X = 1;
  13885. AbstractMesh._BILLBOARDMODE_Y = 2;
  13886. AbstractMesh._BILLBOARDMODE_Z = 4;
  13887. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13888. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  13889. AbstractMesh.OCCLUSION_TYPE_OPTIMISITC = 1;
  13890. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  13891. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  13892. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  13893. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13894. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13895. return AbstractMesh;
  13896. }(BABYLON.Node));
  13897. BABYLON.AbstractMesh = AbstractMesh;
  13898. })(BABYLON || (BABYLON = {}));
  13899. //# sourceMappingURL=babylon.abstractMesh.js.map
  13900. var BABYLON;
  13901. (function (BABYLON) {
  13902. var Light = (function (_super) {
  13903. __extends(Light, _super);
  13904. /**
  13905. * Creates a Light object in the scene.
  13906. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13907. */
  13908. function Light(name, scene) {
  13909. var _this = _super.call(this, name, scene) || this;
  13910. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13911. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13912. _this.intensity = 1.0;
  13913. _this.range = Number.MAX_VALUE;
  13914. /**
  13915. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13916. * of light.
  13917. */
  13918. _this._photometricScale = 1.0;
  13919. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13920. _this._radius = 0.00001;
  13921. _this.renderPriority = 0;
  13922. /**
  13923. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13924. * the current shadow generator.
  13925. */
  13926. _this.shadowEnabled = true;
  13927. _this._excludeWithLayerMask = 0;
  13928. _this._includeOnlyWithLayerMask = 0;
  13929. _this._lightmapMode = 0;
  13930. _this._excludedMeshesIds = new Array();
  13931. _this._includedOnlyMeshesIds = new Array();
  13932. _this.getScene().addLight(_this);
  13933. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13934. _this._buildUniformLayout();
  13935. _this.includedOnlyMeshes = new Array();
  13936. _this.excludedMeshes = new Array();
  13937. _this._resyncMeshes();
  13938. return _this;
  13939. }
  13940. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13941. /**
  13942. * If every light affecting the material is in this lightmapMode,
  13943. * material.lightmapTexture adds or multiplies
  13944. * (depends on material.useLightmapAsShadowmap)
  13945. * after every other light calculations.
  13946. */
  13947. get: function () {
  13948. return Light._LIGHTMAP_DEFAULT;
  13949. },
  13950. enumerable: true,
  13951. configurable: true
  13952. });
  13953. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13954. /**
  13955. * material.lightmapTexture as only diffuse lighting from this light
  13956. * adds pnly specular lighting from this light
  13957. * adds dynamic shadows
  13958. */
  13959. get: function () {
  13960. return Light._LIGHTMAP_SPECULAR;
  13961. },
  13962. enumerable: true,
  13963. configurable: true
  13964. });
  13965. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13966. /**
  13967. * material.lightmapTexture as only lighting
  13968. * no light calculation from this light
  13969. * only adds dynamic shadows from this light
  13970. */
  13971. get: function () {
  13972. return Light._LIGHTMAP_SHADOWSONLY;
  13973. },
  13974. enumerable: true,
  13975. configurable: true
  13976. });
  13977. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13978. /**
  13979. * Each light type uses the default quantity according to its type:
  13980. * point/spot lights use luminous intensity
  13981. * directional lights use illuminance
  13982. */
  13983. get: function () {
  13984. return Light._INTENSITYMODE_AUTOMATIC;
  13985. },
  13986. enumerable: true,
  13987. configurable: true
  13988. });
  13989. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13990. /**
  13991. * lumen (lm)
  13992. */
  13993. get: function () {
  13994. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13995. },
  13996. enumerable: true,
  13997. configurable: true
  13998. });
  13999. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14000. /**
  14001. * candela (lm/sr)
  14002. */
  14003. get: function () {
  14004. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14005. },
  14006. enumerable: true,
  14007. configurable: true
  14008. });
  14009. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14010. /**
  14011. * lux (lm/m^2)
  14012. */
  14013. get: function () {
  14014. return Light._INTENSITYMODE_ILLUMINANCE;
  14015. },
  14016. enumerable: true,
  14017. configurable: true
  14018. });
  14019. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14020. /**
  14021. * nit (cd/m^2)
  14022. */
  14023. get: function () {
  14024. return Light._INTENSITYMODE_LUMINANCE;
  14025. },
  14026. enumerable: true,
  14027. configurable: true
  14028. });
  14029. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14030. /**
  14031. * Light type const id of the point light.
  14032. */
  14033. get: function () {
  14034. return Light._LIGHTTYPEID_POINTLIGHT;
  14035. },
  14036. enumerable: true,
  14037. configurable: true
  14038. });
  14039. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14040. /**
  14041. * Light type const id of the directional light.
  14042. */
  14043. get: function () {
  14044. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14045. },
  14046. enumerable: true,
  14047. configurable: true
  14048. });
  14049. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14050. /**
  14051. * Light type const id of the spot light.
  14052. */
  14053. get: function () {
  14054. return Light._LIGHTTYPEID_SPOTLIGHT;
  14055. },
  14056. enumerable: true,
  14057. configurable: true
  14058. });
  14059. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14060. /**
  14061. * Light type const id of the hemispheric light.
  14062. */
  14063. get: function () {
  14064. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14065. },
  14066. enumerable: true,
  14067. configurable: true
  14068. });
  14069. Object.defineProperty(Light.prototype, "intensityMode", {
  14070. /**
  14071. * Gets the photometric scale used to interpret the intensity.
  14072. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14073. */
  14074. get: function () {
  14075. return this._intensityMode;
  14076. },
  14077. /**
  14078. * Sets the photometric scale used to interpret the intensity.
  14079. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14080. */
  14081. set: function (value) {
  14082. this._intensityMode = value;
  14083. this._computePhotometricScale();
  14084. },
  14085. enumerable: true,
  14086. configurable: true
  14087. });
  14088. ;
  14089. ;
  14090. Object.defineProperty(Light.prototype, "radius", {
  14091. /**
  14092. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14093. */
  14094. get: function () {
  14095. return this._radius;
  14096. },
  14097. /**
  14098. * sets the light radius used by PBR Materials to simulate soft area lights.
  14099. */
  14100. set: function (value) {
  14101. this._radius = value;
  14102. this._computePhotometricScale();
  14103. },
  14104. enumerable: true,
  14105. configurable: true
  14106. });
  14107. ;
  14108. ;
  14109. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14110. get: function () {
  14111. return this._includedOnlyMeshes;
  14112. },
  14113. set: function (value) {
  14114. this._includedOnlyMeshes = value;
  14115. this._hookArrayForIncludedOnly(value);
  14116. },
  14117. enumerable: true,
  14118. configurable: true
  14119. });
  14120. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14121. get: function () {
  14122. return this._excludedMeshes;
  14123. },
  14124. set: function (value) {
  14125. this._excludedMeshes = value;
  14126. this._hookArrayForExcluded(value);
  14127. },
  14128. enumerable: true,
  14129. configurable: true
  14130. });
  14131. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14132. get: function () {
  14133. return this._excludeWithLayerMask;
  14134. },
  14135. set: function (value) {
  14136. this._excludeWithLayerMask = value;
  14137. this._resyncMeshes();
  14138. },
  14139. enumerable: true,
  14140. configurable: true
  14141. });
  14142. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14143. get: function () {
  14144. return this._includeOnlyWithLayerMask;
  14145. },
  14146. set: function (value) {
  14147. this._includeOnlyWithLayerMask = value;
  14148. this._resyncMeshes();
  14149. },
  14150. enumerable: true,
  14151. configurable: true
  14152. });
  14153. Object.defineProperty(Light.prototype, "lightmapMode", {
  14154. get: function () {
  14155. return this._lightmapMode;
  14156. },
  14157. set: function (value) {
  14158. if (this._lightmapMode === value) {
  14159. return;
  14160. }
  14161. this._lightmapMode = value;
  14162. this._markMeshesAsLightDirty();
  14163. },
  14164. enumerable: true,
  14165. configurable: true
  14166. });
  14167. Light.prototype._buildUniformLayout = function () {
  14168. // Overridden
  14169. };
  14170. /**
  14171. * Returns the string "Light".
  14172. */
  14173. Light.prototype.getClassName = function () {
  14174. return "Light";
  14175. };
  14176. /**
  14177. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14178. */
  14179. Light.prototype.toString = function (fullDetails) {
  14180. var ret = "Name: " + this.name;
  14181. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14182. if (this.animations) {
  14183. for (var i = 0; i < this.animations.length; i++) {
  14184. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14185. }
  14186. }
  14187. if (fullDetails) {
  14188. }
  14189. return ret;
  14190. };
  14191. /**
  14192. * Set the enabled state of this node.
  14193. * @param {boolean} value - the new enabled state
  14194. * @see isEnabled
  14195. */
  14196. Light.prototype.setEnabled = function (value) {
  14197. _super.prototype.setEnabled.call(this, value);
  14198. this._resyncMeshes();
  14199. };
  14200. /**
  14201. * Returns the Light associated shadow generator.
  14202. */
  14203. Light.prototype.getShadowGenerator = function () {
  14204. return this._shadowGenerator;
  14205. };
  14206. /**
  14207. * Returns a Vector3, the absolute light position in the World.
  14208. */
  14209. Light.prototype.getAbsolutePosition = function () {
  14210. return BABYLON.Vector3.Zero();
  14211. };
  14212. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14213. };
  14214. Light.prototype._getWorldMatrix = function () {
  14215. return BABYLON.Matrix.Identity();
  14216. };
  14217. /**
  14218. * Boolean : True if the light will affect the passed mesh.
  14219. */
  14220. Light.prototype.canAffectMesh = function (mesh) {
  14221. if (!mesh) {
  14222. return true;
  14223. }
  14224. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14225. return false;
  14226. }
  14227. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14228. return false;
  14229. }
  14230. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14231. return false;
  14232. }
  14233. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14234. return false;
  14235. }
  14236. return true;
  14237. };
  14238. /**
  14239. * Returns the light World matrix.
  14240. */
  14241. Light.prototype.getWorldMatrix = function () {
  14242. this._currentRenderId = this.getScene().getRenderId();
  14243. var worldMatrix = this._getWorldMatrix();
  14244. if (this.parent && this.parent.getWorldMatrix) {
  14245. if (!this._parentedWorldMatrix) {
  14246. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14247. }
  14248. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14249. this._markSyncedWithParent();
  14250. return this._parentedWorldMatrix;
  14251. }
  14252. return worldMatrix;
  14253. };
  14254. /**
  14255. * Sort function to order lights for rendering.
  14256. * @param a First Light object to compare to second.
  14257. * @param b Second Light object to compare first.
  14258. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14259. */
  14260. Light.compareLightsPriority = function (a, b) {
  14261. //shadow-casting lights have priority over non-shadow-casting lights
  14262. //the renderPrioirty is a secondary sort criterion
  14263. if (a.shadowEnabled !== b.shadowEnabled) {
  14264. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14265. }
  14266. return b.renderPriority - a.renderPriority;
  14267. };
  14268. /**
  14269. * Disposes the light.
  14270. */
  14271. Light.prototype.dispose = function () {
  14272. if (this._shadowGenerator) {
  14273. this._shadowGenerator.dispose();
  14274. this._shadowGenerator = null;
  14275. }
  14276. // Animations
  14277. this.getScene().stopAnimation(this);
  14278. // Remove from meshes
  14279. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14280. var mesh = _a[_i];
  14281. mesh._removeLightSource(this);
  14282. }
  14283. this._uniformBuffer.dispose();
  14284. // Remove from scene
  14285. this.getScene().removeLight(this);
  14286. _super.prototype.dispose.call(this);
  14287. };
  14288. /**
  14289. * Returns the light type ID (integer).
  14290. */
  14291. Light.prototype.getTypeID = function () {
  14292. return 0;
  14293. };
  14294. /**
  14295. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14296. */
  14297. Light.prototype.getScaledIntensity = function () {
  14298. return this._photometricScale * this.intensity;
  14299. };
  14300. /**
  14301. * Returns a new Light object, named "name", from the current one.
  14302. */
  14303. Light.prototype.clone = function (name) {
  14304. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14305. };
  14306. /**
  14307. * Serializes the current light into a Serialization object.
  14308. * Returns the serialized object.
  14309. */
  14310. Light.prototype.serialize = function () {
  14311. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14312. // Type
  14313. serializationObject.type = this.getTypeID();
  14314. // Parent
  14315. if (this.parent) {
  14316. serializationObject.parentId = this.parent.id;
  14317. }
  14318. // Inclusion / exclusions
  14319. if (this.excludedMeshes.length > 0) {
  14320. serializationObject.excludedMeshesIds = [];
  14321. this.excludedMeshes.forEach(function (mesh) {
  14322. serializationObject.excludedMeshesIds.push(mesh.id);
  14323. });
  14324. }
  14325. if (this.includedOnlyMeshes.length > 0) {
  14326. serializationObject.includedOnlyMeshesIds = [];
  14327. this.includedOnlyMeshes.forEach(function (mesh) {
  14328. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14329. });
  14330. }
  14331. // Animations
  14332. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14333. serializationObject.ranges = this.serializeAnimationRanges();
  14334. return serializationObject;
  14335. };
  14336. /**
  14337. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14338. * This new light is named "name" and added to the passed scene.
  14339. */
  14340. Light.GetConstructorFromName = function (type, name, scene) {
  14341. switch (type) {
  14342. case 0:
  14343. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14344. case 1:
  14345. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14346. case 2:
  14347. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14348. case 3:
  14349. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14350. }
  14351. };
  14352. /**
  14353. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14354. */
  14355. Light.Parse = function (parsedLight, scene) {
  14356. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14357. // Inclusion / exclusions
  14358. if (parsedLight.excludedMeshesIds) {
  14359. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14360. }
  14361. if (parsedLight.includedOnlyMeshesIds) {
  14362. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14363. }
  14364. // Parent
  14365. if (parsedLight.parentId) {
  14366. light._waitingParentId = parsedLight.parentId;
  14367. }
  14368. // Animations
  14369. if (parsedLight.animations) {
  14370. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14371. var parsedAnimation = parsedLight.animations[animationIndex];
  14372. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14373. }
  14374. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14375. }
  14376. if (parsedLight.autoAnimate) {
  14377. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14378. }
  14379. return light;
  14380. };
  14381. Light.prototype._hookArrayForExcluded = function (array) {
  14382. var _this = this;
  14383. var oldPush = array.push;
  14384. array.push = function () {
  14385. var items = [];
  14386. for (var _i = 0; _i < arguments.length; _i++) {
  14387. items[_i] = arguments[_i];
  14388. }
  14389. var result = oldPush.apply(array, items);
  14390. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14391. var item = items_1[_a];
  14392. item._resyncLighSource(_this);
  14393. }
  14394. return result;
  14395. };
  14396. var oldSplice = array.splice;
  14397. array.splice = function (index, deleteCount) {
  14398. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14399. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14400. var item = deleted_1[_i];
  14401. item._resyncLighSource(_this);
  14402. }
  14403. return deleted;
  14404. };
  14405. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14406. var item = array_1[_i];
  14407. item._resyncLighSource(this);
  14408. }
  14409. };
  14410. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14411. var _this = this;
  14412. var oldPush = array.push;
  14413. array.push = function () {
  14414. var items = [];
  14415. for (var _i = 0; _i < arguments.length; _i++) {
  14416. items[_i] = arguments[_i];
  14417. }
  14418. var result = oldPush.apply(array, items);
  14419. _this._resyncMeshes();
  14420. return result;
  14421. };
  14422. var oldSplice = array.splice;
  14423. array.splice = function (index, deleteCount) {
  14424. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14425. _this._resyncMeshes();
  14426. return deleted;
  14427. };
  14428. this._resyncMeshes();
  14429. };
  14430. Light.prototype._resyncMeshes = function () {
  14431. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14432. var mesh = _a[_i];
  14433. mesh._resyncLighSource(this);
  14434. }
  14435. };
  14436. Light.prototype._markMeshesAsLightDirty = function () {
  14437. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14438. var mesh = _a[_i];
  14439. if (mesh._lightSources.indexOf(this) !== -1) {
  14440. mesh._markSubMeshesAsLightDirty();
  14441. }
  14442. }
  14443. };
  14444. /**
  14445. * Recomputes the cached photometric scale if needed.
  14446. */
  14447. Light.prototype._computePhotometricScale = function () {
  14448. this._photometricScale = this._getPhotometricScale();
  14449. this.getScene().resetCachedMaterial();
  14450. };
  14451. /**
  14452. * Returns the Photometric Scale according to the light type and intensity mode.
  14453. */
  14454. Light.prototype._getPhotometricScale = function () {
  14455. var photometricScale = 0.0;
  14456. var lightTypeID = this.getTypeID();
  14457. //get photometric mode
  14458. var photometricMode = this.intensityMode;
  14459. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14460. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14461. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14462. }
  14463. else {
  14464. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14465. }
  14466. }
  14467. //compute photometric scale
  14468. switch (lightTypeID) {
  14469. case Light.LIGHTTYPEID_POINTLIGHT:
  14470. case Light.LIGHTTYPEID_SPOTLIGHT:
  14471. switch (photometricMode) {
  14472. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14473. photometricScale = 1.0 / (4.0 * Math.PI);
  14474. break;
  14475. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14476. photometricScale = 1.0;
  14477. break;
  14478. case Light.INTENSITYMODE_LUMINANCE:
  14479. photometricScale = this.radius * this.radius;
  14480. break;
  14481. }
  14482. break;
  14483. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14484. switch (photometricMode) {
  14485. case Light.INTENSITYMODE_ILLUMINANCE:
  14486. photometricScale = 1.0;
  14487. break;
  14488. case Light.INTENSITYMODE_LUMINANCE:
  14489. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14490. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14491. var apexAngleRadians = this.radius;
  14492. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14493. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14494. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14495. photometricScale = solidAngle;
  14496. break;
  14497. }
  14498. break;
  14499. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14500. // No fall off in hemisperic light.
  14501. photometricScale = 1.0;
  14502. break;
  14503. }
  14504. return photometricScale;
  14505. };
  14506. Light.prototype._reorderLightsInScene = function () {
  14507. var scene = this.getScene();
  14508. if (this.renderPriority != 0) {
  14509. scene.requireLightSorting = true;
  14510. }
  14511. this.getScene().sortLightsByPriority();
  14512. };
  14513. //lightmapMode Consts
  14514. Light._LIGHTMAP_DEFAULT = 0;
  14515. Light._LIGHTMAP_SPECULAR = 1;
  14516. Light._LIGHTMAP_SHADOWSONLY = 2;
  14517. // Intensity Mode Consts
  14518. Light._INTENSITYMODE_AUTOMATIC = 0;
  14519. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14520. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14521. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14522. Light._INTENSITYMODE_LUMINANCE = 4;
  14523. // Light types ids const.
  14524. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14525. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14526. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14527. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14528. __decorate([
  14529. BABYLON.serializeAsColor3()
  14530. ], Light.prototype, "diffuse", void 0);
  14531. __decorate([
  14532. BABYLON.serializeAsColor3()
  14533. ], Light.prototype, "specular", void 0);
  14534. __decorate([
  14535. BABYLON.serialize()
  14536. ], Light.prototype, "intensity", void 0);
  14537. __decorate([
  14538. BABYLON.serialize()
  14539. ], Light.prototype, "range", void 0);
  14540. __decorate([
  14541. BABYLON.serialize()
  14542. ], Light.prototype, "intensityMode", null);
  14543. __decorate([
  14544. BABYLON.serialize()
  14545. ], Light.prototype, "radius", null);
  14546. __decorate([
  14547. BABYLON.serialize()
  14548. ], Light.prototype, "_renderPriority", void 0);
  14549. __decorate([
  14550. BABYLON.expandToProperty("_reorderLightsInScene")
  14551. ], Light.prototype, "renderPriority", void 0);
  14552. __decorate([
  14553. BABYLON.serialize()
  14554. ], Light.prototype, "shadowEnabled", void 0);
  14555. __decorate([
  14556. BABYLON.serialize("excludeWithLayerMask")
  14557. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14558. __decorate([
  14559. BABYLON.serialize("includeOnlyWithLayerMask")
  14560. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14561. __decorate([
  14562. BABYLON.serialize("lightmapMode")
  14563. ], Light.prototype, "_lightmapMode", void 0);
  14564. return Light;
  14565. }(BABYLON.Node));
  14566. BABYLON.Light = Light;
  14567. })(BABYLON || (BABYLON = {}));
  14568. //# sourceMappingURL=babylon.light.js.map
  14569. var BABYLON;
  14570. (function (BABYLON) {
  14571. var Camera = (function (_super) {
  14572. __extends(Camera, _super);
  14573. function Camera(name, position, scene) {
  14574. var _this = _super.call(this, name, scene) || this;
  14575. _this.upVector = BABYLON.Vector3.Up();
  14576. _this.orthoLeft = null;
  14577. _this.orthoRight = null;
  14578. _this.orthoBottom = null;
  14579. _this.orthoTop = null;
  14580. _this.fov = 0.8;
  14581. _this.minZ = 1.0;
  14582. _this.maxZ = 10000.0;
  14583. _this.inertia = 0.9;
  14584. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14585. _this.isIntermediate = false;
  14586. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14587. _this.layerMask = 0x0FFFFFFF;
  14588. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14589. // Camera rig members
  14590. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14591. _this._rigCameras = new Array();
  14592. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14593. _this.customRenderTargets = new Array();
  14594. // Observables
  14595. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14596. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14597. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14598. // Cache
  14599. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14600. _this._projectionMatrix = new BABYLON.Matrix();
  14601. _this._doNotComputeProjectionMatrix = false;
  14602. _this._postProcesses = new Array();
  14603. _this._transformMatrix = BABYLON.Matrix.Zero();
  14604. _this._activeMeshes = new BABYLON.SmartArray(256);
  14605. _this._globalPosition = BABYLON.Vector3.Zero();
  14606. _this._refreshFrustumPlanes = true;
  14607. _this.getScene().addCamera(_this);
  14608. if (!_this.getScene().activeCamera) {
  14609. _this.getScene().activeCamera = _this;
  14610. }
  14611. _this.position = position;
  14612. return _this;
  14613. }
  14614. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14615. get: function () {
  14616. return Camera._PERSPECTIVE_CAMERA;
  14617. },
  14618. enumerable: true,
  14619. configurable: true
  14620. });
  14621. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14622. get: function () {
  14623. return Camera._ORTHOGRAPHIC_CAMERA;
  14624. },
  14625. enumerable: true,
  14626. configurable: true
  14627. });
  14628. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14629. get: function () {
  14630. return Camera._FOVMODE_VERTICAL_FIXED;
  14631. },
  14632. enumerable: true,
  14633. configurable: true
  14634. });
  14635. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14636. get: function () {
  14637. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14638. },
  14639. enumerable: true,
  14640. configurable: true
  14641. });
  14642. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14643. get: function () {
  14644. return Camera._RIG_MODE_NONE;
  14645. },
  14646. enumerable: true,
  14647. configurable: true
  14648. });
  14649. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14650. get: function () {
  14651. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14652. },
  14653. enumerable: true,
  14654. configurable: true
  14655. });
  14656. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14657. get: function () {
  14658. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14659. },
  14660. enumerable: true,
  14661. configurable: true
  14662. });
  14663. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14664. get: function () {
  14665. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14666. },
  14667. enumerable: true,
  14668. configurable: true
  14669. });
  14670. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14671. get: function () {
  14672. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14673. },
  14674. enumerable: true,
  14675. configurable: true
  14676. });
  14677. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14678. get: function () {
  14679. return Camera._RIG_MODE_VR;
  14680. },
  14681. enumerable: true,
  14682. configurable: true
  14683. });
  14684. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14685. get: function () {
  14686. return Camera._RIG_MODE_WEBVR;
  14687. },
  14688. enumerable: true,
  14689. configurable: true
  14690. });
  14691. Camera.prototype.getClassName = function () {
  14692. return "Camera";
  14693. };
  14694. /**
  14695. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14696. */
  14697. Camera.prototype.toString = function (fullDetails) {
  14698. var ret = "Name: " + this.name;
  14699. ret += ", type: " + this.getClassName();
  14700. if (this.animations) {
  14701. for (var i = 0; i < this.animations.length; i++) {
  14702. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14703. }
  14704. }
  14705. if (fullDetails) {
  14706. }
  14707. return ret;
  14708. };
  14709. Object.defineProperty(Camera.prototype, "globalPosition", {
  14710. get: function () {
  14711. return this._globalPosition;
  14712. },
  14713. enumerable: true,
  14714. configurable: true
  14715. });
  14716. Camera.prototype.getActiveMeshes = function () {
  14717. return this._activeMeshes;
  14718. };
  14719. Camera.prototype.isActiveMesh = function (mesh) {
  14720. return (this._activeMeshes.indexOf(mesh) !== -1);
  14721. };
  14722. //Cache
  14723. Camera.prototype._initCache = function () {
  14724. _super.prototype._initCache.call(this);
  14725. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14726. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14727. this._cache.mode = undefined;
  14728. this._cache.minZ = undefined;
  14729. this._cache.maxZ = undefined;
  14730. this._cache.fov = undefined;
  14731. this._cache.fovMode = undefined;
  14732. this._cache.aspectRatio = undefined;
  14733. this._cache.orthoLeft = undefined;
  14734. this._cache.orthoRight = undefined;
  14735. this._cache.orthoBottom = undefined;
  14736. this._cache.orthoTop = undefined;
  14737. this._cache.renderWidth = undefined;
  14738. this._cache.renderHeight = undefined;
  14739. };
  14740. Camera.prototype._updateCache = function (ignoreParentClass) {
  14741. if (!ignoreParentClass) {
  14742. _super.prototype._updateCache.call(this);
  14743. }
  14744. var engine = this.getEngine();
  14745. this._cache.position.copyFrom(this.position);
  14746. this._cache.upVector.copyFrom(this.upVector);
  14747. this._cache.mode = this.mode;
  14748. this._cache.minZ = this.minZ;
  14749. this._cache.maxZ = this.maxZ;
  14750. this._cache.fov = this.fov;
  14751. this._cache.fovMode = this.fovMode;
  14752. this._cache.aspectRatio = engine.getAspectRatio(this);
  14753. this._cache.orthoLeft = this.orthoLeft;
  14754. this._cache.orthoRight = this.orthoRight;
  14755. this._cache.orthoBottom = this.orthoBottom;
  14756. this._cache.orthoTop = this.orthoTop;
  14757. this._cache.renderWidth = engine.getRenderWidth();
  14758. this._cache.renderHeight = engine.getRenderHeight();
  14759. };
  14760. Camera.prototype._updateFromScene = function () {
  14761. this.updateCache();
  14762. this.update();
  14763. };
  14764. // Synchronized
  14765. Camera.prototype._isSynchronized = function () {
  14766. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14767. };
  14768. Camera.prototype._isSynchronizedViewMatrix = function () {
  14769. if (!_super.prototype._isSynchronized.call(this))
  14770. return false;
  14771. return this._cache.position.equals(this.position)
  14772. && this._cache.upVector.equals(this.upVector)
  14773. && this.isSynchronizedWithParent();
  14774. };
  14775. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14776. var check = this._cache.mode === this.mode
  14777. && this._cache.minZ === this.minZ
  14778. && this._cache.maxZ === this.maxZ;
  14779. if (!check) {
  14780. return false;
  14781. }
  14782. var engine = this.getEngine();
  14783. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14784. check = this._cache.fov === this.fov
  14785. && this._cache.fovMode === this.fovMode
  14786. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14787. }
  14788. else {
  14789. check = this._cache.orthoLeft === this.orthoLeft
  14790. && this._cache.orthoRight === this.orthoRight
  14791. && this._cache.orthoBottom === this.orthoBottom
  14792. && this._cache.orthoTop === this.orthoTop
  14793. && this._cache.renderWidth === engine.getRenderWidth()
  14794. && this._cache.renderHeight === engine.getRenderHeight();
  14795. }
  14796. return check;
  14797. };
  14798. // Controls
  14799. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14800. };
  14801. Camera.prototype.detachControl = function (element) {
  14802. };
  14803. Camera.prototype.update = function () {
  14804. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14805. this._updateRigCameras();
  14806. }
  14807. this._checkInputs();
  14808. };
  14809. Camera.prototype._checkInputs = function () {
  14810. this.onAfterCheckInputsObservable.notifyObservers(this);
  14811. };
  14812. Object.defineProperty(Camera.prototype, "rigCameras", {
  14813. get: function () {
  14814. return this._rigCameras;
  14815. },
  14816. enumerable: true,
  14817. configurable: true
  14818. });
  14819. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14820. get: function () {
  14821. return this._rigPostProcess;
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14827. // invalidate framebuffer
  14828. if (this._postProcesses.length > 0) {
  14829. this._postProcesses[0].markTextureDirty();
  14830. }
  14831. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14832. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14833. var cam = this._rigCameras[i];
  14834. var rigPostProcess = cam._rigPostProcess;
  14835. // for VR rig, there does not have to be a post process
  14836. if (rigPostProcess) {
  14837. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14838. if (isPass) {
  14839. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14840. cam.isIntermediate = this._postProcesses.length === 0;
  14841. }
  14842. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14843. rigPostProcess.markTextureDirty();
  14844. }
  14845. else {
  14846. cam._postProcesses = this._postProcesses.slice(0);
  14847. }
  14848. }
  14849. };
  14850. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14851. if (insertAt === void 0) { insertAt = null; }
  14852. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14853. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14854. return 0;
  14855. }
  14856. if (insertAt == null || insertAt < 0) {
  14857. this._postProcesses.push(postProcess);
  14858. }
  14859. else {
  14860. this._postProcesses.splice(insertAt, 0, postProcess);
  14861. }
  14862. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14863. return this._postProcesses.indexOf(postProcess);
  14864. };
  14865. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14866. if (atIndices === void 0) { atIndices = null; }
  14867. var result = [];
  14868. var i;
  14869. var index;
  14870. if (!atIndices) {
  14871. var idx = this._postProcesses.indexOf(postProcess);
  14872. if (idx !== -1) {
  14873. this._postProcesses.splice(idx, 1);
  14874. }
  14875. }
  14876. else {
  14877. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14878. // iterate descending, so can just splice as we go
  14879. for (i = atIndices.length - 1; i >= 0; i--) {
  14880. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14881. result.push(i);
  14882. continue;
  14883. }
  14884. index = atIndices[i];
  14885. this._postProcesses.splice(index, 1);
  14886. }
  14887. }
  14888. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14889. return result;
  14890. };
  14891. Camera.prototype.getWorldMatrix = function () {
  14892. if (!this._worldMatrix) {
  14893. this._worldMatrix = BABYLON.Matrix.Identity();
  14894. }
  14895. var viewMatrix = this.getViewMatrix();
  14896. viewMatrix.invertToRef(this._worldMatrix);
  14897. return this._worldMatrix;
  14898. };
  14899. Camera.prototype._getViewMatrix = function () {
  14900. return BABYLON.Matrix.Identity();
  14901. };
  14902. Camera.prototype.getViewMatrix = function (force) {
  14903. if (!force && this._isSynchronizedViewMatrix()) {
  14904. return this._computedViewMatrix;
  14905. }
  14906. this._computedViewMatrix = this._getViewMatrix();
  14907. this._currentRenderId = this.getScene().getRenderId();
  14908. this._refreshFrustumPlanes = true;
  14909. if (!this.parent || !this.parent.getWorldMatrix) {
  14910. this._globalPosition.copyFrom(this.position);
  14911. }
  14912. else {
  14913. if (!this._worldMatrix) {
  14914. this._worldMatrix = BABYLON.Matrix.Identity();
  14915. }
  14916. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14917. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14918. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14919. this._computedViewMatrix.invert();
  14920. this._markSyncedWithParent();
  14921. }
  14922. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14923. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14924. }
  14925. this.onViewMatrixChangedObservable.notifyObservers(this);
  14926. return this._computedViewMatrix;
  14927. };
  14928. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14929. this._doNotComputeProjectionMatrix = true;
  14930. if (projection !== undefined) {
  14931. this._projectionMatrix = projection;
  14932. }
  14933. };
  14934. ;
  14935. Camera.prototype.unfreezeProjectionMatrix = function () {
  14936. this._doNotComputeProjectionMatrix = false;
  14937. };
  14938. ;
  14939. Camera.prototype.getProjectionMatrix = function (force) {
  14940. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14941. return this._projectionMatrix;
  14942. }
  14943. this._refreshFrustumPlanes = true;
  14944. var engine = this.getEngine();
  14945. var scene = this.getScene();
  14946. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14947. if (this.minZ <= 0) {
  14948. this.minZ = 0.1;
  14949. }
  14950. if (scene.useRightHandedSystem) {
  14951. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14952. }
  14953. else {
  14954. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14955. }
  14956. }
  14957. else {
  14958. var halfWidth = engine.getRenderWidth() / 2.0;
  14959. var halfHeight = engine.getRenderHeight() / 2.0;
  14960. if (scene.useRightHandedSystem) {
  14961. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14962. }
  14963. else {
  14964. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14965. }
  14966. }
  14967. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  14968. return this._projectionMatrix;
  14969. };
  14970. Camera.prototype.getTranformationMatrix = function () {
  14971. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14972. return this._transformMatrix;
  14973. };
  14974. Camera.prototype.updateFrustumPlanes = function () {
  14975. if (!this._refreshFrustumPlanes) {
  14976. return;
  14977. }
  14978. this.getTranformationMatrix();
  14979. if (!this._frustumPlanes) {
  14980. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14981. }
  14982. else {
  14983. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14984. }
  14985. this._refreshFrustumPlanes = false;
  14986. };
  14987. Camera.prototype.isInFrustum = function (target) {
  14988. this.updateFrustumPlanes();
  14989. return target.isInFrustum(this._frustumPlanes);
  14990. };
  14991. Camera.prototype.isCompletelyInFrustum = function (target) {
  14992. this.updateFrustumPlanes();
  14993. return target.isCompletelyInFrustum(this._frustumPlanes);
  14994. };
  14995. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14996. if (length === void 0) { length = 100; }
  14997. if (!transform) {
  14998. transform = this.getWorldMatrix();
  14999. }
  15000. if (!origin) {
  15001. origin = this.position;
  15002. }
  15003. var forward = new BABYLON.Vector3(0, 0, 1);
  15004. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15005. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15006. return new BABYLON.Ray(origin, direction, length);
  15007. };
  15008. Camera.prototype.dispose = function () {
  15009. // Observables
  15010. this.onViewMatrixChangedObservable.clear();
  15011. this.onProjectionMatrixChangedObservable.clear();
  15012. this.onAfterCheckInputsObservable.clear();
  15013. // Inputs
  15014. this.inputs.clear();
  15015. // Animations
  15016. this.getScene().stopAnimation(this);
  15017. // Remove from scene
  15018. this.getScene().removeCamera(this);
  15019. while (this._rigCameras.length > 0) {
  15020. this._rigCameras.pop().dispose();
  15021. }
  15022. // Postprocesses
  15023. var i = this._postProcesses.length;
  15024. while (--i >= 0) {
  15025. this._postProcesses[i].dispose(this);
  15026. }
  15027. // Render targets
  15028. var i = this.customRenderTargets.length;
  15029. while (--i >= 0) {
  15030. this.customRenderTargets[i].dispose();
  15031. }
  15032. this.customRenderTargets = [];
  15033. // Active Meshes
  15034. this._activeMeshes.dispose();
  15035. _super.prototype.dispose.call(this);
  15036. };
  15037. Object.defineProperty(Camera.prototype, "leftCamera", {
  15038. // ---- Camera rigs section ----
  15039. get: function () {
  15040. if (this._rigCameras.length < 1) {
  15041. return undefined;
  15042. }
  15043. return this._rigCameras[0];
  15044. },
  15045. enumerable: true,
  15046. configurable: true
  15047. });
  15048. Object.defineProperty(Camera.prototype, "rightCamera", {
  15049. get: function () {
  15050. if (this._rigCameras.length < 2) {
  15051. return undefined;
  15052. }
  15053. return this._rigCameras[1];
  15054. },
  15055. enumerable: true,
  15056. configurable: true
  15057. });
  15058. Camera.prototype.getLeftTarget = function () {
  15059. if (this._rigCameras.length < 1) {
  15060. return undefined;
  15061. }
  15062. return this._rigCameras[0].getTarget();
  15063. };
  15064. Camera.prototype.getRightTarget = function () {
  15065. if (this._rigCameras.length < 2) {
  15066. return undefined;
  15067. }
  15068. return this._rigCameras[1].getTarget();
  15069. };
  15070. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15071. while (this._rigCameras.length > 0) {
  15072. this._rigCameras.pop().dispose();
  15073. }
  15074. this.cameraRigMode = mode;
  15075. this._cameraRigParams = {};
  15076. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15077. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15078. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15079. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15080. // create the rig cameras, unless none
  15081. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15082. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15083. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15084. }
  15085. switch (this.cameraRigMode) {
  15086. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15087. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15088. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15089. break;
  15090. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15091. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15092. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15093. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15094. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15095. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15096. break;
  15097. case Camera.RIG_MODE_VR:
  15098. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15099. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15100. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15101. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15102. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15103. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15104. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15105. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15106. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15107. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15108. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15109. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15110. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15111. if (metrics.compensateDistortion) {
  15112. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15113. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15114. }
  15115. break;
  15116. case Camera.RIG_MODE_WEBVR:
  15117. if (rigParams.vrDisplay) {
  15118. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15119. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15120. //Left eye
  15121. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15122. this._rigCameras[0].setCameraRigParameter("left", true);
  15123. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15124. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15125. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15126. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15127. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15128. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15129. this._rigCameras[0].parent = this;
  15130. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15131. //Right eye
  15132. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15133. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15134. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15135. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15136. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15137. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15138. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15139. this._rigCameras[1].parent = this;
  15140. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15141. }
  15142. break;
  15143. }
  15144. this._cascadePostProcessesToRigCams();
  15145. this.
  15146. update();
  15147. };
  15148. Camera.prototype._getVRProjectionMatrix = function () {
  15149. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15150. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15151. return this._projectionMatrix;
  15152. };
  15153. Camera.prototype._updateCameraRotationMatrix = function () {
  15154. //Here for WebVR
  15155. };
  15156. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15157. //Here for WebVR
  15158. };
  15159. /**
  15160. * This function MUST be overwritten by the different WebVR cameras available.
  15161. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15162. */
  15163. Camera.prototype._getWebVRProjectionMatrix = function () {
  15164. return BABYLON.Matrix.Identity();
  15165. };
  15166. /**
  15167. * This function MUST be overwritten by the different WebVR cameras available.
  15168. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15169. */
  15170. Camera.prototype._getWebVRViewMatrix = function () {
  15171. return BABYLON.Matrix.Identity();
  15172. };
  15173. Camera.prototype.setCameraRigParameter = function (name, value) {
  15174. if (!this._cameraRigParams) {
  15175. this._cameraRigParams = {};
  15176. }
  15177. this._cameraRigParams[name] = value;
  15178. //provisionnally:
  15179. if (name === "interaxialDistance") {
  15180. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15181. }
  15182. };
  15183. /**
  15184. * needs to be overridden by children so sub has required properties to be copied
  15185. */
  15186. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15187. return null;
  15188. };
  15189. /**
  15190. * May need to be overridden by children
  15191. */
  15192. Camera.prototype._updateRigCameras = function () {
  15193. for (var i = 0; i < this._rigCameras.length; i++) {
  15194. this._rigCameras[i].minZ = this.minZ;
  15195. this._rigCameras[i].maxZ = this.maxZ;
  15196. this._rigCameras[i].fov = this.fov;
  15197. }
  15198. // only update viewport when ANAGLYPH
  15199. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15200. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15201. }
  15202. };
  15203. Camera.prototype._setupInputs = function () {
  15204. };
  15205. Camera.prototype.serialize = function () {
  15206. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15207. // Type
  15208. serializationObject.type = this.getClassName();
  15209. // Parent
  15210. if (this.parent) {
  15211. serializationObject.parentId = this.parent.id;
  15212. }
  15213. if (this.inputs) {
  15214. this.inputs.serialize(serializationObject);
  15215. }
  15216. // Animations
  15217. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15218. serializationObject.ranges = this.serializeAnimationRanges();
  15219. return serializationObject;
  15220. };
  15221. Camera.prototype.clone = function (name) {
  15222. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15223. };
  15224. Camera.prototype.getDirection = function (localAxis) {
  15225. var result = BABYLON.Vector3.Zero();
  15226. this.getDirectionToRef(localAxis, result);
  15227. return result;
  15228. };
  15229. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15230. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15231. };
  15232. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15233. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15234. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15235. switch (type) {
  15236. case "ArcRotateCamera":
  15237. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15238. case "DeviceOrientationCamera":
  15239. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15240. case "FollowCamera":
  15241. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15242. case "ArcFollowCamera":
  15243. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15244. case "GamepadCamera":
  15245. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15246. case "TouchCamera":
  15247. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15248. case "VirtualJoysticksCamera":
  15249. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15250. case "WebVRFreeCamera":
  15251. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15252. case "WebVRGamepadCamera":
  15253. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15254. case "VRDeviceOrientationFreeCamera":
  15255. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15256. case "VRDeviceOrientationGamepadCamera":
  15257. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15258. case "AnaglyphArcRotateCamera":
  15259. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15260. case "AnaglyphFreeCamera":
  15261. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15262. case "AnaglyphGamepadCamera":
  15263. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15264. case "AnaglyphUniversalCamera":
  15265. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15266. case "StereoscopicArcRotateCamera":
  15267. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15268. case "StereoscopicFreeCamera":
  15269. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15270. case "StereoscopicGamepadCamera":
  15271. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15272. case "StereoscopicUniversalCamera":
  15273. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15274. case "FreeCamera":// Forcing Universal here
  15275. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15276. default:// Universal Camera is the default value
  15277. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15278. }
  15279. };
  15280. Camera.Parse = function (parsedCamera, scene) {
  15281. var type = parsedCamera.type;
  15282. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15283. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15284. // Parent
  15285. if (parsedCamera.parentId) {
  15286. camera._waitingParentId = parsedCamera.parentId;
  15287. }
  15288. //If camera has an input manager, let it parse inputs settings
  15289. if (camera.inputs) {
  15290. camera.inputs.parse(parsedCamera);
  15291. camera._setupInputs();
  15292. }
  15293. if (camera.setPosition) {
  15294. camera.position.copyFromFloats(0, 0, 0);
  15295. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15296. }
  15297. // Target
  15298. if (parsedCamera.target) {
  15299. if (camera.setTarget) {
  15300. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15301. }
  15302. }
  15303. // Apply 3d rig, when found
  15304. if (parsedCamera.cameraRigMode) {
  15305. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15306. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15307. }
  15308. // Animations
  15309. if (parsedCamera.animations) {
  15310. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15311. var parsedAnimation = parsedCamera.animations[animationIndex];
  15312. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15313. }
  15314. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15315. }
  15316. if (parsedCamera.autoAnimate) {
  15317. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15318. }
  15319. return camera;
  15320. };
  15321. // Statics
  15322. Camera._PERSPECTIVE_CAMERA = 0;
  15323. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15324. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15325. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15326. Camera._RIG_MODE_NONE = 0;
  15327. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15328. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15329. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15330. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15331. Camera._RIG_MODE_VR = 20;
  15332. Camera._RIG_MODE_WEBVR = 21;
  15333. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15334. __decorate([
  15335. BABYLON.serializeAsVector3()
  15336. ], Camera.prototype, "position", void 0);
  15337. __decorate([
  15338. BABYLON.serializeAsVector3()
  15339. ], Camera.prototype, "upVector", void 0);
  15340. __decorate([
  15341. BABYLON.serialize()
  15342. ], Camera.prototype, "orthoLeft", void 0);
  15343. __decorate([
  15344. BABYLON.serialize()
  15345. ], Camera.prototype, "orthoRight", void 0);
  15346. __decorate([
  15347. BABYLON.serialize()
  15348. ], Camera.prototype, "orthoBottom", void 0);
  15349. __decorate([
  15350. BABYLON.serialize()
  15351. ], Camera.prototype, "orthoTop", void 0);
  15352. __decorate([
  15353. BABYLON.serialize()
  15354. ], Camera.prototype, "fov", void 0);
  15355. __decorate([
  15356. BABYLON.serialize()
  15357. ], Camera.prototype, "minZ", void 0);
  15358. __decorate([
  15359. BABYLON.serialize()
  15360. ], Camera.prototype, "maxZ", void 0);
  15361. __decorate([
  15362. BABYLON.serialize()
  15363. ], Camera.prototype, "inertia", void 0);
  15364. __decorate([
  15365. BABYLON.serialize()
  15366. ], Camera.prototype, "mode", void 0);
  15367. __decorate([
  15368. BABYLON.serialize()
  15369. ], Camera.prototype, "layerMask", void 0);
  15370. __decorate([
  15371. BABYLON.serialize()
  15372. ], Camera.prototype, "fovMode", void 0);
  15373. __decorate([
  15374. BABYLON.serialize()
  15375. ], Camera.prototype, "cameraRigMode", void 0);
  15376. __decorate([
  15377. BABYLON.serialize()
  15378. ], Camera.prototype, "interaxialDistance", void 0);
  15379. __decorate([
  15380. BABYLON.serialize()
  15381. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15382. return Camera;
  15383. }(BABYLON.Node));
  15384. BABYLON.Camera = Camera;
  15385. })(BABYLON || (BABYLON = {}));
  15386. //# sourceMappingURL=babylon.camera.js.map
  15387. var BABYLON;
  15388. (function (BABYLON) {
  15389. var RenderingManager = (function () {
  15390. function RenderingManager(scene) {
  15391. this._renderingGroups = new Array();
  15392. this._autoClearDepthStencil = {};
  15393. this._customOpaqueSortCompareFn = {};
  15394. this._customAlphaTestSortCompareFn = {};
  15395. this._customTransparentSortCompareFn = {};
  15396. this._renderinGroupInfo = null;
  15397. this._scene = scene;
  15398. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15399. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15400. }
  15401. }
  15402. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15403. if (depth === void 0) { depth = true; }
  15404. if (stencil === void 0) { stencil = true; }
  15405. if (this._depthStencilBufferAlreadyCleaned) {
  15406. return;
  15407. }
  15408. this._scene.getEngine().clear(null, false, depth, stencil);
  15409. this._depthStencilBufferAlreadyCleaned = true;
  15410. };
  15411. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15412. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15413. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15414. var info = null;
  15415. if (observable) {
  15416. if (!this._renderinGroupInfo) {
  15417. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15418. }
  15419. info = this._renderinGroupInfo;
  15420. info.scene = this._scene;
  15421. info.camera = this._scene.activeCamera;
  15422. }
  15423. // Dispatch sprites
  15424. if (renderSprites) {
  15425. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15426. var manager = this._scene.spriteManagers[index];
  15427. this.dispatchSprites(manager);
  15428. }
  15429. }
  15430. // Render
  15431. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15432. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15433. var renderingGroup = this._renderingGroups[index];
  15434. if (!renderingGroup && !observable)
  15435. continue;
  15436. this._currentIndex = index;
  15437. var renderingGroupMask = 0;
  15438. // Fire PRECLEAR stage
  15439. if (observable) {
  15440. renderingGroupMask = Math.pow(2, index);
  15441. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15442. info.renderingGroupId = index;
  15443. observable.notifyObservers(info, renderingGroupMask);
  15444. }
  15445. // Clear depth/stencil if needed
  15446. if (RenderingManager.AUTOCLEAR) {
  15447. var autoClear = this._autoClearDepthStencil[index];
  15448. if (autoClear && autoClear.autoClear) {
  15449. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15450. }
  15451. }
  15452. if (observable) {
  15453. // Fire PREOPAQUE stage
  15454. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15455. observable.notifyObservers(info, renderingGroupMask);
  15456. // Fire PRETRANSPARENT stage
  15457. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15458. observable.notifyObservers(info, renderingGroupMask);
  15459. }
  15460. if (renderingGroup)
  15461. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15462. // Fire POSTTRANSPARENT stage
  15463. if (observable) {
  15464. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15465. observable.notifyObservers(info, renderingGroupMask);
  15466. }
  15467. }
  15468. };
  15469. RenderingManager.prototype.reset = function () {
  15470. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15471. var renderingGroup = this._renderingGroups[index];
  15472. if (renderingGroup) {
  15473. renderingGroup.prepare();
  15474. }
  15475. }
  15476. };
  15477. RenderingManager.prototype.dispose = function () {
  15478. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15479. var renderingGroup = this._renderingGroups[index];
  15480. if (renderingGroup) {
  15481. renderingGroup.dispose();
  15482. }
  15483. }
  15484. this._renderingGroups.length = 0;
  15485. };
  15486. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15487. if (!this._renderingGroups[renderingGroupId]) {
  15488. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15489. }
  15490. };
  15491. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15492. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15493. this._prepareRenderingGroup(renderingGroupId);
  15494. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15495. };
  15496. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15497. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15498. this._prepareRenderingGroup(renderingGroupId);
  15499. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15500. };
  15501. RenderingManager.prototype.dispatch = function (subMesh) {
  15502. var mesh = subMesh.getMesh();
  15503. var renderingGroupId = mesh.renderingGroupId || 0;
  15504. this._prepareRenderingGroup(renderingGroupId);
  15505. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15506. };
  15507. /**
  15508. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15509. * This allowed control for front to back rendering or reversly depending of the special needs.
  15510. *
  15511. * @param renderingGroupId The rendering group id corresponding to its index
  15512. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15513. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15514. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15515. */
  15516. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15517. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15518. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15519. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15520. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15521. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15522. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15523. if (this._renderingGroups[renderingGroupId]) {
  15524. var group = this._renderingGroups[renderingGroupId];
  15525. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15526. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15527. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15528. }
  15529. };
  15530. /**
  15531. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15532. *
  15533. * @param renderingGroupId The rendering group id corresponding to its index
  15534. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15535. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15536. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15537. */
  15538. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15539. if (depth === void 0) { depth = true; }
  15540. if (stencil === void 0) { stencil = true; }
  15541. this._autoClearDepthStencil[renderingGroupId] = {
  15542. autoClear: autoClearDepthStencil,
  15543. depth: depth,
  15544. stencil: stencil
  15545. };
  15546. };
  15547. /**
  15548. * The max id used for rendering groups (not included)
  15549. */
  15550. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15551. /**
  15552. * The min id used for rendering groups (included)
  15553. */
  15554. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15555. /**
  15556. * Used to globally prevent autoclearing scenes.
  15557. */
  15558. RenderingManager.AUTOCLEAR = true;
  15559. return RenderingManager;
  15560. }());
  15561. BABYLON.RenderingManager = RenderingManager;
  15562. })(BABYLON || (BABYLON = {}));
  15563. //# sourceMappingURL=babylon.renderingManager.js.map
  15564. var BABYLON;
  15565. (function (BABYLON) {
  15566. var RenderingGroup = (function () {
  15567. /**
  15568. * Creates a new rendering group.
  15569. * @param index The rendering group index
  15570. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15571. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15572. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15573. */
  15574. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15575. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15576. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15577. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15578. this.index = index;
  15579. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15580. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15581. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15582. this._particleSystems = new BABYLON.SmartArray(256);
  15583. this._spriteManagers = new BABYLON.SmartArray(256);
  15584. this._edgesRenderers = new BABYLON.SmartArray(16);
  15585. this._scene = scene;
  15586. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15587. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15588. this.transparentSortCompareFn = transparentSortCompareFn;
  15589. }
  15590. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15591. /**
  15592. * Set the opaque sort comparison function.
  15593. * If null the sub meshes will be render in the order they were created
  15594. */
  15595. set: function (value) {
  15596. this._opaqueSortCompareFn = value;
  15597. if (value) {
  15598. this._renderOpaque = this.renderOpaqueSorted;
  15599. }
  15600. else {
  15601. this._renderOpaque = RenderingGroup.renderUnsorted;
  15602. }
  15603. },
  15604. enumerable: true,
  15605. configurable: true
  15606. });
  15607. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15608. /**
  15609. * Set the alpha test sort comparison function.
  15610. * If null the sub meshes will be render in the order they were created
  15611. */
  15612. set: function (value) {
  15613. this._alphaTestSortCompareFn = value;
  15614. if (value) {
  15615. this._renderAlphaTest = this.renderAlphaTestSorted;
  15616. }
  15617. else {
  15618. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15619. }
  15620. },
  15621. enumerable: true,
  15622. configurable: true
  15623. });
  15624. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15625. /**
  15626. * Set the transparent sort comparison function.
  15627. * If null the sub meshes will be render in the order they were created
  15628. */
  15629. set: function (value) {
  15630. if (value) {
  15631. this._transparentSortCompareFn = value;
  15632. }
  15633. else {
  15634. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15635. }
  15636. this._renderTransparent = this.renderTransparentSorted;
  15637. },
  15638. enumerable: true,
  15639. configurable: true
  15640. });
  15641. /**
  15642. * Render all the sub meshes contained in the group.
  15643. * @param customRenderFunction Used to override the default render behaviour of the group.
  15644. * @returns true if rendered some submeshes.
  15645. */
  15646. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15647. if (customRenderFunction) {
  15648. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15649. return;
  15650. }
  15651. var engine = this._scene.getEngine();
  15652. // Opaque
  15653. if (this._opaqueSubMeshes.length !== 0) {
  15654. this._renderOpaque(this._opaqueSubMeshes);
  15655. }
  15656. // Alpha test
  15657. if (this._alphaTestSubMeshes.length !== 0) {
  15658. engine.setAlphaTesting(true);
  15659. this._renderAlphaTest(this._alphaTestSubMeshes);
  15660. engine.setAlphaTesting(false);
  15661. }
  15662. var stencilState = engine.getStencilBuffer();
  15663. engine.setStencilBuffer(false);
  15664. // Sprites
  15665. if (renderSprites) {
  15666. this._renderSprites();
  15667. }
  15668. // Particles
  15669. if (renderParticles) {
  15670. this._renderParticles(activeMeshes);
  15671. }
  15672. if (this.onBeforeTransparentRendering) {
  15673. this.onBeforeTransparentRendering();
  15674. }
  15675. // Transparent
  15676. if (this._transparentSubMeshes.length !== 0) {
  15677. this._renderTransparent(this._transparentSubMeshes);
  15678. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15679. }
  15680. // Set back stencil to false in case it changes before the edge renderer.
  15681. engine.setStencilBuffer(false);
  15682. // Edges
  15683. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15684. this._edgesRenderers.data[edgesRendererIndex].render();
  15685. }
  15686. // Restore Stencil state.
  15687. engine.setStencilBuffer(stencilState);
  15688. };
  15689. /**
  15690. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15691. * @param subMeshes The submeshes to render
  15692. */
  15693. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15694. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15695. };
  15696. /**
  15697. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15698. * @param subMeshes The submeshes to render
  15699. */
  15700. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15701. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15702. };
  15703. /**
  15704. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15705. * @param subMeshes The submeshes to render
  15706. */
  15707. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15708. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15709. };
  15710. /**
  15711. * Renders the submeshes in a specified order.
  15712. * @param subMeshes The submeshes to sort before render
  15713. * @param sortCompareFn The comparison function use to sort
  15714. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15715. * @param transparent Specifies to activate blending if true
  15716. */
  15717. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15718. var subIndex = 0;
  15719. var subMesh;
  15720. for (; subIndex < subMeshes.length; subIndex++) {
  15721. subMesh = subMeshes.data[subIndex];
  15722. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15723. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15724. }
  15725. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15726. sortedArray.sort(sortCompareFn);
  15727. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15728. subMesh = sortedArray[subIndex];
  15729. subMesh.render(transparent);
  15730. }
  15731. };
  15732. /**
  15733. * Renders the submeshes in the order they were dispatched (no sort applied).
  15734. * @param subMeshes The submeshes to render
  15735. */
  15736. RenderingGroup.renderUnsorted = function (subMeshes) {
  15737. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15738. var submesh = subMeshes.data[subIndex];
  15739. submesh.render(false);
  15740. }
  15741. };
  15742. /**
  15743. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15744. * are rendered back to front if in the same alpha index.
  15745. *
  15746. * @param a The first submesh
  15747. * @param b The second submesh
  15748. * @returns The result of the comparison
  15749. */
  15750. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15751. // Alpha index first
  15752. if (a._alphaIndex > b._alphaIndex) {
  15753. return 1;
  15754. }
  15755. if (a._alphaIndex < b._alphaIndex) {
  15756. return -1;
  15757. }
  15758. // Then distance to camera
  15759. return RenderingGroup.backToFrontSortCompare(a, b);
  15760. };
  15761. /**
  15762. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15763. * are rendered back to front.
  15764. *
  15765. * @param a The first submesh
  15766. * @param b The second submesh
  15767. * @returns The result of the comparison
  15768. */
  15769. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15770. // Then distance to camera
  15771. if (a._distanceToCamera < b._distanceToCamera) {
  15772. return 1;
  15773. }
  15774. if (a._distanceToCamera > b._distanceToCamera) {
  15775. return -1;
  15776. }
  15777. return 0;
  15778. };
  15779. /**
  15780. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15781. * are rendered front to back (prevent overdraw).
  15782. *
  15783. * @param a The first submesh
  15784. * @param b The second submesh
  15785. * @returns The result of the comparison
  15786. */
  15787. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15788. // Then distance to camera
  15789. if (a._distanceToCamera < b._distanceToCamera) {
  15790. return -1;
  15791. }
  15792. if (a._distanceToCamera > b._distanceToCamera) {
  15793. return 1;
  15794. }
  15795. return 0;
  15796. };
  15797. /**
  15798. * Resets the different lists of submeshes to prepare a new frame.
  15799. */
  15800. RenderingGroup.prototype.prepare = function () {
  15801. this._opaqueSubMeshes.reset();
  15802. this._transparentSubMeshes.reset();
  15803. this._alphaTestSubMeshes.reset();
  15804. this._particleSystems.reset();
  15805. this._spriteManagers.reset();
  15806. this._edgesRenderers.reset();
  15807. };
  15808. RenderingGroup.prototype.dispose = function () {
  15809. this._opaqueSubMeshes.dispose();
  15810. this._transparentSubMeshes.dispose();
  15811. this._alphaTestSubMeshes.dispose();
  15812. this._particleSystems.dispose();
  15813. this._spriteManagers.dispose();
  15814. this._edgesRenderers.dispose();
  15815. };
  15816. /**
  15817. * Inserts the submesh in its correct queue depending on its material.
  15818. * @param subMesh The submesh to dispatch
  15819. */
  15820. RenderingGroup.prototype.dispatch = function (subMesh) {
  15821. var material = subMesh.getMaterial();
  15822. var mesh = subMesh.getMesh();
  15823. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15824. this._transparentSubMeshes.push(subMesh);
  15825. }
  15826. else if (material.needAlphaTesting()) {
  15827. this._alphaTestSubMeshes.push(subMesh);
  15828. }
  15829. else {
  15830. this._opaqueSubMeshes.push(subMesh); // Opaque
  15831. }
  15832. if (mesh._edgesRenderer) {
  15833. this._edgesRenderers.push(mesh._edgesRenderer);
  15834. }
  15835. };
  15836. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15837. this._spriteManagers.push(spriteManager);
  15838. };
  15839. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15840. this._particleSystems.push(particleSystem);
  15841. };
  15842. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15843. if (this._particleSystems.length === 0) {
  15844. return;
  15845. }
  15846. // Particles
  15847. var activeCamera = this._scene.activeCamera;
  15848. this._scene._particlesDuration.beginMonitoring();
  15849. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15850. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15851. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15852. continue;
  15853. }
  15854. var emitter = particleSystem.emitter;
  15855. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  15856. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15857. }
  15858. }
  15859. this._scene._particlesDuration.endMonitoring(false);
  15860. };
  15861. RenderingGroup.prototype._renderSprites = function () {
  15862. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15863. return;
  15864. }
  15865. // Sprites
  15866. var activeCamera = this._scene.activeCamera;
  15867. this._scene._spritesDuration.beginMonitoring();
  15868. for (var id = 0; id < this._spriteManagers.length; id++) {
  15869. var spriteManager = this._spriteManagers.data[id];
  15870. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15871. spriteManager.render();
  15872. }
  15873. }
  15874. this._scene._spritesDuration.endMonitoring(false);
  15875. };
  15876. return RenderingGroup;
  15877. }());
  15878. BABYLON.RenderingGroup = RenderingGroup;
  15879. })(BABYLON || (BABYLON = {}));
  15880. //# sourceMappingURL=babylon.renderingGroup.js.map
  15881. var BABYLON;
  15882. (function (BABYLON) {
  15883. var ClickInfo = (function () {
  15884. function ClickInfo() {
  15885. this._singleClick = false;
  15886. this._doubleClick = false;
  15887. this._hasSwiped = false;
  15888. this._ignore = false;
  15889. }
  15890. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15891. get: function () {
  15892. return this._singleClick;
  15893. },
  15894. set: function (b) {
  15895. this._singleClick = b;
  15896. },
  15897. enumerable: true,
  15898. configurable: true
  15899. });
  15900. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15901. get: function () {
  15902. return this._doubleClick;
  15903. },
  15904. set: function (b) {
  15905. this._doubleClick = b;
  15906. },
  15907. enumerable: true,
  15908. configurable: true
  15909. });
  15910. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15911. get: function () {
  15912. return this._hasSwiped;
  15913. },
  15914. set: function (b) {
  15915. this._hasSwiped = b;
  15916. },
  15917. enumerable: true,
  15918. configurable: true
  15919. });
  15920. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15921. get: function () {
  15922. return this._ignore;
  15923. },
  15924. set: function (b) {
  15925. this._ignore = b;
  15926. },
  15927. enumerable: true,
  15928. configurable: true
  15929. });
  15930. return ClickInfo;
  15931. }());
  15932. var PointerEventTypes = (function () {
  15933. function PointerEventTypes() {
  15934. }
  15935. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15936. get: function () {
  15937. return PointerEventTypes._POINTERDOWN;
  15938. },
  15939. enumerable: true,
  15940. configurable: true
  15941. });
  15942. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15943. get: function () {
  15944. return PointerEventTypes._POINTERUP;
  15945. },
  15946. enumerable: true,
  15947. configurable: true
  15948. });
  15949. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15950. get: function () {
  15951. return PointerEventTypes._POINTERMOVE;
  15952. },
  15953. enumerable: true,
  15954. configurable: true
  15955. });
  15956. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15957. get: function () {
  15958. return PointerEventTypes._POINTERWHEEL;
  15959. },
  15960. enumerable: true,
  15961. configurable: true
  15962. });
  15963. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15964. get: function () {
  15965. return PointerEventTypes._POINTERPICK;
  15966. },
  15967. enumerable: true,
  15968. configurable: true
  15969. });
  15970. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15971. get: function () {
  15972. return PointerEventTypes._POINTERTAP;
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15978. get: function () {
  15979. return PointerEventTypes._POINTERDOUBLETAP;
  15980. },
  15981. enumerable: true,
  15982. configurable: true
  15983. });
  15984. PointerEventTypes._POINTERDOWN = 0x01;
  15985. PointerEventTypes._POINTERUP = 0x02;
  15986. PointerEventTypes._POINTERMOVE = 0x04;
  15987. PointerEventTypes._POINTERWHEEL = 0x08;
  15988. PointerEventTypes._POINTERPICK = 0x10;
  15989. PointerEventTypes._POINTERTAP = 0x20;
  15990. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15991. return PointerEventTypes;
  15992. }());
  15993. BABYLON.PointerEventTypes = PointerEventTypes;
  15994. var PointerInfoBase = (function () {
  15995. function PointerInfoBase(type, event) {
  15996. this.type = type;
  15997. this.event = event;
  15998. }
  15999. return PointerInfoBase;
  16000. }());
  16001. BABYLON.PointerInfoBase = PointerInfoBase;
  16002. /**
  16003. * This class is used to store pointer related info for the onPrePointerObservable event.
  16004. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16005. */
  16006. var PointerInfoPre = (function (_super) {
  16007. __extends(PointerInfoPre, _super);
  16008. function PointerInfoPre(type, event, localX, localY) {
  16009. var _this = _super.call(this, type, event) || this;
  16010. _this.skipOnPointerObservable = false;
  16011. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16012. return _this;
  16013. }
  16014. return PointerInfoPre;
  16015. }(PointerInfoBase));
  16016. BABYLON.PointerInfoPre = PointerInfoPre;
  16017. /**
  16018. * This type contains all the data related to a pointer event in Babylon.js.
  16019. * 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.
  16020. */
  16021. var PointerInfo = (function (_super) {
  16022. __extends(PointerInfo, _super);
  16023. function PointerInfo(type, event, pickInfo) {
  16024. var _this = _super.call(this, type, event) || this;
  16025. _this.pickInfo = pickInfo;
  16026. return _this;
  16027. }
  16028. return PointerInfo;
  16029. }(PointerInfoBase));
  16030. BABYLON.PointerInfo = PointerInfo;
  16031. /**
  16032. * This class is used by the onRenderingGroupObservable
  16033. */
  16034. var RenderingGroupInfo = (function () {
  16035. function RenderingGroupInfo() {
  16036. }
  16037. /**
  16038. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16039. * This stage will be fired no matter what
  16040. */
  16041. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16042. /**
  16043. * Called before opaque object are rendered.
  16044. * This stage will be fired only if there's 3D Opaque content to render
  16045. */
  16046. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16047. /**
  16048. * Called after the opaque objects are rendered and before the transparent ones
  16049. * This stage will be fired only if there's 3D transparent content to render
  16050. */
  16051. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16052. /**
  16053. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16054. * This stage will be fired no matter what
  16055. */
  16056. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16057. return RenderingGroupInfo;
  16058. }());
  16059. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16060. /**
  16061. * Represents a scene to be rendered by the engine.
  16062. * @see http://doc.babylonjs.com/page.php?p=21911
  16063. */
  16064. var Scene = (function () {
  16065. /**
  16066. * @constructor
  16067. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16068. */
  16069. function Scene(engine) {
  16070. // Members
  16071. this.autoClear = true;
  16072. this.autoClearDepthAndStencil = true;
  16073. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16074. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16075. this.forceWireframe = false;
  16076. this._forcePointsCloud = false;
  16077. this.forceShowBoundingBoxes = false;
  16078. this.animationsEnabled = true;
  16079. this.constantlyUpdateMeshUnderPointer = false;
  16080. this.hoverCursor = "pointer";
  16081. this.defaultCursor = "";
  16082. // Metadata
  16083. this.metadata = null;
  16084. // Events
  16085. /**
  16086. * An event triggered when the scene is disposed.
  16087. * @type {BABYLON.Observable}
  16088. */
  16089. this.onDisposeObservable = new BABYLON.Observable();
  16090. /**
  16091. * An event triggered before rendering the scene
  16092. * @type {BABYLON.Observable}
  16093. */
  16094. this.onBeforeRenderObservable = new BABYLON.Observable();
  16095. /**
  16096. * An event triggered after rendering the scene
  16097. * @type {BABYLON.Observable}
  16098. */
  16099. this.onAfterRenderObservable = new BABYLON.Observable();
  16100. /**
  16101. * An event triggered when the scene is ready
  16102. * @type {BABYLON.Observable}
  16103. */
  16104. this.onReadyObservable = new BABYLON.Observable();
  16105. /**
  16106. * An event triggered before rendering a camera
  16107. * @type {BABYLON.Observable}
  16108. */
  16109. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16110. /**
  16111. * An event triggered after rendering a camera
  16112. * @type {BABYLON.Observable}
  16113. */
  16114. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16115. /**
  16116. * An event triggered when a camera is created
  16117. * @type {BABYLON.Observable}
  16118. */
  16119. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16120. /**
  16121. * An event triggered when a camera is removed
  16122. * @type {BABYLON.Observable}
  16123. */
  16124. this.onCameraRemovedObservable = new BABYLON.Observable();
  16125. /**
  16126. * An event triggered when a light is created
  16127. * @type {BABYLON.Observable}
  16128. */
  16129. this.onNewLightAddedObservable = new BABYLON.Observable();
  16130. /**
  16131. * An event triggered when a light is removed
  16132. * @type {BABYLON.Observable}
  16133. */
  16134. this.onLightRemovedObservable = new BABYLON.Observable();
  16135. /**
  16136. * An event triggered when a geometry is created
  16137. * @type {BABYLON.Observable}
  16138. */
  16139. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16140. /**
  16141. * An event triggered when a geometry is removed
  16142. * @type {BABYLON.Observable}
  16143. */
  16144. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16145. /**
  16146. * An event triggered when a mesh is created
  16147. * @type {BABYLON.Observable}
  16148. */
  16149. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16150. /**
  16151. * An event triggered when a mesh is removed
  16152. * @type {BABYLON.Observable}
  16153. */
  16154. this.onMeshRemovedObservable = new BABYLON.Observable();
  16155. /**
  16156. * An event triggered before calculating deterministic simulation step
  16157. * @type {BABYLON.Observable}
  16158. */
  16159. this.onBeforeStepObservable = new BABYLON.Observable();
  16160. /**
  16161. * An event triggered after calculating deterministic simulation step
  16162. * @type {BABYLON.Observable}
  16163. */
  16164. this.onAfterStepObservable = new BABYLON.Observable();
  16165. /**
  16166. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16167. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16168. * 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)
  16169. */
  16170. this.onRenderingGroupObservable = new BABYLON.Observable();
  16171. // Animations
  16172. this.animations = [];
  16173. /**
  16174. * 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).
  16175. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16176. */
  16177. this.onPrePointerObservable = new BABYLON.Observable();
  16178. /**
  16179. * Observable event triggered each time an input event is received from the rendering canvas
  16180. */
  16181. this.onPointerObservable = new BABYLON.Observable();
  16182. this._meshPickProceed = false;
  16183. this._previousHasSwiped = false;
  16184. this._currentPickResult = null;
  16185. this._previousPickResult = null;
  16186. this._isButtonPressed = false;
  16187. this._doubleClickOccured = false;
  16188. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16189. this.cameraToUseForPointers = null;
  16190. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16191. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16192. this._startingPointerTime = 0;
  16193. this._previousStartingPointerTime = 0;
  16194. // Deterministic lockstep
  16195. this._timeAccumulator = 0;
  16196. this._currentStepId = 0;
  16197. this._currentInternalStep = 0;
  16198. // Coordinate system
  16199. /**
  16200. * use right-handed coordinate system on this scene.
  16201. * @type {boolean}
  16202. */
  16203. this._useRightHandedSystem = false;
  16204. // Fog
  16205. this._fogEnabled = true;
  16206. this._fogMode = Scene.FOGMODE_NONE;
  16207. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16208. this.fogDensity = 0.1;
  16209. this.fogStart = 0;
  16210. this.fogEnd = 1000.0;
  16211. // Lights
  16212. /**
  16213. * is shadow enabled on this scene.
  16214. * @type {boolean}
  16215. */
  16216. this._shadowsEnabled = true;
  16217. /**
  16218. * is light enabled on this scene.
  16219. * @type {boolean}
  16220. */
  16221. this._lightsEnabled = true;
  16222. /**
  16223. * All of the lights added to this scene.
  16224. * @see BABYLON.Light
  16225. * @type {BABYLON.Light[]}
  16226. */
  16227. this.lights = new Array();
  16228. // Cameras
  16229. /** All of the cameras added to this scene. */
  16230. this.cameras = new Array();
  16231. /** All of the active cameras added to this scene. */
  16232. this.activeCameras = new Array();
  16233. // Meshes
  16234. /**
  16235. * All of the (abstract) meshes added to this scene.
  16236. * @see BABYLON.AbstractMesh
  16237. * @type {BABYLON.AbstractMesh[]}
  16238. */
  16239. this.meshes = new Array();
  16240. // Geometries
  16241. this._geometries = new Array();
  16242. this.materials = new Array();
  16243. this.multiMaterials = new Array();
  16244. // Textures
  16245. this._texturesEnabled = true;
  16246. this.textures = new Array();
  16247. // Particles
  16248. this.particlesEnabled = true;
  16249. this.particleSystems = new Array();
  16250. // Sprites
  16251. this.spritesEnabled = true;
  16252. this.spriteManagers = new Array();
  16253. // Layers
  16254. this.layers = new Array();
  16255. this.highlightLayers = new Array();
  16256. // Skeletons
  16257. this._skeletonsEnabled = true;
  16258. this.skeletons = new Array();
  16259. // Morph targets
  16260. this.morphTargetManagers = new Array();
  16261. // Lens flares
  16262. this.lensFlaresEnabled = true;
  16263. this.lensFlareSystems = new Array();
  16264. // Collisions
  16265. this.collisionsEnabled = true;
  16266. /** Defines the gravity applied to this scene */
  16267. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16268. // Postprocesses
  16269. this.postProcessesEnabled = true;
  16270. // Customs render targets
  16271. this.renderTargetsEnabled = true;
  16272. this.dumpNextRenderTargets = false;
  16273. this.customRenderTargets = new Array();
  16274. // Imported meshes
  16275. this.importedMeshesFiles = new Array();
  16276. // Probes
  16277. this.probesEnabled = true;
  16278. this.reflectionProbes = new Array();
  16279. this._actionManagers = new Array();
  16280. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16281. // Procedural textures
  16282. this.proceduralTexturesEnabled = true;
  16283. this._proceduralTextures = new Array();
  16284. this.soundTracks = new Array();
  16285. this._audioEnabled = true;
  16286. this._headphone = false;
  16287. // Performance counters
  16288. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16289. this._totalLightsCounter = new BABYLON.PerfCounter();
  16290. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16291. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16292. this._totalVertices = new BABYLON.PerfCounter();
  16293. this._activeIndices = new BABYLON.PerfCounter();
  16294. this._activeParticles = new BABYLON.PerfCounter();
  16295. this._lastFrameDuration = new BABYLON.PerfCounter();
  16296. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16297. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16298. this._particlesDuration = new BABYLON.PerfCounter();
  16299. this._renderDuration = new BABYLON.PerfCounter();
  16300. this._spritesDuration = new BABYLON.PerfCounter();
  16301. this._activeBones = new BABYLON.PerfCounter();
  16302. this._animationTime = 0;
  16303. this.animationTimeScale = 1;
  16304. this._renderId = 0;
  16305. this._executeWhenReadyTimeoutId = -1;
  16306. this._intermediateRendering = false;
  16307. this._viewUpdateFlag = -1;
  16308. this._projectionUpdateFlag = -1;
  16309. this._toBeDisposed = new BABYLON.SmartArray(256);
  16310. this._pendingData = []; //ANY
  16311. this._activeMeshes = new BABYLON.SmartArray(256);
  16312. this._processedMaterials = new BABYLON.SmartArray(256);
  16313. this._renderTargets = new BABYLON.SmartArray(256);
  16314. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16315. this._activeSkeletons = new BABYLON.SmartArray(32);
  16316. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16317. this._activeAnimatables = new Array();
  16318. this._transformMatrix = BABYLON.Matrix.Zero();
  16319. this.requireLightSorting = false;
  16320. this._uniqueIdCounter = 0;
  16321. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16322. this._engine.scenes.push(this);
  16323. this._uid = null;
  16324. this._renderingManager = new BABYLON.RenderingManager(this);
  16325. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16326. if (BABYLON.OutlineRenderer) {
  16327. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16328. }
  16329. this.attachControl();
  16330. if (BABYLON.SoundTrack) {
  16331. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16332. }
  16333. //simplification queue
  16334. if (BABYLON.SimplificationQueue) {
  16335. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16336. }
  16337. //collision coordinator initialization. For now legacy per default.
  16338. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16339. // Uniform Buffer
  16340. this._createUbo();
  16341. // Default Image processing definition.
  16342. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16343. }
  16344. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16345. /** The fog is deactivated */
  16346. get: function () {
  16347. return Scene._FOGMODE_NONE;
  16348. },
  16349. enumerable: true,
  16350. configurable: true
  16351. });
  16352. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16353. /** The fog density is following an exponential function */
  16354. get: function () {
  16355. return Scene._FOGMODE_EXP;
  16356. },
  16357. enumerable: true,
  16358. configurable: true
  16359. });
  16360. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16361. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16362. get: function () {
  16363. return Scene._FOGMODE_EXP2;
  16364. },
  16365. enumerable: true,
  16366. configurable: true
  16367. });
  16368. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16369. /** The fog density is following a linear function. */
  16370. get: function () {
  16371. return Scene._FOGMODE_LINEAR;
  16372. },
  16373. enumerable: true,
  16374. configurable: true
  16375. });
  16376. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16377. /**
  16378. * Texture used in all pbr material as the reflection texture.
  16379. * As in the majority of the scene they are the same (exception for multi room and so on),
  16380. * this is easier to reference from here than from all the materials.
  16381. */
  16382. get: function () {
  16383. return this._environmentTexture;
  16384. },
  16385. /**
  16386. * Texture used in all pbr material as the reflection texture.
  16387. * As in the majority of the scene they are the same (exception for multi room and so on),
  16388. * this is easier to set here than in all the materials.
  16389. */
  16390. set: function (value) {
  16391. this._environmentTexture = value;
  16392. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16393. },
  16394. enumerable: true,
  16395. configurable: true
  16396. });
  16397. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16398. /**
  16399. * Default image processing configuration used either in the rendering
  16400. * Forward main pass or through the imageProcessingPostProcess if present.
  16401. * As in the majority of the scene they are the same (exception for multi camera),
  16402. * this is easier to reference from here than from all the materials and post process.
  16403. *
  16404. * No setter as we it is a shared configuration, you can set the values instead.
  16405. */
  16406. get: function () {
  16407. return this._imageProcessingConfiguration;
  16408. },
  16409. enumerable: true,
  16410. configurable: true
  16411. });
  16412. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16413. get: function () {
  16414. return this._forcePointsCloud;
  16415. },
  16416. set: function (value) {
  16417. if (this._forcePointsCloud === value) {
  16418. return;
  16419. }
  16420. this._forcePointsCloud = value;
  16421. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16422. },
  16423. enumerable: true,
  16424. configurable: true
  16425. });
  16426. Object.defineProperty(Scene.prototype, "onDispose", {
  16427. /** A function to be executed when this scene is disposed. */
  16428. set: function (callback) {
  16429. if (this._onDisposeObserver) {
  16430. this.onDisposeObservable.remove(this._onDisposeObserver);
  16431. }
  16432. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16433. },
  16434. enumerable: true,
  16435. configurable: true
  16436. });
  16437. Object.defineProperty(Scene.prototype, "beforeRender", {
  16438. /** A function to be executed before rendering this scene */
  16439. set: function (callback) {
  16440. if (this._onBeforeRenderObserver) {
  16441. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16442. }
  16443. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16444. },
  16445. enumerable: true,
  16446. configurable: true
  16447. });
  16448. Object.defineProperty(Scene.prototype, "afterRender", {
  16449. /** A function to be executed after rendering this scene */
  16450. set: function (callback) {
  16451. if (this._onAfterRenderObserver) {
  16452. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16453. }
  16454. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16455. },
  16456. enumerable: true,
  16457. configurable: true
  16458. });
  16459. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16460. set: function (callback) {
  16461. if (this._onBeforeCameraRenderObserver) {
  16462. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16463. }
  16464. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16465. },
  16466. enumerable: true,
  16467. configurable: true
  16468. });
  16469. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16470. set: function (callback) {
  16471. if (this._onAfterCameraRenderObserver) {
  16472. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16473. }
  16474. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16475. },
  16476. enumerable: true,
  16477. configurable: true
  16478. });
  16479. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16480. get: function () {
  16481. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16482. },
  16483. enumerable: true,
  16484. configurable: true
  16485. });
  16486. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16487. get: function () {
  16488. return this._useRightHandedSystem;
  16489. },
  16490. set: function (value) {
  16491. if (this._useRightHandedSystem === value) {
  16492. return;
  16493. }
  16494. this._useRightHandedSystem = value;
  16495. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16496. },
  16497. enumerable: true,
  16498. configurable: true
  16499. });
  16500. Scene.prototype.setStepId = function (newStepId) {
  16501. this._currentStepId = newStepId;
  16502. };
  16503. ;
  16504. Scene.prototype.getStepId = function () {
  16505. return this._currentStepId;
  16506. };
  16507. ;
  16508. Scene.prototype.getInternalStep = function () {
  16509. return this._currentInternalStep;
  16510. };
  16511. ;
  16512. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16513. get: function () {
  16514. return this._fogEnabled;
  16515. },
  16516. /**
  16517. * is fog enabled on this scene.
  16518. */
  16519. set: function (value) {
  16520. if (this._fogEnabled === value) {
  16521. return;
  16522. }
  16523. this._fogEnabled = value;
  16524. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16525. },
  16526. enumerable: true,
  16527. configurable: true
  16528. });
  16529. Object.defineProperty(Scene.prototype, "fogMode", {
  16530. get: function () {
  16531. return this._fogMode;
  16532. },
  16533. set: function (value) {
  16534. if (this._fogMode === value) {
  16535. return;
  16536. }
  16537. this._fogMode = value;
  16538. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16539. },
  16540. enumerable: true,
  16541. configurable: true
  16542. });
  16543. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16544. get: function () {
  16545. return this._shadowsEnabled;
  16546. },
  16547. set: function (value) {
  16548. if (this._shadowsEnabled === value) {
  16549. return;
  16550. }
  16551. this._shadowsEnabled = value;
  16552. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16553. },
  16554. enumerable: true,
  16555. configurable: true
  16556. });
  16557. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16558. get: function () {
  16559. return this._lightsEnabled;
  16560. },
  16561. set: function (value) {
  16562. if (this._lightsEnabled === value) {
  16563. return;
  16564. }
  16565. this._lightsEnabled = value;
  16566. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16567. },
  16568. enumerable: true,
  16569. configurable: true
  16570. });
  16571. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16572. /** The default material used on meshes when no material is affected */
  16573. get: function () {
  16574. if (!this._defaultMaterial) {
  16575. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16576. }
  16577. return this._defaultMaterial;
  16578. },
  16579. /** The default material used on meshes when no material is affected */
  16580. set: function (value) {
  16581. this._defaultMaterial = value;
  16582. },
  16583. enumerable: true,
  16584. configurable: true
  16585. });
  16586. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16587. get: function () {
  16588. return this._texturesEnabled;
  16589. },
  16590. set: function (value) {
  16591. if (this._texturesEnabled === value) {
  16592. return;
  16593. }
  16594. this._texturesEnabled = value;
  16595. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16596. },
  16597. enumerable: true,
  16598. configurable: true
  16599. });
  16600. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16601. get: function () {
  16602. return this._skeletonsEnabled;
  16603. },
  16604. set: function (value) {
  16605. if (this._skeletonsEnabled === value) {
  16606. return;
  16607. }
  16608. this._skeletonsEnabled = value;
  16609. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16610. },
  16611. enumerable: true,
  16612. configurable: true
  16613. });
  16614. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16615. get: function () {
  16616. if (!this._postProcessRenderPipelineManager) {
  16617. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16618. }
  16619. return this._postProcessRenderPipelineManager;
  16620. },
  16621. enumerable: true,
  16622. configurable: true
  16623. });
  16624. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16625. get: function () {
  16626. return this._frustumPlanes;
  16627. },
  16628. enumerable: true,
  16629. configurable: true
  16630. });
  16631. Object.defineProperty(Scene.prototype, "debugLayer", {
  16632. // Properties
  16633. get: function () {
  16634. if (!this._debugLayer) {
  16635. this._debugLayer = new BABYLON.DebugLayer(this);
  16636. }
  16637. return this._debugLayer;
  16638. },
  16639. enumerable: true,
  16640. configurable: true
  16641. });
  16642. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16643. get: function () {
  16644. return this._workerCollisions;
  16645. },
  16646. set: function (enabled) {
  16647. if (!BABYLON.CollisionCoordinatorLegacy) {
  16648. return;
  16649. }
  16650. enabled = (enabled && !!Worker);
  16651. this._workerCollisions = enabled;
  16652. if (this.collisionCoordinator) {
  16653. this.collisionCoordinator.destroy();
  16654. }
  16655. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16656. this.collisionCoordinator.init(this);
  16657. },
  16658. enumerable: true,
  16659. configurable: true
  16660. });
  16661. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16662. get: function () {
  16663. return this._selectionOctree;
  16664. },
  16665. enumerable: true,
  16666. configurable: true
  16667. });
  16668. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16669. /**
  16670. * The mesh that is currently under the pointer.
  16671. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16672. */
  16673. get: function () {
  16674. return this._pointerOverMesh;
  16675. },
  16676. enumerable: true,
  16677. configurable: true
  16678. });
  16679. Object.defineProperty(Scene.prototype, "pointerX", {
  16680. /**
  16681. * Current on-screen X position of the pointer
  16682. * @return {number} X position of the pointer
  16683. */
  16684. get: function () {
  16685. return this._pointerX;
  16686. },
  16687. enumerable: true,
  16688. configurable: true
  16689. });
  16690. Object.defineProperty(Scene.prototype, "pointerY", {
  16691. /**
  16692. * Current on-screen Y position of the pointer
  16693. * @return {number} Y position of the pointer
  16694. */
  16695. get: function () {
  16696. return this._pointerY;
  16697. },
  16698. enumerable: true,
  16699. configurable: true
  16700. });
  16701. Scene.prototype.getCachedMaterial = function () {
  16702. return this._cachedMaterial;
  16703. };
  16704. Scene.prototype.getCachedEffect = function () {
  16705. return this._cachedEffect;
  16706. };
  16707. Scene.prototype.getCachedVisibility = function () {
  16708. return this._cachedVisibility;
  16709. };
  16710. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16711. if (visibility === void 0) { visibility = 1; }
  16712. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16713. };
  16714. Scene.prototype.getBoundingBoxRenderer = function () {
  16715. if (!this._boundingBoxRenderer) {
  16716. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16717. }
  16718. return this._boundingBoxRenderer;
  16719. };
  16720. Scene.prototype.getOutlineRenderer = function () {
  16721. return this._outlineRenderer;
  16722. };
  16723. Scene.prototype.getEngine = function () {
  16724. return this._engine;
  16725. };
  16726. Scene.prototype.getTotalVertices = function () {
  16727. return this._totalVertices.current;
  16728. };
  16729. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16730. get: function () {
  16731. return this._totalVertices;
  16732. },
  16733. enumerable: true,
  16734. configurable: true
  16735. });
  16736. Scene.prototype.getActiveIndices = function () {
  16737. return this._activeIndices.current;
  16738. };
  16739. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16740. get: function () {
  16741. return this._activeIndices;
  16742. },
  16743. enumerable: true,
  16744. configurable: true
  16745. });
  16746. Scene.prototype.getActiveParticles = function () {
  16747. return this._activeParticles.current;
  16748. };
  16749. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16750. get: function () {
  16751. return this._activeParticles;
  16752. },
  16753. enumerable: true,
  16754. configurable: true
  16755. });
  16756. Scene.prototype.getActiveBones = function () {
  16757. return this._activeBones.current;
  16758. };
  16759. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16760. get: function () {
  16761. return this._activeBones;
  16762. },
  16763. enumerable: true,
  16764. configurable: true
  16765. });
  16766. // Stats
  16767. Scene.prototype.getLastFrameDuration = function () {
  16768. return this._lastFrameDuration.current;
  16769. };
  16770. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16771. get: function () {
  16772. return this._lastFrameDuration;
  16773. },
  16774. enumerable: true,
  16775. configurable: true
  16776. });
  16777. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16778. return this._evaluateActiveMeshesDuration.current;
  16779. };
  16780. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16781. get: function () {
  16782. return this._evaluateActiveMeshesDuration;
  16783. },
  16784. enumerable: true,
  16785. configurable: true
  16786. });
  16787. Scene.prototype.getActiveMeshes = function () {
  16788. return this._activeMeshes;
  16789. };
  16790. Scene.prototype.getRenderTargetsDuration = function () {
  16791. return this._renderTargetsDuration.current;
  16792. };
  16793. Scene.prototype.getRenderDuration = function () {
  16794. return this._renderDuration.current;
  16795. };
  16796. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16797. get: function () {
  16798. return this._renderDuration;
  16799. },
  16800. enumerable: true,
  16801. configurable: true
  16802. });
  16803. Scene.prototype.getParticlesDuration = function () {
  16804. return this._particlesDuration.current;
  16805. };
  16806. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16807. get: function () {
  16808. return this._particlesDuration;
  16809. },
  16810. enumerable: true,
  16811. configurable: true
  16812. });
  16813. Scene.prototype.getSpritesDuration = function () {
  16814. return this._spritesDuration.current;
  16815. };
  16816. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16817. get: function () {
  16818. return this._spritesDuration;
  16819. },
  16820. enumerable: true,
  16821. configurable: true
  16822. });
  16823. Scene.prototype.getAnimationRatio = function () {
  16824. return this._animationRatio;
  16825. };
  16826. Scene.prototype.getRenderId = function () {
  16827. return this._renderId;
  16828. };
  16829. Scene.prototype.incrementRenderId = function () {
  16830. this._renderId++;
  16831. };
  16832. Scene.prototype._updatePointerPosition = function (evt) {
  16833. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16834. this._pointerX = evt.clientX - canvasRect.left;
  16835. this._pointerY = evt.clientY - canvasRect.top;
  16836. this._unTranslatedPointerX = this._pointerX;
  16837. this._unTranslatedPointerY = this._pointerY;
  16838. };
  16839. Scene.prototype._createUbo = function () {
  16840. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16841. this._sceneUbo.addUniform("viewProjection", 16);
  16842. this._sceneUbo.addUniform("view", 16);
  16843. };
  16844. // Pointers handling
  16845. /**
  16846. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16847. * @param attachUp defines if you want to attach events to pointerup
  16848. * @param attachDown defines if you want to attach events to pointerdown
  16849. * @param attachMove defines if you want to attach events to pointermove
  16850. */
  16851. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16852. var _this = this;
  16853. if (attachUp === void 0) { attachUp = true; }
  16854. if (attachDown === void 0) { attachDown = true; }
  16855. if (attachMove === void 0) { attachMove = true; }
  16856. this._initActionManager = function (act, clickInfo) {
  16857. if (!_this._meshPickProceed) {
  16858. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16859. _this._currentPickResult = pickResult;
  16860. if (pickResult) {
  16861. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16862. }
  16863. _this._meshPickProceed = true;
  16864. }
  16865. return act;
  16866. };
  16867. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16868. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16869. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16870. btn !== _this._previousButtonPressed) {
  16871. _this._doubleClickOccured = false;
  16872. clickInfo.singleClick = true;
  16873. clickInfo.ignore = false;
  16874. cb(clickInfo, _this._currentPickResult);
  16875. }
  16876. };
  16877. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16878. var clickInfo = new ClickInfo();
  16879. _this._currentPickResult = null;
  16880. var act;
  16881. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16882. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16883. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16884. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16885. act = _this._initActionManager(act, clickInfo);
  16886. if (act)
  16887. checkPicking = act.hasPickTriggers;
  16888. }
  16889. if (checkPicking) {
  16890. var btn = evt.button;
  16891. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16892. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16893. if (!clickInfo.hasSwiped) {
  16894. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16895. if (!checkSingleClickImmediately) {
  16896. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16897. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16898. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16899. act = _this._initActionManager(act, clickInfo);
  16900. if (act)
  16901. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16902. }
  16903. }
  16904. if (checkSingleClickImmediately) {
  16905. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16906. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16907. btn !== _this._previousButtonPressed) {
  16908. clickInfo.singleClick = true;
  16909. cb(clickInfo, _this._currentPickResult);
  16910. }
  16911. }
  16912. else {
  16913. // wait that no double click has been raised during the double click delay
  16914. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16915. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16916. }
  16917. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16918. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16919. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16920. act = _this._initActionManager(act, clickInfo);
  16921. if (act)
  16922. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16923. }
  16924. if (checkDoubleClick) {
  16925. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16926. if (btn === _this._previousButtonPressed &&
  16927. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16928. !_this._doubleClickOccured) {
  16929. // pointer has not moved for 2 clicks, it's a double click
  16930. if (!clickInfo.hasSwiped &&
  16931. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16932. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16933. _this._previousStartingPointerTime = 0;
  16934. _this._doubleClickOccured = true;
  16935. clickInfo.doubleClick = true;
  16936. clickInfo.ignore = false;
  16937. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16938. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16939. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16940. cb(clickInfo, _this._currentPickResult);
  16941. }
  16942. else {
  16943. _this._doubleClickOccured = false;
  16944. _this._previousStartingPointerTime = _this._startingPointerTime;
  16945. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16946. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16947. _this._previousButtonPressed = btn;
  16948. _this._previousHasSwiped = clickInfo.hasSwiped;
  16949. if (Scene.ExclusiveDoubleClickMode) {
  16950. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16951. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16952. }
  16953. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16954. cb(clickInfo, _this._previousPickResult);
  16955. }
  16956. else {
  16957. cb(clickInfo, _this._currentPickResult);
  16958. }
  16959. }
  16960. }
  16961. else {
  16962. _this._doubleClickOccured = false;
  16963. _this._previousStartingPointerTime = _this._startingPointerTime;
  16964. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16965. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16966. _this._previousButtonPressed = btn;
  16967. _this._previousHasSwiped = clickInfo.hasSwiped;
  16968. }
  16969. }
  16970. }
  16971. }
  16972. clickInfo.ignore = true;
  16973. cb(clickInfo, _this._currentPickResult);
  16974. };
  16975. var spritePredicate = function (sprite) {
  16976. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16977. };
  16978. this._onPointerMove = function (evt) {
  16979. _this._updatePointerPosition(evt);
  16980. // PreObservable support
  16981. if (_this.onPrePointerObservable.hasObservers()) {
  16982. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16983. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16984. _this.onPrePointerObservable.notifyObservers(pi, type);
  16985. if (pi.skipOnPointerObservable) {
  16986. return;
  16987. }
  16988. }
  16989. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16990. return;
  16991. }
  16992. var canvas = _this._engine.getRenderingCanvas();
  16993. if (!_this.pointerMovePredicate) {
  16994. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16995. }
  16996. // Meshes
  16997. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16998. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16999. _this.setPointerOverSprite(null);
  17000. _this.setPointerOverMesh(pickResult.pickedMesh);
  17001. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17002. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17003. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17004. }
  17005. else {
  17006. canvas.style.cursor = _this.hoverCursor;
  17007. }
  17008. }
  17009. else {
  17010. canvas.style.cursor = _this.defaultCursor;
  17011. }
  17012. }
  17013. else {
  17014. _this.setPointerOverMesh(null);
  17015. // Sprites
  17016. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17017. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17018. _this.setPointerOverSprite(pickResult.pickedSprite);
  17019. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17020. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17021. }
  17022. else {
  17023. canvas.style.cursor = _this.hoverCursor;
  17024. }
  17025. }
  17026. else {
  17027. _this.setPointerOverSprite(null);
  17028. // Restore pointer
  17029. canvas.style.cursor = _this.defaultCursor;
  17030. }
  17031. }
  17032. if (_this.onPointerMove) {
  17033. _this.onPointerMove(evt, pickResult);
  17034. }
  17035. if (_this.onPointerObservable.hasObservers()) {
  17036. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17037. var pi = new PointerInfo(type, evt, pickResult);
  17038. _this.onPointerObservable.notifyObservers(pi, type);
  17039. }
  17040. };
  17041. this._onPointerDown = function (evt) {
  17042. _this._isButtonPressed = true;
  17043. _this._pickedDownMesh = null;
  17044. _this._meshPickProceed = false;
  17045. _this._updatePointerPosition(evt);
  17046. // PreObservable support
  17047. if (_this.onPrePointerObservable.hasObservers()) {
  17048. var type = PointerEventTypes.POINTERDOWN;
  17049. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17050. _this.onPrePointerObservable.notifyObservers(pi, type);
  17051. if (pi.skipOnPointerObservable) {
  17052. return;
  17053. }
  17054. }
  17055. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17056. return;
  17057. }
  17058. _this._startingPointerPosition.x = _this._pointerX;
  17059. _this._startingPointerPosition.y = _this._pointerY;
  17060. _this._startingPointerTime = new Date().getTime();
  17061. if (!_this.pointerDownPredicate) {
  17062. _this.pointerDownPredicate = function (mesh) {
  17063. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17064. };
  17065. }
  17066. // Meshes
  17067. _this._pickedDownMesh = null;
  17068. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17069. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17070. _this._pickedDownMesh = pickResult.pickedMesh;
  17071. var actionManager = pickResult.pickedMesh.actionManager;
  17072. if (actionManager) {
  17073. if (actionManager.hasPickTriggers) {
  17074. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17075. switch (evt.button) {
  17076. case 0:
  17077. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17078. break;
  17079. case 1:
  17080. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17081. break;
  17082. case 2:
  17083. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17084. break;
  17085. }
  17086. }
  17087. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17088. window.setTimeout((function () {
  17089. var _this = this;
  17090. 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);
  17091. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17092. if (this._isButtonPressed &&
  17093. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17094. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17095. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17096. this._startingPointerTime = 0;
  17097. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17098. }
  17099. }
  17100. }).bind(_this), Scene.LongPressDelay);
  17101. }
  17102. }
  17103. }
  17104. if (_this.onPointerDown) {
  17105. _this.onPointerDown(evt, pickResult);
  17106. }
  17107. if (_this.onPointerObservable.hasObservers()) {
  17108. var type = PointerEventTypes.POINTERDOWN;
  17109. var pi = new PointerInfo(type, evt, pickResult);
  17110. _this.onPointerObservable.notifyObservers(pi, type);
  17111. }
  17112. // Sprites
  17113. _this._pickedDownSprite = null;
  17114. if (_this.spriteManagers.length > 0) {
  17115. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17116. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17117. if (pickResult.pickedSprite.actionManager) {
  17118. _this._pickedDownSprite = pickResult.pickedSprite;
  17119. switch (evt.button) {
  17120. case 0:
  17121. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17122. break;
  17123. case 1:
  17124. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17125. break;
  17126. case 2:
  17127. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17128. break;
  17129. }
  17130. if (pickResult.pickedSprite.actionManager) {
  17131. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17132. }
  17133. }
  17134. }
  17135. }
  17136. };
  17137. this._onPointerUp = function (evt) {
  17138. _this._isButtonPressed = false;
  17139. _this._pickedUpMesh = null;
  17140. _this._meshPickProceed = false;
  17141. _this._updatePointerPosition(evt);
  17142. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17143. // PreObservable support
  17144. if (this.onPrePointerObservable.hasObservers()) {
  17145. if (!clickInfo.ignore) {
  17146. if (!clickInfo.hasSwiped) {
  17147. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17148. var type = PointerEventTypes.POINTERTAP;
  17149. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17150. this.onPrePointerObservable.notifyObservers(pi, type);
  17151. if (pi.skipOnPointerObservable) {
  17152. return;
  17153. }
  17154. }
  17155. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17156. var type = PointerEventTypes.POINTERDOUBLETAP;
  17157. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17158. this.onPrePointerObservable.notifyObservers(pi, type);
  17159. if (pi.skipOnPointerObservable) {
  17160. return;
  17161. }
  17162. }
  17163. }
  17164. }
  17165. else {
  17166. var type = PointerEventTypes.POINTERUP;
  17167. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17168. this.onPrePointerObservable.notifyObservers(pi, type);
  17169. if (pi.skipOnPointerObservable) {
  17170. return;
  17171. }
  17172. }
  17173. }
  17174. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17175. return;
  17176. }
  17177. if (!this.pointerUpPredicate) {
  17178. this.pointerUpPredicate = function (mesh) {
  17179. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17180. };
  17181. }
  17182. // Meshes
  17183. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17184. this._initActionManager(null, clickInfo);
  17185. }
  17186. if (!pickResult) {
  17187. pickResult = this._currentPickResult;
  17188. }
  17189. if (pickResult && pickResult && pickResult.pickedMesh) {
  17190. this._pickedUpMesh = pickResult.pickedMesh;
  17191. if (this._pickedDownMesh === this._pickedUpMesh) {
  17192. if (this.onPointerPick) {
  17193. this.onPointerPick(evt, pickResult);
  17194. }
  17195. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17196. var type = PointerEventTypes.POINTERPICK;
  17197. var pi = new PointerInfo(type, evt, pickResult);
  17198. this.onPointerObservable.notifyObservers(pi, type);
  17199. }
  17200. }
  17201. if (pickResult.pickedMesh.actionManager) {
  17202. if (clickInfo.ignore) {
  17203. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17204. }
  17205. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17206. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17207. }
  17208. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17209. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17210. }
  17211. }
  17212. }
  17213. if (this._pickedDownMesh &&
  17214. this._pickedDownMesh.actionManager &&
  17215. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17216. this._pickedDownMesh !== this._pickedUpMesh) {
  17217. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17218. }
  17219. if (this.onPointerUp) {
  17220. this.onPointerUp(evt, pickResult);
  17221. }
  17222. if (this.onPointerObservable.hasObservers()) {
  17223. if (!clickInfo.ignore) {
  17224. if (!clickInfo.hasSwiped) {
  17225. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17226. var type = PointerEventTypes.POINTERTAP;
  17227. var pi = new PointerInfo(type, evt, pickResult);
  17228. this.onPointerObservable.notifyObservers(pi, type);
  17229. }
  17230. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17231. var type = PointerEventTypes.POINTERDOUBLETAP;
  17232. var pi = new PointerInfo(type, evt, pickResult);
  17233. this.onPointerObservable.notifyObservers(pi, type);
  17234. }
  17235. }
  17236. }
  17237. else {
  17238. var type = PointerEventTypes.POINTERUP;
  17239. var pi = new PointerInfo(type, evt, pickResult);
  17240. this.onPointerObservable.notifyObservers(pi, type);
  17241. }
  17242. }
  17243. // Sprites
  17244. if (this.spriteManagers.length > 0) {
  17245. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17246. if (pickResult.hit && pickResult.pickedSprite) {
  17247. if (pickResult.pickedSprite.actionManager) {
  17248. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17249. if (pickResult.pickedSprite.actionManager) {
  17250. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17251. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17252. }
  17253. }
  17254. }
  17255. }
  17256. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17257. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17258. }
  17259. }
  17260. this._previousPickResult = this._currentPickResult;
  17261. }).bind(_this));
  17262. };
  17263. this._onKeyDown = function (evt) {
  17264. if (_this.actionManager) {
  17265. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17266. }
  17267. };
  17268. this._onKeyUp = function (evt) {
  17269. if (_this.actionManager) {
  17270. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17271. }
  17272. };
  17273. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17274. var canvas = this._engine.getRenderingCanvas();
  17275. if (attachMove) {
  17276. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17277. // Wheel
  17278. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17279. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17280. }
  17281. if (attachDown) {
  17282. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17283. }
  17284. if (attachUp) {
  17285. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17286. }
  17287. canvas.tabIndex = 1;
  17288. canvas.addEventListener("keydown", this._onKeyDown, false);
  17289. canvas.addEventListener("keyup", this._onKeyUp, false);
  17290. };
  17291. Scene.prototype.detachControl = function () {
  17292. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17293. var canvas = this._engine.getRenderingCanvas();
  17294. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17295. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17296. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17297. // Wheel
  17298. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17299. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17300. canvas.removeEventListener("keydown", this._onKeyDown);
  17301. canvas.removeEventListener("keyup", this._onKeyUp);
  17302. };
  17303. // Ready
  17304. Scene.prototype.isReady = function () {
  17305. if (this._pendingData.length > 0) {
  17306. return false;
  17307. }
  17308. var index;
  17309. // Geometries
  17310. for (index = 0; index < this._geometries.length; index++) {
  17311. var geometry = this._geometries[index];
  17312. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17313. return false;
  17314. }
  17315. }
  17316. // Meshes
  17317. for (index = 0; index < this.meshes.length; index++) {
  17318. var mesh = this.meshes[index];
  17319. if (!mesh.isEnabled()) {
  17320. continue;
  17321. }
  17322. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17323. continue;
  17324. }
  17325. if (!mesh.isReady()) {
  17326. return false;
  17327. }
  17328. var mat = mesh.material;
  17329. if (mat) {
  17330. if (!mat.isReady(mesh)) {
  17331. return false;
  17332. }
  17333. }
  17334. }
  17335. return true;
  17336. };
  17337. Scene.prototype.resetCachedMaterial = function () {
  17338. this._cachedMaterial = null;
  17339. this._cachedEffect = null;
  17340. this._cachedVisibility = null;
  17341. };
  17342. Scene.prototype.registerBeforeRender = function (func) {
  17343. this.onBeforeRenderObservable.add(func);
  17344. };
  17345. Scene.prototype.unregisterBeforeRender = function (func) {
  17346. this.onBeforeRenderObservable.removeCallback(func);
  17347. };
  17348. Scene.prototype.registerAfterRender = function (func) {
  17349. this.onAfterRenderObservable.add(func);
  17350. };
  17351. Scene.prototype.unregisterAfterRender = function (func) {
  17352. this.onAfterRenderObservable.removeCallback(func);
  17353. };
  17354. Scene.prototype._addPendingData = function (data) {
  17355. this._pendingData.push(data);
  17356. };
  17357. Scene.prototype._removePendingData = function (data) {
  17358. var index = this._pendingData.indexOf(data);
  17359. if (index !== -1) {
  17360. this._pendingData.splice(index, 1);
  17361. }
  17362. };
  17363. Scene.prototype.getWaitingItemsCount = function () {
  17364. return this._pendingData.length;
  17365. };
  17366. /**
  17367. * Registers a function to be executed when the scene is ready.
  17368. * @param {Function} func - the function to be executed.
  17369. */
  17370. Scene.prototype.executeWhenReady = function (func) {
  17371. var _this = this;
  17372. this.onReadyObservable.add(func);
  17373. if (this._executeWhenReadyTimeoutId !== -1) {
  17374. return;
  17375. }
  17376. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17377. _this._checkIsReady();
  17378. }, 150);
  17379. };
  17380. Scene.prototype._checkIsReady = function () {
  17381. var _this = this;
  17382. if (this.isReady()) {
  17383. this.onReadyObservable.notifyObservers(this);
  17384. this.onReadyObservable.clear();
  17385. this._executeWhenReadyTimeoutId = -1;
  17386. return;
  17387. }
  17388. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17389. _this._checkIsReady();
  17390. }, 150);
  17391. };
  17392. // Animations
  17393. /**
  17394. * Will start the animation sequence of a given target
  17395. * @param target - the target
  17396. * @param {number} from - from which frame should animation start
  17397. * @param {number} to - till which frame should animation run.
  17398. * @param {boolean} [loop] - should the animation loop
  17399. * @param {number} [speedRatio] - the speed in which to run the animation
  17400. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17401. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17402. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17403. * See BABYLON.Animatable
  17404. */
  17405. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17406. if (speedRatio === void 0) { speedRatio = 1.0; }
  17407. if (from > to && speedRatio > 0) {
  17408. speedRatio *= -1;
  17409. }
  17410. this.stopAnimation(target);
  17411. if (!animatable) {
  17412. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17413. }
  17414. // Local animations
  17415. if (target.animations) {
  17416. animatable.appendAnimations(target, target.animations);
  17417. }
  17418. // Children animations
  17419. if (target.getAnimatables) {
  17420. var animatables = target.getAnimatables();
  17421. for (var index = 0; index < animatables.length; index++) {
  17422. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17423. }
  17424. }
  17425. animatable.reset();
  17426. return animatable;
  17427. };
  17428. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17429. if (speedRatio === undefined) {
  17430. speedRatio = 1.0;
  17431. }
  17432. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17433. return animatable;
  17434. };
  17435. Scene.prototype.getAnimatableByTarget = function (target) {
  17436. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17437. if (this._activeAnimatables[index].target === target) {
  17438. return this._activeAnimatables[index];
  17439. }
  17440. }
  17441. return null;
  17442. };
  17443. Object.defineProperty(Scene.prototype, "Animatables", {
  17444. get: function () {
  17445. return this._activeAnimatables;
  17446. },
  17447. enumerable: true,
  17448. configurable: true
  17449. });
  17450. /**
  17451. * Will stop the animation of the given target
  17452. * @param target - the target
  17453. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17454. * @see beginAnimation
  17455. */
  17456. Scene.prototype.stopAnimation = function (target, animationName) {
  17457. var animatable = this.getAnimatableByTarget(target);
  17458. if (animatable) {
  17459. animatable.stop(animationName);
  17460. }
  17461. };
  17462. Scene.prototype._animate = function () {
  17463. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17464. return;
  17465. }
  17466. // Getting time
  17467. var now = BABYLON.Tools.Now;
  17468. if (!this._animationTimeLast) {
  17469. if (this._pendingData.length > 0) {
  17470. return;
  17471. }
  17472. this._animationTimeLast = now;
  17473. }
  17474. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17475. this._animationTime += deltaTime;
  17476. this._animationTimeLast = now;
  17477. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17478. this._activeAnimatables[index]._animate(this._animationTime);
  17479. }
  17480. };
  17481. // Matrix
  17482. Scene.prototype.getViewMatrix = function () {
  17483. return this._viewMatrix;
  17484. };
  17485. Scene.prototype.getProjectionMatrix = function () {
  17486. return this._projectionMatrix;
  17487. };
  17488. Scene.prototype.getTransformMatrix = function () {
  17489. return this._transformMatrix;
  17490. };
  17491. Scene.prototype.setTransformMatrix = function (view, projection) {
  17492. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17493. return;
  17494. }
  17495. this._viewUpdateFlag = view.updateFlag;
  17496. this._projectionUpdateFlag = projection.updateFlag;
  17497. this._viewMatrix = view;
  17498. this._projectionMatrix = projection;
  17499. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17500. // Update frustum
  17501. if (!this._frustumPlanes) {
  17502. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17503. }
  17504. else {
  17505. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17506. }
  17507. if (this._sceneUbo.useUbo) {
  17508. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17509. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17510. this._sceneUbo.update();
  17511. }
  17512. };
  17513. Scene.prototype.getSceneUniformBuffer = function () {
  17514. return this._sceneUbo;
  17515. };
  17516. // Methods
  17517. Scene.prototype.getUniqueId = function () {
  17518. var result = this._uniqueIdCounter;
  17519. this._uniqueIdCounter++;
  17520. return result;
  17521. };
  17522. Scene.prototype.addMesh = function (newMesh) {
  17523. newMesh.uniqueId = this.getUniqueId();
  17524. var position = this.meshes.push(newMesh);
  17525. //notify the collision coordinator
  17526. if (this.collisionCoordinator) {
  17527. this.collisionCoordinator.onMeshAdded(newMesh);
  17528. }
  17529. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17530. };
  17531. Scene.prototype.removeMesh = function (toRemove) {
  17532. var index = this.meshes.indexOf(toRemove);
  17533. if (index !== -1) {
  17534. // Remove from the scene if mesh found
  17535. this.meshes.splice(index, 1);
  17536. }
  17537. //notify the collision coordinator
  17538. if (this.collisionCoordinator) {
  17539. this.collisionCoordinator.onMeshRemoved(toRemove);
  17540. }
  17541. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17542. return index;
  17543. };
  17544. Scene.prototype.removeSkeleton = function (toRemove) {
  17545. var index = this.skeletons.indexOf(toRemove);
  17546. if (index !== -1) {
  17547. // Remove from the scene if found
  17548. this.skeletons.splice(index, 1);
  17549. }
  17550. return index;
  17551. };
  17552. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17553. var index = this.morphTargetManagers.indexOf(toRemove);
  17554. if (index !== -1) {
  17555. // Remove from the scene if found
  17556. this.morphTargetManagers.splice(index, 1);
  17557. }
  17558. return index;
  17559. };
  17560. Scene.prototype.removeLight = function (toRemove) {
  17561. var index = this.lights.indexOf(toRemove);
  17562. if (index !== -1) {
  17563. // Remove from the scene if mesh found
  17564. this.lights.splice(index, 1);
  17565. this.sortLightsByPriority();
  17566. }
  17567. this.onLightRemovedObservable.notifyObservers(toRemove);
  17568. return index;
  17569. };
  17570. Scene.prototype.removeCamera = function (toRemove) {
  17571. var index = this.cameras.indexOf(toRemove);
  17572. if (index !== -1) {
  17573. // Remove from the scene if mesh found
  17574. this.cameras.splice(index, 1);
  17575. }
  17576. // Remove from activeCameras
  17577. var index2 = this.activeCameras.indexOf(toRemove);
  17578. if (index2 !== -1) {
  17579. // Remove from the scene if mesh found
  17580. this.activeCameras.splice(index2, 1);
  17581. }
  17582. // Reset the activeCamera
  17583. if (this.activeCamera === toRemove) {
  17584. if (this.cameras.length > 0) {
  17585. this.activeCamera = this.cameras[0];
  17586. }
  17587. else {
  17588. this.activeCamera = null;
  17589. }
  17590. }
  17591. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17592. return index;
  17593. };
  17594. Scene.prototype.addLight = function (newLight) {
  17595. newLight.uniqueId = this.getUniqueId();
  17596. this.lights.push(newLight);
  17597. this.sortLightsByPriority();
  17598. this.onNewLightAddedObservable.notifyObservers(newLight);
  17599. };
  17600. Scene.prototype.sortLightsByPriority = function () {
  17601. if (this.requireLightSorting) {
  17602. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17603. }
  17604. };
  17605. Scene.prototype.addCamera = function (newCamera) {
  17606. newCamera.uniqueId = this.getUniqueId();
  17607. var position = this.cameras.push(newCamera);
  17608. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17609. };
  17610. /**
  17611. * Switch active camera
  17612. * @param {Camera} newCamera - new active camera
  17613. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17614. */
  17615. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17616. if (attachControl === void 0) { attachControl = true; }
  17617. var canvas = this._engine.getRenderingCanvas();
  17618. this.activeCamera.detachControl(canvas);
  17619. this.activeCamera = newCamera;
  17620. if (attachControl) {
  17621. newCamera.attachControl(canvas);
  17622. }
  17623. };
  17624. /**
  17625. * sets the active camera of the scene using its ID
  17626. * @param {string} id - the camera's ID
  17627. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17628. * @see activeCamera
  17629. */
  17630. Scene.prototype.setActiveCameraByID = function (id) {
  17631. var camera = this.getCameraByID(id);
  17632. if (camera) {
  17633. this.activeCamera = camera;
  17634. return camera;
  17635. }
  17636. return null;
  17637. };
  17638. /**
  17639. * sets the active camera of the scene using its name
  17640. * @param {string} name - the camera's name
  17641. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17642. * @see activeCamera
  17643. */
  17644. Scene.prototype.setActiveCameraByName = function (name) {
  17645. var camera = this.getCameraByName(name);
  17646. if (camera) {
  17647. this.activeCamera = camera;
  17648. return camera;
  17649. }
  17650. return null;
  17651. };
  17652. /**
  17653. * get a material using its id
  17654. * @param {string} the material's ID
  17655. * @return {BABYLON.Material|null} the material or null if none found.
  17656. */
  17657. Scene.prototype.getMaterialByID = function (id) {
  17658. for (var index = 0; index < this.materials.length; index++) {
  17659. if (this.materials[index].id === id) {
  17660. return this.materials[index];
  17661. }
  17662. }
  17663. return null;
  17664. };
  17665. /**
  17666. * get a material using its name
  17667. * @param {string} the material's name
  17668. * @return {BABYLON.Material|null} the material or null if none found.
  17669. */
  17670. Scene.prototype.getMaterialByName = function (name) {
  17671. for (var index = 0; index < this.materials.length; index++) {
  17672. if (this.materials[index].name === name) {
  17673. return this.materials[index];
  17674. }
  17675. }
  17676. return null;
  17677. };
  17678. Scene.prototype.getLensFlareSystemByName = function (name) {
  17679. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17680. if (this.lensFlareSystems[index].name === name) {
  17681. return this.lensFlareSystems[index];
  17682. }
  17683. }
  17684. return null;
  17685. };
  17686. Scene.prototype.getLensFlareSystemByID = function (id) {
  17687. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17688. if (this.lensFlareSystems[index].id === id) {
  17689. return this.lensFlareSystems[index];
  17690. }
  17691. }
  17692. return null;
  17693. };
  17694. Scene.prototype.getCameraByID = function (id) {
  17695. for (var index = 0; index < this.cameras.length; index++) {
  17696. if (this.cameras[index].id === id) {
  17697. return this.cameras[index];
  17698. }
  17699. }
  17700. return null;
  17701. };
  17702. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17703. for (var index = 0; index < this.cameras.length; index++) {
  17704. if (this.cameras[index].uniqueId === uniqueId) {
  17705. return this.cameras[index];
  17706. }
  17707. }
  17708. return null;
  17709. };
  17710. /**
  17711. * get a camera using its name
  17712. * @param {string} the camera's name
  17713. * @return {BABYLON.Camera|null} the camera or null if none found.
  17714. */
  17715. Scene.prototype.getCameraByName = function (name) {
  17716. for (var index = 0; index < this.cameras.length; index++) {
  17717. if (this.cameras[index].name === name) {
  17718. return this.cameras[index];
  17719. }
  17720. }
  17721. return null;
  17722. };
  17723. /**
  17724. * get a bone using its id
  17725. * @param {string} the bone's id
  17726. * @return {BABYLON.Bone|null} the bone or null if not found
  17727. */
  17728. Scene.prototype.getBoneByID = function (id) {
  17729. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17730. var skeleton = this.skeletons[skeletonIndex];
  17731. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17732. if (skeleton.bones[boneIndex].id === id) {
  17733. return skeleton.bones[boneIndex];
  17734. }
  17735. }
  17736. }
  17737. return null;
  17738. };
  17739. /**
  17740. * get a bone using its id
  17741. * @param {string} the bone's name
  17742. * @return {BABYLON.Bone|null} the bone or null if not found
  17743. */
  17744. Scene.prototype.getBoneByName = function (name) {
  17745. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17746. var skeleton = this.skeletons[skeletonIndex];
  17747. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17748. if (skeleton.bones[boneIndex].name === name) {
  17749. return skeleton.bones[boneIndex];
  17750. }
  17751. }
  17752. }
  17753. return null;
  17754. };
  17755. /**
  17756. * get a light node using its name
  17757. * @param {string} the light's name
  17758. * @return {BABYLON.Light|null} the light or null if none found.
  17759. */
  17760. Scene.prototype.getLightByName = function (name) {
  17761. for (var index = 0; index < this.lights.length; index++) {
  17762. if (this.lights[index].name === name) {
  17763. return this.lights[index];
  17764. }
  17765. }
  17766. return null;
  17767. };
  17768. /**
  17769. * get a light node using its ID
  17770. * @param {string} the light's id
  17771. * @return {BABYLON.Light|null} the light or null if none found.
  17772. */
  17773. Scene.prototype.getLightByID = function (id) {
  17774. for (var index = 0; index < this.lights.length; index++) {
  17775. if (this.lights[index].id === id) {
  17776. return this.lights[index];
  17777. }
  17778. }
  17779. return null;
  17780. };
  17781. /**
  17782. * get a light node using its scene-generated unique ID
  17783. * @param {number} the light's unique id
  17784. * @return {BABYLON.Light|null} the light or null if none found.
  17785. */
  17786. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17787. for (var index = 0; index < this.lights.length; index++) {
  17788. if (this.lights[index].uniqueId === uniqueId) {
  17789. return this.lights[index];
  17790. }
  17791. }
  17792. return null;
  17793. };
  17794. /**
  17795. * get a particle system by id
  17796. * @param id {number} the particle system id
  17797. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17798. */
  17799. Scene.prototype.getParticleSystemByID = function (id) {
  17800. for (var index = 0; index < this.particleSystems.length; index++) {
  17801. if (this.particleSystems[index].id === id) {
  17802. return this.particleSystems[index];
  17803. }
  17804. }
  17805. return null;
  17806. };
  17807. /**
  17808. * get a geometry using its ID
  17809. * @param {string} the geometry's id
  17810. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17811. */
  17812. Scene.prototype.getGeometryByID = function (id) {
  17813. for (var index = 0; index < this._geometries.length; index++) {
  17814. if (this._geometries[index].id === id) {
  17815. return this._geometries[index];
  17816. }
  17817. }
  17818. return null;
  17819. };
  17820. /**
  17821. * add a new geometry to this scene.
  17822. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17823. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17824. * @return {boolean} was the geometry added or not
  17825. */
  17826. Scene.prototype.pushGeometry = function (geometry, force) {
  17827. if (!force && this.getGeometryByID(geometry.id)) {
  17828. return false;
  17829. }
  17830. this._geometries.push(geometry);
  17831. //notify the collision coordinator
  17832. if (this.collisionCoordinator) {
  17833. this.collisionCoordinator.onGeometryAdded(geometry);
  17834. }
  17835. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17836. return true;
  17837. };
  17838. /**
  17839. * Removes an existing geometry
  17840. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17841. * @return {boolean} was the geometry removed or not
  17842. */
  17843. Scene.prototype.removeGeometry = function (geometry) {
  17844. var index = this._geometries.indexOf(geometry);
  17845. if (index > -1) {
  17846. this._geometries.splice(index, 1);
  17847. //notify the collision coordinator
  17848. if (this.collisionCoordinator) {
  17849. this.collisionCoordinator.onGeometryDeleted(geometry);
  17850. }
  17851. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17852. return true;
  17853. }
  17854. return false;
  17855. };
  17856. Scene.prototype.getGeometries = function () {
  17857. return this._geometries;
  17858. };
  17859. /**
  17860. * Get the first added mesh found of a given ID
  17861. * @param {string} id - the id to search for
  17862. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17863. */
  17864. Scene.prototype.getMeshByID = function (id) {
  17865. for (var index = 0; index < this.meshes.length; index++) {
  17866. if (this.meshes[index].id === id) {
  17867. return this.meshes[index];
  17868. }
  17869. }
  17870. return null;
  17871. };
  17872. Scene.prototype.getMeshesByID = function (id) {
  17873. return this.meshes.filter(function (m) {
  17874. return m.id === id;
  17875. });
  17876. };
  17877. /**
  17878. * Get a mesh with its auto-generated unique id
  17879. * @param {number} uniqueId - the unique id to search for
  17880. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17881. */
  17882. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17883. for (var index = 0; index < this.meshes.length; index++) {
  17884. if (this.meshes[index].uniqueId === uniqueId) {
  17885. return this.meshes[index];
  17886. }
  17887. }
  17888. return null;
  17889. };
  17890. /**
  17891. * Get a the last added mesh found of a given ID
  17892. * @param {string} id - the id to search for
  17893. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17894. */
  17895. Scene.prototype.getLastMeshByID = function (id) {
  17896. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17897. if (this.meshes[index].id === id) {
  17898. return this.meshes[index];
  17899. }
  17900. }
  17901. return null;
  17902. };
  17903. /**
  17904. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17905. * @param {string} id - the id to search for
  17906. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17907. */
  17908. Scene.prototype.getLastEntryByID = function (id) {
  17909. var index;
  17910. for (index = this.meshes.length - 1; index >= 0; index--) {
  17911. if (this.meshes[index].id === id) {
  17912. return this.meshes[index];
  17913. }
  17914. }
  17915. for (index = this.cameras.length - 1; index >= 0; index--) {
  17916. if (this.cameras[index].id === id) {
  17917. return this.cameras[index];
  17918. }
  17919. }
  17920. for (index = this.lights.length - 1; index >= 0; index--) {
  17921. if (this.lights[index].id === id) {
  17922. return this.lights[index];
  17923. }
  17924. }
  17925. return null;
  17926. };
  17927. Scene.prototype.getNodeByID = function (id) {
  17928. var mesh = this.getMeshByID(id);
  17929. if (mesh) {
  17930. return mesh;
  17931. }
  17932. var light = this.getLightByID(id);
  17933. if (light) {
  17934. return light;
  17935. }
  17936. var camera = this.getCameraByID(id);
  17937. if (camera) {
  17938. return camera;
  17939. }
  17940. var bone = this.getBoneByID(id);
  17941. return bone;
  17942. };
  17943. Scene.prototype.getNodeByName = function (name) {
  17944. var mesh = this.getMeshByName(name);
  17945. if (mesh) {
  17946. return mesh;
  17947. }
  17948. var light = this.getLightByName(name);
  17949. if (light) {
  17950. return light;
  17951. }
  17952. var camera = this.getCameraByName(name);
  17953. if (camera) {
  17954. return camera;
  17955. }
  17956. var bone = this.getBoneByName(name);
  17957. return bone;
  17958. };
  17959. Scene.prototype.getMeshByName = function (name) {
  17960. for (var index = 0; index < this.meshes.length; index++) {
  17961. if (this.meshes[index].name === name) {
  17962. return this.meshes[index];
  17963. }
  17964. }
  17965. return null;
  17966. };
  17967. Scene.prototype.getSoundByName = function (name) {
  17968. var index;
  17969. if (BABYLON.AudioEngine) {
  17970. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17971. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17972. return this.mainSoundTrack.soundCollection[index];
  17973. }
  17974. }
  17975. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17976. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17977. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17978. return this.soundTracks[sdIndex].soundCollection[index];
  17979. }
  17980. }
  17981. }
  17982. }
  17983. return null;
  17984. };
  17985. Scene.prototype.getLastSkeletonByID = function (id) {
  17986. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17987. if (this.skeletons[index].id === id) {
  17988. return this.skeletons[index];
  17989. }
  17990. }
  17991. return null;
  17992. };
  17993. Scene.prototype.getSkeletonById = function (id) {
  17994. for (var index = 0; index < this.skeletons.length; index++) {
  17995. if (this.skeletons[index].id === id) {
  17996. return this.skeletons[index];
  17997. }
  17998. }
  17999. return null;
  18000. };
  18001. Scene.prototype.getSkeletonByName = function (name) {
  18002. for (var index = 0; index < this.skeletons.length; index++) {
  18003. if (this.skeletons[index].name === name) {
  18004. return this.skeletons[index];
  18005. }
  18006. }
  18007. return null;
  18008. };
  18009. Scene.prototype.getMorphTargetManagerById = function (id) {
  18010. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18011. if (this.morphTargetManagers[index].uniqueId === id) {
  18012. return this.morphTargetManagers[index];
  18013. }
  18014. }
  18015. return null;
  18016. };
  18017. Scene.prototype.isActiveMesh = function (mesh) {
  18018. return (this._activeMeshes.indexOf(mesh) !== -1);
  18019. };
  18020. /**
  18021. * Return a the first highlight layer of the scene with a given name.
  18022. * @param name The name of the highlight layer to look for.
  18023. * @return The highlight layer if found otherwise null.
  18024. */
  18025. Scene.prototype.getHighlightLayerByName = function (name) {
  18026. for (var index = 0; index < this.highlightLayers.length; index++) {
  18027. if (this.highlightLayers[index].name === name) {
  18028. return this.highlightLayers[index];
  18029. }
  18030. }
  18031. return null;
  18032. };
  18033. Object.defineProperty(Scene.prototype, "uid", {
  18034. /**
  18035. * Return a unique id as a string which can serve as an identifier for the scene
  18036. */
  18037. get: function () {
  18038. if (!this._uid) {
  18039. this._uid = BABYLON.Tools.RandomId();
  18040. }
  18041. return this._uid;
  18042. },
  18043. enumerable: true,
  18044. configurable: true
  18045. });
  18046. /**
  18047. * Add an externaly attached data from its key.
  18048. * This method call will fail and return false, if such key already exists.
  18049. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18050. * @param key the unique key that identifies the data
  18051. * @param data the data object to associate to the key for this Engine instance
  18052. * @return true if no such key were already present and the data was added successfully, false otherwise
  18053. */
  18054. Scene.prototype.addExternalData = function (key, data) {
  18055. if (!this._externalData) {
  18056. this._externalData = new BABYLON.StringDictionary();
  18057. }
  18058. return this._externalData.add(key, data);
  18059. };
  18060. /**
  18061. * Get an externaly attached data from its key
  18062. * @param key the unique key that identifies the data
  18063. * @return the associated data, if present (can be null), or undefined if not present
  18064. */
  18065. Scene.prototype.getExternalData = function (key) {
  18066. if (!this._externalData) {
  18067. return null;
  18068. }
  18069. return this._externalData.get(key);
  18070. };
  18071. /**
  18072. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18073. * @param key the unique key that identifies the data
  18074. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18075. * @return the associated data, can be null if the factory returned null.
  18076. */
  18077. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18078. if (!this._externalData) {
  18079. this._externalData = new BABYLON.StringDictionary();
  18080. }
  18081. return this._externalData.getOrAddWithFactory(key, factory);
  18082. };
  18083. /**
  18084. * Remove an externaly attached data from the Engine instance
  18085. * @param key the unique key that identifies the data
  18086. * @return true if the data was successfully removed, false if it doesn't exist
  18087. */
  18088. Scene.prototype.removeExternalData = function (key) {
  18089. return this._externalData.remove(key);
  18090. };
  18091. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18092. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18093. var material = subMesh.getMaterial();
  18094. if (mesh.showSubMeshesBoundingBox) {
  18095. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18096. }
  18097. if (material) {
  18098. // Render targets
  18099. if (material.getRenderTargetTextures) {
  18100. if (this._processedMaterials.indexOf(material) === -1) {
  18101. this._processedMaterials.push(material);
  18102. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18103. }
  18104. }
  18105. // Dispatch
  18106. this._activeIndices.addCount(subMesh.indexCount, false);
  18107. this._renderingManager.dispatch(subMesh);
  18108. }
  18109. }
  18110. };
  18111. Scene.prototype._isInIntermediateRendering = function () {
  18112. return this._intermediateRendering;
  18113. };
  18114. Scene.prototype._evaluateActiveMeshes = function () {
  18115. this.activeCamera._activeMeshes.reset();
  18116. this._activeMeshes.reset();
  18117. this._renderingManager.reset();
  18118. this._processedMaterials.reset();
  18119. this._activeParticleSystems.reset();
  18120. this._activeSkeletons.reset();
  18121. this._softwareSkinnedMeshes.reset();
  18122. if (this._boundingBoxRenderer) {
  18123. this._boundingBoxRenderer.reset();
  18124. }
  18125. // Meshes
  18126. var meshes;
  18127. var len;
  18128. if (this._selectionOctree) {
  18129. var selection = this._selectionOctree.select(this._frustumPlanes);
  18130. meshes = selection.data;
  18131. len = selection.length;
  18132. }
  18133. else {
  18134. len = this.meshes.length;
  18135. meshes = this.meshes;
  18136. }
  18137. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18138. var mesh = meshes[meshIndex];
  18139. if (mesh.isBlocked) {
  18140. continue;
  18141. }
  18142. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18143. if (!mesh.isReady() || !mesh.isEnabled()) {
  18144. continue;
  18145. }
  18146. mesh.computeWorldMatrix();
  18147. // Intersections
  18148. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18149. this._meshesForIntersections.pushNoDuplicate(mesh);
  18150. }
  18151. // Switch to current LOD
  18152. var meshLOD = mesh.getLOD(this.activeCamera);
  18153. if (!meshLOD) {
  18154. continue;
  18155. }
  18156. mesh._preActivate();
  18157. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18158. this._activeMeshes.push(mesh);
  18159. this.activeCamera._activeMeshes.push(mesh);
  18160. mesh._activate(this._renderId);
  18161. if (meshLOD !== mesh) {
  18162. meshLOD._activate(this._renderId);
  18163. }
  18164. this._activeMesh(mesh, meshLOD);
  18165. }
  18166. }
  18167. // Particle systems
  18168. this._particlesDuration.beginMonitoring();
  18169. var beforeParticlesDate = BABYLON.Tools.Now;
  18170. if (this.particlesEnabled) {
  18171. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18172. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18173. var particleSystem = this.particleSystems[particleIndex];
  18174. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18175. continue;
  18176. }
  18177. var emitter = particleSystem.emitter;
  18178. if (!emitter.position || emitter.isEnabled()) {
  18179. this._activeParticleSystems.push(particleSystem);
  18180. particleSystem.animate();
  18181. this._renderingManager.dispatchParticles(particleSystem);
  18182. }
  18183. }
  18184. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18185. }
  18186. this._particlesDuration.endMonitoring(false);
  18187. };
  18188. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18189. if (mesh.skeleton && this.skeletonsEnabled) {
  18190. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18191. mesh.skeleton.prepare();
  18192. }
  18193. if (!mesh.computeBonesUsingShaders) {
  18194. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18195. }
  18196. }
  18197. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18198. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18199. }
  18200. if (mesh && mesh.subMeshes) {
  18201. // Submeshes Octrees
  18202. var len;
  18203. var subMeshes;
  18204. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18205. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18206. len = intersections.length;
  18207. subMeshes = intersections.data;
  18208. }
  18209. else {
  18210. subMeshes = mesh.subMeshes;
  18211. len = subMeshes.length;
  18212. }
  18213. for (var subIndex = 0; subIndex < len; subIndex++) {
  18214. var subMesh = subMeshes[subIndex];
  18215. this._evaluateSubMesh(subMesh, mesh);
  18216. }
  18217. }
  18218. };
  18219. Scene.prototype.updateTransformMatrix = function (force) {
  18220. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18221. };
  18222. Scene.prototype._renderForCamera = function (camera) {
  18223. var engine = this._engine;
  18224. var startTime = BABYLON.Tools.Now;
  18225. this.activeCamera = camera;
  18226. if (!this.activeCamera)
  18227. throw new Error("Active camera not set");
  18228. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18229. // Viewport
  18230. engine.setViewport(this.activeCamera.viewport);
  18231. // Camera
  18232. this.resetCachedMaterial();
  18233. this._renderId++;
  18234. this.updateTransformMatrix();
  18235. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18236. // Meshes
  18237. this._evaluateActiveMeshesDuration.beginMonitoring();
  18238. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18239. this._evaluateActiveMeshes();
  18240. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18241. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18242. // Software skinning
  18243. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18244. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18245. mesh.applySkeleton(mesh.skeleton);
  18246. }
  18247. // Render targets
  18248. this._renderTargetsDuration.beginMonitoring();
  18249. var needsRestoreFrameBuffer = false;
  18250. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18251. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18252. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18253. }
  18254. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18255. this._intermediateRendering = true;
  18256. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18257. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18258. var renderTarget = this._renderTargets.data[renderIndex];
  18259. if (renderTarget._shouldRender()) {
  18260. this._renderId++;
  18261. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18262. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18263. }
  18264. }
  18265. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18266. this._intermediateRendering = false;
  18267. this._renderId++;
  18268. needsRestoreFrameBuffer = true; // Restore back buffer
  18269. }
  18270. // Render HighlightLayer Texture
  18271. var stencilState = this._engine.getStencilBuffer();
  18272. var renderhighlights = false;
  18273. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18274. this._intermediateRendering = true;
  18275. for (var i = 0; i < this.highlightLayers.length; i++) {
  18276. var highlightLayer = this.highlightLayers[i];
  18277. if (highlightLayer.shouldRender() &&
  18278. (!highlightLayer.camera ||
  18279. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18280. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18281. renderhighlights = true;
  18282. var renderTarget = highlightLayer._mainTexture;
  18283. if (renderTarget._shouldRender()) {
  18284. this._renderId++;
  18285. renderTarget.render(false, false);
  18286. needsRestoreFrameBuffer = true;
  18287. }
  18288. }
  18289. }
  18290. this._intermediateRendering = false;
  18291. this._renderId++;
  18292. }
  18293. if (needsRestoreFrameBuffer) {
  18294. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18295. }
  18296. this._renderTargetsDuration.endMonitoring(false);
  18297. // Prepare Frame
  18298. this.postProcessManager._prepareFrame();
  18299. this._renderDuration.beginMonitoring();
  18300. // Backgrounds
  18301. var layerIndex;
  18302. var layer;
  18303. if (this.layers.length) {
  18304. engine.setDepthBuffer(false);
  18305. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18306. layer = this.layers[layerIndex];
  18307. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18308. layer.render();
  18309. }
  18310. }
  18311. engine.setDepthBuffer(true);
  18312. }
  18313. // Render
  18314. BABYLON.Tools.StartPerformanceCounter("Main render");
  18315. // Activate HighlightLayer stencil
  18316. if (renderhighlights) {
  18317. this._engine.setStencilBuffer(true);
  18318. }
  18319. this._renderingManager.render(null, null, true, true);
  18320. // Restore HighlightLayer stencil
  18321. if (renderhighlights) {
  18322. this._engine.setStencilBuffer(stencilState);
  18323. }
  18324. BABYLON.Tools.EndPerformanceCounter("Main render");
  18325. // Bounding boxes
  18326. if (this._boundingBoxRenderer) {
  18327. this._boundingBoxRenderer.render();
  18328. }
  18329. // Lens flares
  18330. if (this.lensFlaresEnabled) {
  18331. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18332. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18333. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18334. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18335. lensFlareSystem.render();
  18336. }
  18337. }
  18338. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18339. }
  18340. // Foregrounds
  18341. if (this.layers.length) {
  18342. engine.setDepthBuffer(false);
  18343. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18344. layer = this.layers[layerIndex];
  18345. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18346. layer.render();
  18347. }
  18348. }
  18349. engine.setDepthBuffer(true);
  18350. }
  18351. // Highlight Layer
  18352. if (renderhighlights) {
  18353. engine.setDepthBuffer(false);
  18354. for (var i = 0; i < this.highlightLayers.length; i++) {
  18355. if (this.highlightLayers[i].shouldRender()) {
  18356. this.highlightLayers[i].render();
  18357. }
  18358. }
  18359. engine.setDepthBuffer(true);
  18360. }
  18361. this._renderDuration.endMonitoring(false);
  18362. // Finalize frame
  18363. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18364. // Update camera
  18365. this.activeCamera._updateFromScene();
  18366. // Reset some special arrays
  18367. this._renderTargets.reset();
  18368. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18369. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18370. };
  18371. Scene.prototype._processSubCameras = function (camera) {
  18372. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18373. this._renderForCamera(camera);
  18374. return;
  18375. }
  18376. // rig cameras
  18377. for (var index = 0; index < camera._rigCameras.length; index++) {
  18378. this._renderForCamera(camera._rigCameras[index]);
  18379. }
  18380. this.activeCamera = camera;
  18381. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18382. // Update camera
  18383. this.activeCamera._updateFromScene();
  18384. };
  18385. Scene.prototype._checkIntersections = function () {
  18386. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18387. var sourceMesh = this._meshesForIntersections.data[index];
  18388. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18389. var action = sourceMesh.actionManager.actions[actionIndex];
  18390. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18391. var parameters = action.getTriggerParameter();
  18392. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18393. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18394. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18395. if (areIntersecting && currentIntersectionInProgress === -1) {
  18396. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18397. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18398. sourceMesh._intersectionsInProgress.push(otherMesh);
  18399. }
  18400. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18401. sourceMesh._intersectionsInProgress.push(otherMesh);
  18402. }
  18403. }
  18404. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18405. //They intersected, and now they don't.
  18406. //is this trigger an exit trigger? execute an event.
  18407. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18408. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18409. }
  18410. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18411. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18412. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18413. }
  18414. }
  18415. }
  18416. }
  18417. }
  18418. };
  18419. Scene.prototype.render = function () {
  18420. if (this.isDisposed) {
  18421. return;
  18422. }
  18423. this._lastFrameDuration.beginMonitoring();
  18424. this._particlesDuration.fetchNewFrame();
  18425. this._spritesDuration.fetchNewFrame();
  18426. this._activeParticles.fetchNewFrame();
  18427. this._renderDuration.fetchNewFrame();
  18428. this._renderTargetsDuration.fetchNewFrame();
  18429. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18430. this._totalVertices.fetchNewFrame();
  18431. this._activeIndices.fetchNewFrame();
  18432. this._activeBones.fetchNewFrame();
  18433. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18434. this._meshesForIntersections.reset();
  18435. this.resetCachedMaterial();
  18436. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18437. // Actions
  18438. if (this.actionManager) {
  18439. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18440. }
  18441. //Simplification Queue
  18442. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18443. this.simplificationQueue.executeNext();
  18444. }
  18445. if (this._engine.isDeterministicLockStep()) {
  18446. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18447. var defaultTimeStep = (60.0 / 1000.0);
  18448. if (this._physicsEngine) {
  18449. defaultTimeStep = this._physicsEngine.getTimeStep();
  18450. }
  18451. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18452. this._timeAccumulator += deltaTime;
  18453. // compute the amount of fixed steps we should have taken since the last step
  18454. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18455. internalSteps = Math.min(internalSteps, maxSubSteps);
  18456. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18457. this.onBeforeStepObservable.notifyObservers(this);
  18458. // Animations
  18459. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18460. this._animate();
  18461. // Physics
  18462. if (this._physicsEngine) {
  18463. BABYLON.Tools.StartPerformanceCounter("Physics");
  18464. this._physicsEngine._step(defaultTimeStep);
  18465. BABYLON.Tools.EndPerformanceCounter("Physics");
  18466. }
  18467. this._timeAccumulator -= defaultTimeStep;
  18468. this.onAfterStepObservable.notifyObservers(this);
  18469. this._currentStepId++;
  18470. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18471. // Q: can this be optimized by putting some code in the afterStep callback?
  18472. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18473. // would return incorrect positions for internal stepIds (non-rendered steps)
  18474. this._evaluateActiveMeshes();
  18475. }
  18476. }
  18477. }
  18478. else {
  18479. // Animations
  18480. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18481. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18482. this._animate();
  18483. // Physics
  18484. if (this._physicsEngine) {
  18485. BABYLON.Tools.StartPerformanceCounter("Physics");
  18486. this._physicsEngine._step(deltaTime / 1000.0);
  18487. BABYLON.Tools.EndPerformanceCounter("Physics");
  18488. }
  18489. }
  18490. // Before render
  18491. this.onBeforeRenderObservable.notifyObservers(this);
  18492. // Customs render targets
  18493. this._renderTargetsDuration.beginMonitoring();
  18494. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18495. var engine = this.getEngine();
  18496. var currentActiveCamera = this.activeCamera;
  18497. if (this.renderTargetsEnabled) {
  18498. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18499. this._intermediateRendering = true;
  18500. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18501. var renderTarget = this.customRenderTargets[customIndex];
  18502. if (renderTarget._shouldRender()) {
  18503. this._renderId++;
  18504. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18505. if (!this.activeCamera)
  18506. throw new Error("Active camera not set");
  18507. // Viewport
  18508. engine.setViewport(this.activeCamera.viewport);
  18509. // Camera
  18510. this.updateTransformMatrix();
  18511. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18512. }
  18513. }
  18514. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18515. this._intermediateRendering = false;
  18516. this._renderId++;
  18517. }
  18518. // Restore back buffer
  18519. if (this.customRenderTargets.length > 0) {
  18520. engine.restoreDefaultFramebuffer();
  18521. }
  18522. this._renderTargetsDuration.endMonitoring();
  18523. this.activeCamera = currentActiveCamera;
  18524. // Procedural textures
  18525. if (this.proceduralTexturesEnabled) {
  18526. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18527. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18528. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18529. if (proceduralTexture._shouldRender()) {
  18530. proceduralTexture.render();
  18531. }
  18532. }
  18533. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18534. }
  18535. // Clear
  18536. if (this.autoClearDepthAndStencil || this.autoClear) {
  18537. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18538. }
  18539. // Shadows
  18540. if (this.shadowsEnabled) {
  18541. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18542. var light = this.lights[lightIndex];
  18543. var shadowGenerator = light.getShadowGenerator();
  18544. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18545. var shadowMap = shadowGenerator.getShadowMap();
  18546. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18547. this._renderTargets.push(shadowMap);
  18548. }
  18549. }
  18550. }
  18551. }
  18552. // Depth renderer
  18553. if (this._depthRenderer) {
  18554. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18555. }
  18556. // Geometry renderer
  18557. if (this._geometryBufferRenderer) {
  18558. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18559. }
  18560. // RenderPipeline
  18561. if (this._postProcessRenderPipelineManager) {
  18562. this._postProcessRenderPipelineManager.update();
  18563. }
  18564. // Multi-cameras?
  18565. if (this.activeCameras.length > 0) {
  18566. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18567. if (cameraIndex > 0) {
  18568. this._engine.clear(null, false, true, true);
  18569. }
  18570. this._processSubCameras(this.activeCameras[cameraIndex]);
  18571. }
  18572. }
  18573. else {
  18574. if (!this.activeCamera) {
  18575. throw new Error("No camera defined");
  18576. }
  18577. this._processSubCameras(this.activeCamera);
  18578. }
  18579. // Intersection checks
  18580. this._checkIntersections();
  18581. // Update the audio listener attached to the camera
  18582. if (BABYLON.AudioEngine) {
  18583. this._updateAudioParameters();
  18584. }
  18585. // After render
  18586. if (this.afterRender) {
  18587. this.afterRender();
  18588. }
  18589. this.onAfterRenderObservable.notifyObservers(this);
  18590. // Cleaning
  18591. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18592. this._toBeDisposed.data[index].dispose();
  18593. this._toBeDisposed[index] = null;
  18594. }
  18595. this._toBeDisposed.reset();
  18596. if (this.dumpNextRenderTargets) {
  18597. this.dumpNextRenderTargets = false;
  18598. }
  18599. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18600. this._lastFrameDuration.endMonitoring();
  18601. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18602. this._totalLightsCounter.addCount(this.lights.length, true);
  18603. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18604. this._totalTexturesCounter.addCount(this.textures.length, true);
  18605. this._activeBones.addCount(0, true);
  18606. this._activeIndices.addCount(0, true);
  18607. this._activeParticles.addCount(0, true);
  18608. };
  18609. Scene.prototype._updateAudioParameters = function () {
  18610. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18611. return;
  18612. }
  18613. var listeningCamera;
  18614. var audioEngine = BABYLON.Engine.audioEngine;
  18615. if (this.activeCameras.length > 0) {
  18616. listeningCamera = this.activeCameras[0];
  18617. }
  18618. else {
  18619. listeningCamera = this.activeCamera;
  18620. }
  18621. if (listeningCamera && audioEngine.canUseWebAudio) {
  18622. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18623. // for VR cameras
  18624. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18625. listeningCamera = listeningCamera.rigCameras[0];
  18626. }
  18627. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18628. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18629. cameraDirection.normalize();
  18630. // To avoid some errors on GearVR
  18631. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18632. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18633. }
  18634. var i;
  18635. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18636. var sound = this.mainSoundTrack.soundCollection[i];
  18637. if (sound.useCustomAttenuation) {
  18638. sound.updateDistanceFromListener();
  18639. }
  18640. }
  18641. for (i = 0; i < this.soundTracks.length; i++) {
  18642. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18643. sound = this.soundTracks[i].soundCollection[j];
  18644. if (sound.useCustomAttenuation) {
  18645. sound.updateDistanceFromListener();
  18646. }
  18647. }
  18648. }
  18649. }
  18650. };
  18651. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18652. // Audio
  18653. get: function () {
  18654. return this._audioEnabled;
  18655. },
  18656. set: function (value) {
  18657. this._audioEnabled = value;
  18658. if (BABYLON.AudioEngine) {
  18659. if (this._audioEnabled) {
  18660. this._enableAudio();
  18661. }
  18662. else {
  18663. this._disableAudio();
  18664. }
  18665. }
  18666. },
  18667. enumerable: true,
  18668. configurable: true
  18669. });
  18670. Scene.prototype._disableAudio = function () {
  18671. var i;
  18672. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18673. this.mainSoundTrack.soundCollection[i].pause();
  18674. }
  18675. for (i = 0; i < this.soundTracks.length; i++) {
  18676. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18677. this.soundTracks[i].soundCollection[j].pause();
  18678. }
  18679. }
  18680. };
  18681. Scene.prototype._enableAudio = function () {
  18682. var i;
  18683. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18684. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18685. this.mainSoundTrack.soundCollection[i].play();
  18686. }
  18687. }
  18688. for (i = 0; i < this.soundTracks.length; i++) {
  18689. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18690. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18691. this.soundTracks[i].soundCollection[j].play();
  18692. }
  18693. }
  18694. }
  18695. };
  18696. Object.defineProperty(Scene.prototype, "headphone", {
  18697. get: function () {
  18698. return this._headphone;
  18699. },
  18700. set: function (value) {
  18701. this._headphone = value;
  18702. if (BABYLON.AudioEngine) {
  18703. if (this._headphone) {
  18704. this._switchAudioModeForHeadphones();
  18705. }
  18706. else {
  18707. this._switchAudioModeForNormalSpeakers();
  18708. }
  18709. }
  18710. },
  18711. enumerable: true,
  18712. configurable: true
  18713. });
  18714. Scene.prototype._switchAudioModeForHeadphones = function () {
  18715. this.mainSoundTrack.switchPanningModelToHRTF();
  18716. for (var i = 0; i < this.soundTracks.length; i++) {
  18717. this.soundTracks[i].switchPanningModelToHRTF();
  18718. }
  18719. };
  18720. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18721. this.mainSoundTrack.switchPanningModelToEqualPower();
  18722. for (var i = 0; i < this.soundTracks.length; i++) {
  18723. this.soundTracks[i].switchPanningModelToEqualPower();
  18724. }
  18725. };
  18726. Scene.prototype.enableDepthRenderer = function () {
  18727. if (this._depthRenderer) {
  18728. return this._depthRenderer;
  18729. }
  18730. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18731. return this._depthRenderer;
  18732. };
  18733. Scene.prototype.disableDepthRenderer = function () {
  18734. if (!this._depthRenderer) {
  18735. return;
  18736. }
  18737. this._depthRenderer.dispose();
  18738. this._depthRenderer = null;
  18739. };
  18740. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18741. if (ratio === void 0) { ratio = 1; }
  18742. if (this._geometryBufferRenderer) {
  18743. return this._geometryBufferRenderer;
  18744. }
  18745. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18746. if (!this._geometryBufferRenderer.isSupported) {
  18747. this._geometryBufferRenderer = null;
  18748. }
  18749. return this._geometryBufferRenderer;
  18750. };
  18751. Scene.prototype.disableGeometryBufferRenderer = function () {
  18752. if (!this._geometryBufferRenderer) {
  18753. return;
  18754. }
  18755. this._geometryBufferRenderer.dispose();
  18756. this._geometryBufferRenderer = null;
  18757. };
  18758. Scene.prototype.freezeMaterials = function () {
  18759. for (var i = 0; i < this.materials.length; i++) {
  18760. this.materials[i].freeze();
  18761. }
  18762. };
  18763. Scene.prototype.unfreezeMaterials = function () {
  18764. for (var i = 0; i < this.materials.length; i++) {
  18765. this.materials[i].unfreeze();
  18766. }
  18767. };
  18768. Scene.prototype.dispose = function () {
  18769. this.beforeRender = null;
  18770. this.afterRender = null;
  18771. this.skeletons = [];
  18772. this.morphTargetManagers = [];
  18773. this.importedMeshesFiles = new Array();
  18774. this.resetCachedMaterial();
  18775. if (this._depthRenderer) {
  18776. this._depthRenderer.dispose();
  18777. }
  18778. // Smart arrays
  18779. if (this.activeCamera) {
  18780. this.activeCamera._activeMeshes.dispose();
  18781. this.activeCamera = null;
  18782. }
  18783. this._activeMeshes.dispose();
  18784. this._renderingManager.dispose();
  18785. this._processedMaterials.dispose();
  18786. this._activeParticleSystems.dispose();
  18787. this._activeSkeletons.dispose();
  18788. this._softwareSkinnedMeshes.dispose();
  18789. this._renderTargets.dispose();
  18790. if (this._boundingBoxRenderer) {
  18791. this._boundingBoxRenderer.dispose();
  18792. }
  18793. this._meshesForIntersections.dispose();
  18794. this._toBeDisposed.dispose();
  18795. // Debug layer
  18796. if (this._debugLayer) {
  18797. this._debugLayer.hide();
  18798. }
  18799. // Events
  18800. this.onDisposeObservable.notifyObservers(this);
  18801. this.onDisposeObservable.clear();
  18802. this.onBeforeRenderObservable.clear();
  18803. this.onAfterRenderObservable.clear();
  18804. this.detachControl();
  18805. // Release sounds & sounds tracks
  18806. if (BABYLON.AudioEngine) {
  18807. this.disposeSounds();
  18808. }
  18809. // VR Helper
  18810. if (this.VRHelper) {
  18811. this.VRHelper.dispose();
  18812. }
  18813. // Detach cameras
  18814. var canvas = this._engine.getRenderingCanvas();
  18815. var index;
  18816. for (index = 0; index < this.cameras.length; index++) {
  18817. this.cameras[index].detachControl(canvas);
  18818. }
  18819. // Release lights
  18820. while (this.lights.length) {
  18821. this.lights[0].dispose();
  18822. }
  18823. // Release meshes
  18824. while (this.meshes.length) {
  18825. this.meshes[0].dispose(true);
  18826. }
  18827. // Release cameras
  18828. while (this.cameras.length) {
  18829. this.cameras[0].dispose();
  18830. }
  18831. // Release materials
  18832. if (this.defaultMaterial) {
  18833. this.defaultMaterial.dispose();
  18834. }
  18835. while (this.multiMaterials.length) {
  18836. this.multiMaterials[0].dispose();
  18837. }
  18838. while (this.materials.length) {
  18839. this.materials[0].dispose();
  18840. }
  18841. // Release particles
  18842. while (this.particleSystems.length) {
  18843. this.particleSystems[0].dispose();
  18844. }
  18845. // Release sprites
  18846. while (this.spriteManagers.length) {
  18847. this.spriteManagers[0].dispose();
  18848. }
  18849. // Release layers
  18850. while (this.layers.length) {
  18851. this.layers[0].dispose();
  18852. }
  18853. while (this.highlightLayers.length) {
  18854. this.highlightLayers[0].dispose();
  18855. }
  18856. // Release textures
  18857. while (this.textures.length) {
  18858. this.textures[0].dispose();
  18859. }
  18860. // Release UBO
  18861. this._sceneUbo.dispose();
  18862. // Post-processes
  18863. this.postProcessManager.dispose();
  18864. // Physics
  18865. if (this._physicsEngine) {
  18866. this.disablePhysicsEngine();
  18867. }
  18868. // Remove from engine
  18869. index = this._engine.scenes.indexOf(this);
  18870. if (index > -1) {
  18871. this._engine.scenes.splice(index, 1);
  18872. }
  18873. this._engine.wipeCaches();
  18874. this._engine = null;
  18875. this.defaultMaterial = null;
  18876. this.multiMaterials = null;
  18877. this.materials = null;
  18878. };
  18879. Object.defineProperty(Scene.prototype, "isDisposed", {
  18880. get: function () {
  18881. return !this._engine;
  18882. },
  18883. enumerable: true,
  18884. configurable: true
  18885. });
  18886. // Release sounds & sounds tracks
  18887. Scene.prototype.disposeSounds = function () {
  18888. this.mainSoundTrack.dispose();
  18889. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18890. this.soundTracks[scIndex].dispose();
  18891. }
  18892. };
  18893. // Octrees
  18894. Scene.prototype.getWorldExtends = function () {
  18895. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18896. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18897. for (var index = 0; index < this.meshes.length; index++) {
  18898. var mesh = this.meshes[index];
  18899. mesh.computeWorldMatrix(true);
  18900. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18901. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18902. BABYLON.Tools.CheckExtends(minBox, min, max);
  18903. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18904. }
  18905. return {
  18906. min: min,
  18907. max: max
  18908. };
  18909. };
  18910. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18911. if (maxCapacity === void 0) { maxCapacity = 64; }
  18912. if (maxDepth === void 0) { maxDepth = 2; }
  18913. if (!this._selectionOctree) {
  18914. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18915. }
  18916. var worldExtends = this.getWorldExtends();
  18917. // Update octree
  18918. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18919. return this._selectionOctree;
  18920. };
  18921. // Picking
  18922. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18923. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18924. var engine = this._engine;
  18925. if (!camera) {
  18926. if (!this.activeCamera)
  18927. throw new Error("Active camera not set");
  18928. camera = this.activeCamera;
  18929. }
  18930. var cameraViewport = camera.viewport;
  18931. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18932. // Moving coordinates to local viewport world
  18933. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18934. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18935. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18936. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18937. };
  18938. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18939. if (!BABYLON.PickingInfo) {
  18940. return null;
  18941. }
  18942. var engine = this._engine;
  18943. if (!camera) {
  18944. if (!this.activeCamera)
  18945. throw new Error("Active camera not set");
  18946. camera = this.activeCamera;
  18947. }
  18948. var cameraViewport = camera.viewport;
  18949. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18950. var identity = BABYLON.Matrix.Identity();
  18951. // Moving coordinates to local viewport world
  18952. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18953. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18954. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18955. };
  18956. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18957. if (!BABYLON.PickingInfo) {
  18958. return null;
  18959. }
  18960. var pickingInfo = null;
  18961. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18962. var mesh = this.meshes[meshIndex];
  18963. if (predicate) {
  18964. if (!predicate(mesh)) {
  18965. continue;
  18966. }
  18967. }
  18968. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18969. continue;
  18970. }
  18971. var world = mesh.getWorldMatrix();
  18972. var ray = rayFunction(world);
  18973. var result = mesh.intersects(ray, fastCheck);
  18974. if (!result || !result.hit)
  18975. continue;
  18976. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18977. continue;
  18978. pickingInfo = result;
  18979. if (fastCheck) {
  18980. break;
  18981. }
  18982. }
  18983. return pickingInfo || new BABYLON.PickingInfo();
  18984. };
  18985. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18986. if (!BABYLON.PickingInfo) {
  18987. return null;
  18988. }
  18989. var pickingInfos = new Array();
  18990. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18991. var mesh = this.meshes[meshIndex];
  18992. if (predicate) {
  18993. if (!predicate(mesh)) {
  18994. continue;
  18995. }
  18996. }
  18997. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18998. continue;
  18999. }
  19000. var world = mesh.getWorldMatrix();
  19001. var ray = rayFunction(world);
  19002. var result = mesh.intersects(ray, false);
  19003. if (!result || !result.hit)
  19004. continue;
  19005. pickingInfos.push(result);
  19006. }
  19007. return pickingInfos;
  19008. };
  19009. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19010. if (!BABYLON.PickingInfo) {
  19011. return null;
  19012. }
  19013. var pickingInfo = null;
  19014. camera = camera || this.activeCamera;
  19015. if (this.spriteManagers.length > 0) {
  19016. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19017. var spriteManager = this.spriteManagers[spriteIndex];
  19018. if (!spriteManager.isPickable) {
  19019. continue;
  19020. }
  19021. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19022. if (!result || !result.hit)
  19023. continue;
  19024. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19025. continue;
  19026. pickingInfo = result;
  19027. if (fastCheck) {
  19028. break;
  19029. }
  19030. }
  19031. }
  19032. return pickingInfo || new BABYLON.PickingInfo();
  19033. };
  19034. /** Launch a ray to try to pick a mesh in the scene
  19035. * @param x position on screen
  19036. * @param y position on screen
  19037. * @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
  19038. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19039. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19040. */
  19041. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19042. var _this = this;
  19043. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19044. };
  19045. /** Launch a ray to try to pick a sprite in the scene
  19046. * @param x position on screen
  19047. * @param y position on screen
  19048. * @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
  19049. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19050. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19051. */
  19052. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19053. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19054. };
  19055. /** Use the given ray to pick a mesh in the scene
  19056. * @param ray The ray to use to pick meshes
  19057. * @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
  19058. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19059. */
  19060. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19061. var _this = this;
  19062. return this._internalPick(function (world) {
  19063. if (!_this._pickWithRayInverseMatrix) {
  19064. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19065. }
  19066. world.invertToRef(_this._pickWithRayInverseMatrix);
  19067. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19068. }, predicate, fastCheck);
  19069. };
  19070. /**
  19071. * Launch a ray to try to pick a mesh in the scene
  19072. * @param x X position on screen
  19073. * @param y Y position on screen
  19074. * @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
  19075. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19076. */
  19077. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19078. var _this = this;
  19079. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19080. };
  19081. /**
  19082. * Launch a ray to try to pick a mesh in the scene
  19083. * @param ray Ray to use
  19084. * @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
  19085. */
  19086. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19087. var _this = this;
  19088. return this._internalMultiPick(function (world) {
  19089. if (!_this._pickWithRayInverseMatrix) {
  19090. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19091. }
  19092. world.invertToRef(_this._pickWithRayInverseMatrix);
  19093. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19094. }, predicate);
  19095. };
  19096. Scene.prototype.setPointerOverMesh = function (mesh) {
  19097. if (this._pointerOverMesh === mesh) {
  19098. return;
  19099. }
  19100. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19101. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19102. }
  19103. this._pointerOverMesh = mesh;
  19104. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19105. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19106. }
  19107. };
  19108. Scene.prototype.getPointerOverMesh = function () {
  19109. return this._pointerOverMesh;
  19110. };
  19111. Scene.prototype.setPointerOverSprite = function (sprite) {
  19112. if (this._pointerOverSprite === sprite) {
  19113. return;
  19114. }
  19115. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19116. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19117. }
  19118. this._pointerOverSprite = sprite;
  19119. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19120. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19121. }
  19122. };
  19123. Scene.prototype.getPointerOverSprite = function () {
  19124. return this._pointerOverSprite;
  19125. };
  19126. // Physics
  19127. Scene.prototype.getPhysicsEngine = function () {
  19128. return this._physicsEngine;
  19129. };
  19130. /**
  19131. * Enables physics to the current scene
  19132. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19133. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19134. * @return {boolean} was the physics engine initialized
  19135. */
  19136. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19137. if (this._physicsEngine) {
  19138. return true;
  19139. }
  19140. try {
  19141. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19142. return true;
  19143. }
  19144. catch (e) {
  19145. BABYLON.Tools.Error(e.message);
  19146. return false;
  19147. }
  19148. };
  19149. Scene.prototype.disablePhysicsEngine = function () {
  19150. if (!this._physicsEngine) {
  19151. return;
  19152. }
  19153. this._physicsEngine.dispose();
  19154. this._physicsEngine = undefined;
  19155. };
  19156. Scene.prototype.isPhysicsEnabled = function () {
  19157. return this._physicsEngine !== undefined;
  19158. };
  19159. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19160. var mesh = compound.parts[0].mesh;
  19161. mesh.physicsImpostor.dispose();
  19162. mesh.physicsImpostor = null;
  19163. };
  19164. // Misc.
  19165. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19166. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19167. if (replace === void 0) { replace = false; }
  19168. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19169. // Dispose existing camera or light in replace mode.
  19170. if (replace) {
  19171. if (this.activeCamera) {
  19172. this.activeCamera.dispose();
  19173. this.activeCamera = null;
  19174. }
  19175. if (this.lights) {
  19176. for (var i = 0; i < this.lights.length; i++) {
  19177. this.lights[i].dispose();
  19178. }
  19179. }
  19180. }
  19181. // Light
  19182. if (this.lights.length === 0) {
  19183. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19184. }
  19185. // Camera
  19186. if (!this.activeCamera) {
  19187. var worldExtends = this.getWorldExtends();
  19188. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19189. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19190. var camera;
  19191. var radius = worldSize.length() * 1.5;
  19192. if (createArcRotateCamera) {
  19193. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19194. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19195. arcRotateCamera.wheelPrecision = 100 / radius;
  19196. camera = arcRotateCamera;
  19197. }
  19198. else {
  19199. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19200. freeCamera.setTarget(worldCenter);
  19201. camera = freeCamera;
  19202. }
  19203. camera.minZ = radius * 0.01;
  19204. camera.maxZ = radius * 100;
  19205. camera.speed = radius * 0.2;
  19206. this.activeCamera = camera;
  19207. if (attachCameraControls) {
  19208. camera.attachControl(this.getEngine().getRenderingCanvas());
  19209. }
  19210. }
  19211. };
  19212. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19213. if (pbr === void 0) { pbr = false; }
  19214. if (scale === void 0) { scale = 1000; }
  19215. if (blur === void 0) { blur = 0; }
  19216. if (environmentTexture) {
  19217. this.environmentTexture = environmentTexture;
  19218. }
  19219. if (!this.environmentTexture) {
  19220. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19221. return;
  19222. }
  19223. // Skybox
  19224. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19225. if (pbr) {
  19226. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19227. hdrSkyboxMaterial.backFaceCulling = false;
  19228. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19229. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19230. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19231. hdrSkyboxMaterial.disableLighting = true;
  19232. hdrSkyboxMaterial.twoSidedLighting = true;
  19233. hdrSkybox.infiniteDistance = true;
  19234. hdrSkybox.material = hdrSkyboxMaterial;
  19235. }
  19236. else {
  19237. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19238. skyboxMaterial.backFaceCulling = false;
  19239. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19240. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19241. skyboxMaterial.disableLighting = true;
  19242. hdrSkybox.infiniteDistance = true;
  19243. hdrSkybox.material = skyboxMaterial;
  19244. }
  19245. return hdrSkybox;
  19246. };
  19247. Scene.prototype.createDefaultVRExperience = function () {
  19248. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19249. };
  19250. // Tags
  19251. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19252. if (tagsQuery === undefined) {
  19253. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19254. return list;
  19255. }
  19256. var listByTags = [];
  19257. forEach = forEach || (function (item) { return; });
  19258. for (var i in list) {
  19259. var item = list[i];
  19260. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19261. listByTags.push(item);
  19262. forEach(item);
  19263. }
  19264. }
  19265. return listByTags;
  19266. };
  19267. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19268. return this._getByTags(this.meshes, tagsQuery, forEach);
  19269. };
  19270. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19271. return this._getByTags(this.cameras, tagsQuery, forEach);
  19272. };
  19273. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19274. return this._getByTags(this.lights, tagsQuery, forEach);
  19275. };
  19276. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19277. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19278. };
  19279. /**
  19280. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19281. * This allowed control for front to back rendering or reversly depending of the special needs.
  19282. *
  19283. * @param renderingGroupId The rendering group id corresponding to its index
  19284. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19285. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19286. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19287. */
  19288. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19289. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19290. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19291. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19292. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19293. };
  19294. /**
  19295. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19296. *
  19297. * @param renderingGroupId The rendering group id corresponding to its index
  19298. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19299. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19300. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19301. */
  19302. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19303. if (depth === void 0) { depth = true; }
  19304. if (stencil === void 0) { stencil = true; }
  19305. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19306. };
  19307. /**
  19308. * Will flag all materials as dirty to trigger new shader compilation
  19309. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19310. */
  19311. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19312. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19313. var material = _a[_i];
  19314. if (predicate && !predicate(material)) {
  19315. continue;
  19316. }
  19317. material.markAsDirty(flag);
  19318. }
  19319. };
  19320. // Statics
  19321. Scene._FOGMODE_NONE = 0;
  19322. Scene._FOGMODE_EXP = 1;
  19323. Scene._FOGMODE_EXP2 = 2;
  19324. Scene._FOGMODE_LINEAR = 3;
  19325. Scene.MinDeltaTime = 1.0;
  19326. Scene.MaxDeltaTime = 1000.0;
  19327. /** The distance in pixel that you have to move to prevent some events */
  19328. Scene.DragMovementThreshold = 10; // in pixels
  19329. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19330. Scene.LongPressDelay = 500; // in milliseconds
  19331. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19332. Scene.DoubleClickDelay = 300; // in milliseconds
  19333. /** If you need to check double click without raising a single click at first click, enable this flag */
  19334. Scene.ExclusiveDoubleClickMode = false;
  19335. return Scene;
  19336. }());
  19337. BABYLON.Scene = Scene;
  19338. })(BABYLON || (BABYLON = {}));
  19339. //# sourceMappingURL=babylon.scene.js.map
  19340. var BABYLON;
  19341. (function (BABYLON) {
  19342. var Buffer = (function () {
  19343. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19344. if (engine instanceof BABYLON.Mesh) {
  19345. this._engine = engine.getScene().getEngine();
  19346. }
  19347. else {
  19348. this._engine = engine;
  19349. }
  19350. this._updatable = updatable;
  19351. this._data = data;
  19352. this._strideSize = stride;
  19353. if (!postponeInternalCreation) {
  19354. this.create();
  19355. }
  19356. this._instanced = instanced;
  19357. this._instanceDivisor = instanced ? 1 : 0;
  19358. }
  19359. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19360. // a lot of these parameters are ignored as they are overriden by the buffer
  19361. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19362. };
  19363. // Properties
  19364. Buffer.prototype.isUpdatable = function () {
  19365. return this._updatable;
  19366. };
  19367. Buffer.prototype.getData = function () {
  19368. return this._data;
  19369. };
  19370. Buffer.prototype.getBuffer = function () {
  19371. return this._buffer;
  19372. };
  19373. Buffer.prototype.getStrideSize = function () {
  19374. return this._strideSize;
  19375. };
  19376. Buffer.prototype.getIsInstanced = function () {
  19377. return this._instanced;
  19378. };
  19379. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19380. get: function () {
  19381. return this._instanceDivisor;
  19382. },
  19383. set: function (value) {
  19384. this._instanceDivisor = value;
  19385. if (value == 0) {
  19386. this._instanced = false;
  19387. }
  19388. else {
  19389. this._instanced = true;
  19390. }
  19391. },
  19392. enumerable: true,
  19393. configurable: true
  19394. });
  19395. // Methods
  19396. Buffer.prototype.create = function (data) {
  19397. if (!data && this._buffer) {
  19398. return; // nothing to do
  19399. }
  19400. data = data || this._data;
  19401. if (!this._buffer) {
  19402. if (this._updatable) {
  19403. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19404. this._data = data;
  19405. }
  19406. else {
  19407. this._buffer = this._engine.createVertexBuffer(data);
  19408. }
  19409. }
  19410. else if (this._updatable) {
  19411. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19412. this._data = data;
  19413. }
  19414. };
  19415. Buffer.prototype.update = function (data) {
  19416. this.create(data);
  19417. };
  19418. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19419. if (!this._buffer) {
  19420. return;
  19421. }
  19422. if (this._updatable) {
  19423. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19424. this._data = null;
  19425. }
  19426. };
  19427. Buffer.prototype.dispose = function () {
  19428. if (!this._buffer) {
  19429. return;
  19430. }
  19431. if (this._engine._releaseBuffer(this._buffer)) {
  19432. this._buffer = null;
  19433. }
  19434. };
  19435. return Buffer;
  19436. }());
  19437. BABYLON.Buffer = Buffer;
  19438. })(BABYLON || (BABYLON = {}));
  19439. //# sourceMappingURL=babylon.buffer.js.map
  19440. var BABYLON;
  19441. (function (BABYLON) {
  19442. var VertexBuffer = (function () {
  19443. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19444. if (!stride) {
  19445. // Deduce stride from kind
  19446. switch (kind) {
  19447. case VertexBuffer.PositionKind:
  19448. stride = 3;
  19449. break;
  19450. case VertexBuffer.NormalKind:
  19451. stride = 3;
  19452. break;
  19453. case VertexBuffer.UVKind:
  19454. case VertexBuffer.UV2Kind:
  19455. case VertexBuffer.UV3Kind:
  19456. case VertexBuffer.UV4Kind:
  19457. case VertexBuffer.UV5Kind:
  19458. case VertexBuffer.UV6Kind:
  19459. stride = 2;
  19460. break;
  19461. case VertexBuffer.TangentKind:
  19462. case VertexBuffer.ColorKind:
  19463. stride = 4;
  19464. break;
  19465. case VertexBuffer.MatricesIndicesKind:
  19466. case VertexBuffer.MatricesIndicesExtraKind:
  19467. stride = 4;
  19468. break;
  19469. case VertexBuffer.MatricesWeightsKind:
  19470. case VertexBuffer.MatricesWeightsExtraKind:
  19471. stride = 4;
  19472. break;
  19473. }
  19474. }
  19475. if (data instanceof BABYLON.Buffer) {
  19476. if (!stride) {
  19477. stride = data.getStrideSize();
  19478. }
  19479. this._buffer = data;
  19480. this._ownsBuffer = false;
  19481. }
  19482. else {
  19483. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19484. this._ownsBuffer = true;
  19485. }
  19486. this._stride = stride;
  19487. this._offset = offset ? offset : 0;
  19488. this._size = size ? size : stride;
  19489. this._kind = kind;
  19490. }
  19491. /**
  19492. * Returns the kind of the VertexBuffer (string).
  19493. */
  19494. VertexBuffer.prototype.getKind = function () {
  19495. return this._kind;
  19496. };
  19497. // Properties
  19498. /**
  19499. * Boolean : is the VertexBuffer updatable ?
  19500. */
  19501. VertexBuffer.prototype.isUpdatable = function () {
  19502. return this._buffer.isUpdatable();
  19503. };
  19504. /**
  19505. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19506. */
  19507. VertexBuffer.prototype.getData = function () {
  19508. return this._buffer.getData();
  19509. };
  19510. /**
  19511. * Returns the WebGLBuffer associated to the VertexBuffer.
  19512. */
  19513. VertexBuffer.prototype.getBuffer = function () {
  19514. return this._buffer.getBuffer();
  19515. };
  19516. /**
  19517. * Returns the stride of the VertexBuffer (integer).
  19518. */
  19519. VertexBuffer.prototype.getStrideSize = function () {
  19520. return this._stride;
  19521. };
  19522. /**
  19523. * Returns the offset (integer).
  19524. */
  19525. VertexBuffer.prototype.getOffset = function () {
  19526. return this._offset;
  19527. };
  19528. /**
  19529. * Returns the VertexBuffer total size (integer).
  19530. */
  19531. VertexBuffer.prototype.getSize = function () {
  19532. return this._size;
  19533. };
  19534. /**
  19535. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19536. */
  19537. VertexBuffer.prototype.getIsInstanced = function () {
  19538. return this._buffer.getIsInstanced();
  19539. };
  19540. /**
  19541. * Returns the instancing divisor, zero for non-instanced (integer).
  19542. */
  19543. VertexBuffer.prototype.getInstanceDivisor = function () {
  19544. return this._buffer.instanceDivisor;
  19545. };
  19546. // Methods
  19547. /**
  19548. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19549. * Returns the created WebGLBuffer.
  19550. */
  19551. VertexBuffer.prototype.create = function (data) {
  19552. return this._buffer.create(data);
  19553. };
  19554. /**
  19555. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19556. * Returns the updated WebGLBuffer.
  19557. */
  19558. VertexBuffer.prototype.update = function (data) {
  19559. return this._buffer.update(data);
  19560. };
  19561. /**
  19562. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19563. * Returns the directly updated WebGLBuffer.
  19564. */
  19565. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19566. return this._buffer.updateDirectly(data, offset);
  19567. };
  19568. /**
  19569. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19570. */
  19571. VertexBuffer.prototype.dispose = function () {
  19572. if (this._ownsBuffer) {
  19573. this._buffer.dispose();
  19574. }
  19575. };
  19576. Object.defineProperty(VertexBuffer, "PositionKind", {
  19577. get: function () {
  19578. return VertexBuffer._PositionKind;
  19579. },
  19580. enumerable: true,
  19581. configurable: true
  19582. });
  19583. Object.defineProperty(VertexBuffer, "NormalKind", {
  19584. get: function () {
  19585. return VertexBuffer._NormalKind;
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. Object.defineProperty(VertexBuffer, "TangentKind", {
  19591. get: function () {
  19592. return VertexBuffer._TangentKind;
  19593. },
  19594. enumerable: true,
  19595. configurable: true
  19596. });
  19597. Object.defineProperty(VertexBuffer, "UVKind", {
  19598. get: function () {
  19599. return VertexBuffer._UVKind;
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19605. get: function () {
  19606. return VertexBuffer._UV2Kind;
  19607. },
  19608. enumerable: true,
  19609. configurable: true
  19610. });
  19611. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19612. get: function () {
  19613. return VertexBuffer._UV3Kind;
  19614. },
  19615. enumerable: true,
  19616. configurable: true
  19617. });
  19618. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19619. get: function () {
  19620. return VertexBuffer._UV4Kind;
  19621. },
  19622. enumerable: true,
  19623. configurable: true
  19624. });
  19625. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19626. get: function () {
  19627. return VertexBuffer._UV5Kind;
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19633. get: function () {
  19634. return VertexBuffer._UV6Kind;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(VertexBuffer, "ColorKind", {
  19640. get: function () {
  19641. return VertexBuffer._ColorKind;
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19647. get: function () {
  19648. return VertexBuffer._MatricesIndicesKind;
  19649. },
  19650. enumerable: true,
  19651. configurable: true
  19652. });
  19653. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19654. get: function () {
  19655. return VertexBuffer._MatricesWeightsKind;
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19661. get: function () {
  19662. return VertexBuffer._MatricesIndicesExtraKind;
  19663. },
  19664. enumerable: true,
  19665. configurable: true
  19666. });
  19667. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19668. get: function () {
  19669. return VertexBuffer._MatricesWeightsExtraKind;
  19670. },
  19671. enumerable: true,
  19672. configurable: true
  19673. });
  19674. // Enums
  19675. VertexBuffer._PositionKind = "position";
  19676. VertexBuffer._NormalKind = "normal";
  19677. VertexBuffer._TangentKind = "tangent";
  19678. VertexBuffer._UVKind = "uv";
  19679. VertexBuffer._UV2Kind = "uv2";
  19680. VertexBuffer._UV3Kind = "uv3";
  19681. VertexBuffer._UV4Kind = "uv4";
  19682. VertexBuffer._UV5Kind = "uv5";
  19683. VertexBuffer._UV6Kind = "uv6";
  19684. VertexBuffer._ColorKind = "color";
  19685. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19686. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19687. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19688. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19689. return VertexBuffer;
  19690. }());
  19691. BABYLON.VertexBuffer = VertexBuffer;
  19692. })(BABYLON || (BABYLON = {}));
  19693. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19694. var BABYLON;
  19695. (function (BABYLON) {
  19696. var BaseTexture = (function () {
  19697. function BaseTexture(scene) {
  19698. this._hasAlpha = false;
  19699. this.getAlphaFromRGB = false;
  19700. this.level = 1;
  19701. this.coordinatesIndex = 0;
  19702. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  19703. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  19704. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  19705. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  19706. this.isCube = false;
  19707. this.gammaSpace = true;
  19708. this.invertZ = false;
  19709. this.lodLevelInAlpha = false;
  19710. this.lodGenerationOffset = 0.0;
  19711. this.lodGenerationScale = 0.8;
  19712. this.isRenderTarget = false;
  19713. this.animations = new Array();
  19714. /**
  19715. * An event triggered when the texture is disposed.
  19716. * @type {BABYLON.Observable}
  19717. */
  19718. this.onDisposeObservable = new BABYLON.Observable();
  19719. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19720. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  19721. this._scene.textures.push(this);
  19722. this._uid = null;
  19723. }
  19724. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  19725. get: function () {
  19726. return this._hasAlpha;
  19727. },
  19728. set: function (value) {
  19729. if (this._hasAlpha === value) {
  19730. return;
  19731. }
  19732. this._hasAlpha = value;
  19733. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19734. },
  19735. enumerable: true,
  19736. configurable: true
  19737. });
  19738. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  19739. get: function () {
  19740. return this._coordinatesMode;
  19741. },
  19742. set: function (value) {
  19743. if (this._coordinatesMode === value) {
  19744. return;
  19745. }
  19746. this._coordinatesMode = value;
  19747. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(BaseTexture.prototype, "uid", {
  19753. get: function () {
  19754. if (!this._uid) {
  19755. this._uid = BABYLON.Tools.RandomId();
  19756. }
  19757. return this._uid;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. BaseTexture.prototype.toString = function () {
  19763. return this.name;
  19764. };
  19765. BaseTexture.prototype.getClassName = function () {
  19766. return "BaseTexture";
  19767. };
  19768. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  19769. set: function (callback) {
  19770. if (this._onDisposeObserver) {
  19771. this.onDisposeObservable.remove(this._onDisposeObserver);
  19772. }
  19773. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  19779. get: function () {
  19780. return true;
  19781. },
  19782. enumerable: true,
  19783. configurable: true
  19784. });
  19785. BaseTexture.prototype.getScene = function () {
  19786. return this._scene;
  19787. };
  19788. BaseTexture.prototype.getTextureMatrix = function () {
  19789. return null;
  19790. };
  19791. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  19792. return null;
  19793. };
  19794. BaseTexture.prototype.getInternalTexture = function () {
  19795. return this._texture;
  19796. };
  19797. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  19798. return !this.isBlocking || this.isReady();
  19799. };
  19800. BaseTexture.prototype.isReady = function () {
  19801. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19802. this.delayLoad();
  19803. return false;
  19804. }
  19805. if (this._texture) {
  19806. return this._texture.isReady;
  19807. }
  19808. return false;
  19809. };
  19810. BaseTexture.prototype.getSize = function () {
  19811. if (this._texture._width) {
  19812. return new BABYLON.Size(this._texture._width, this._texture._height);
  19813. }
  19814. if (this._texture._size) {
  19815. return new BABYLON.Size(this._texture._size, this._texture._size);
  19816. }
  19817. return BABYLON.Size.Zero();
  19818. };
  19819. BaseTexture.prototype.getBaseSize = function () {
  19820. if (!this.isReady() || !this._texture)
  19821. return BABYLON.Size.Zero();
  19822. if (this._texture._size) {
  19823. return new BABYLON.Size(this._texture._size, this._texture._size);
  19824. }
  19825. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19826. };
  19827. BaseTexture.prototype.scale = function (ratio) {
  19828. };
  19829. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19830. get: function () {
  19831. return false;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19837. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19838. for (var index = 0; index < texturesCache.length; index++) {
  19839. var texturesCacheEntry = texturesCache[index];
  19840. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19841. texturesCache.splice(index, 1);
  19842. return;
  19843. }
  19844. }
  19845. };
  19846. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19847. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19848. for (var index = 0; index < texturesCache.length; index++) {
  19849. var texturesCacheEntry = texturesCache[index];
  19850. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19851. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19852. texturesCacheEntry.references++;
  19853. return texturesCacheEntry;
  19854. }
  19855. }
  19856. }
  19857. return null;
  19858. };
  19859. BaseTexture.prototype.delayLoad = function () {
  19860. };
  19861. BaseTexture.prototype.clone = function () {
  19862. return null;
  19863. };
  19864. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19865. get: function () {
  19866. if (!this._texture) {
  19867. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19868. }
  19869. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  19875. get: function () {
  19876. if (!this._texture) {
  19877. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19878. }
  19879. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19880. },
  19881. enumerable: true,
  19882. configurable: true
  19883. });
  19884. BaseTexture.prototype.readPixels = function (faceIndex) {
  19885. if (faceIndex === void 0) { faceIndex = 0; }
  19886. if (!this._texture) {
  19887. return null;
  19888. }
  19889. var size = this.getSize();
  19890. var engine = this.getScene().getEngine();
  19891. if (this._texture.isCube) {
  19892. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19893. }
  19894. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  19895. };
  19896. BaseTexture.prototype.releaseInternalTexture = function () {
  19897. if (this._texture) {
  19898. this._scene.getEngine().releaseInternalTexture(this._texture);
  19899. delete this._texture;
  19900. }
  19901. };
  19902. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  19903. get: function () {
  19904. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  19905. return null;
  19906. }
  19907. if (!this._texture._sphericalPolynomial) {
  19908. this._texture._sphericalPolynomial =
  19909. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  19910. }
  19911. return this._texture._sphericalPolynomial;
  19912. },
  19913. set: function (value) {
  19914. if (this._texture) {
  19915. this._texture._sphericalPolynomial = value;
  19916. }
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  19922. get: function () {
  19923. if (this._texture) {
  19924. return this._texture._lodTextureHigh;
  19925. }
  19926. return null;
  19927. },
  19928. enumerable: true,
  19929. configurable: true
  19930. });
  19931. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  19932. get: function () {
  19933. if (this._texture) {
  19934. return this._texture._lodTextureMid;
  19935. }
  19936. return null;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  19942. get: function () {
  19943. if (this._texture) {
  19944. return this._texture._lodTextureLow;
  19945. }
  19946. return null;
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. BaseTexture.prototype.dispose = function () {
  19952. // Animations
  19953. this.getScene().stopAnimation(this);
  19954. // Remove from scene
  19955. this._scene._removePendingData(this);
  19956. var index = this._scene.textures.indexOf(this);
  19957. if (index >= 0) {
  19958. this._scene.textures.splice(index, 1);
  19959. }
  19960. if (this._texture === undefined) {
  19961. return;
  19962. }
  19963. // Release
  19964. this.releaseInternalTexture();
  19965. // Callback
  19966. this.onDisposeObservable.notifyObservers(this);
  19967. this.onDisposeObservable.clear();
  19968. };
  19969. BaseTexture.prototype.serialize = function () {
  19970. if (!this.name) {
  19971. return null;
  19972. }
  19973. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19974. // Animations
  19975. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19976. return serializationObject;
  19977. };
  19978. BaseTexture.WhenAllReady = function (textures, callback) {
  19979. var numRemaining = textures.length;
  19980. if (numRemaining === 0) {
  19981. callback();
  19982. return;
  19983. }
  19984. var _loop_1 = function () {
  19985. texture = textures[i];
  19986. if (texture.isReady()) {
  19987. if (--numRemaining === 0) {
  19988. callback();
  19989. }
  19990. }
  19991. else {
  19992. onLoadObservable = texture.onLoadObservable;
  19993. var onLoadCallback_1 = function () {
  19994. onLoadObservable.removeCallback(onLoadCallback_1);
  19995. if (--numRemaining === 0) {
  19996. callback();
  19997. }
  19998. };
  19999. onLoadObservable.add(onLoadCallback_1);
  20000. }
  20001. };
  20002. var texture, onLoadObservable;
  20003. for (var i = 0; i < textures.length; i++) {
  20004. _loop_1();
  20005. }
  20006. };
  20007. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20008. __decorate([
  20009. BABYLON.serialize()
  20010. ], BaseTexture.prototype, "name", void 0);
  20011. __decorate([
  20012. BABYLON.serialize("hasAlpha")
  20013. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20014. __decorate([
  20015. BABYLON.serialize()
  20016. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20017. __decorate([
  20018. BABYLON.serialize()
  20019. ], BaseTexture.prototype, "level", void 0);
  20020. __decorate([
  20021. BABYLON.serialize()
  20022. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20023. __decorate([
  20024. BABYLON.serialize("coordinatesMode")
  20025. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20026. __decorate([
  20027. BABYLON.serialize()
  20028. ], BaseTexture.prototype, "wrapU", void 0);
  20029. __decorate([
  20030. BABYLON.serialize()
  20031. ], BaseTexture.prototype, "wrapV", void 0);
  20032. __decorate([
  20033. BABYLON.serialize()
  20034. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20035. __decorate([
  20036. BABYLON.serialize()
  20037. ], BaseTexture.prototype, "isCube", void 0);
  20038. __decorate([
  20039. BABYLON.serialize()
  20040. ], BaseTexture.prototype, "gammaSpace", void 0);
  20041. __decorate([
  20042. BABYLON.serialize()
  20043. ], BaseTexture.prototype, "invertZ", void 0);
  20044. __decorate([
  20045. BABYLON.serialize()
  20046. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20047. __decorate([
  20048. BABYLON.serialize()
  20049. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20050. __decorate([
  20051. BABYLON.serialize()
  20052. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20053. __decorate([
  20054. BABYLON.serialize()
  20055. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20056. return BaseTexture;
  20057. }());
  20058. BABYLON.BaseTexture = BaseTexture;
  20059. })(BABYLON || (BABYLON = {}));
  20060. //# sourceMappingURL=babylon.baseTexture.js.map
  20061. var BABYLON;
  20062. (function (BABYLON) {
  20063. var Texture = (function (_super) {
  20064. __extends(Texture, _super);
  20065. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20066. if (noMipmap === void 0) { noMipmap = false; }
  20067. if (invertY === void 0) { invertY = true; }
  20068. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20069. if (onLoad === void 0) { onLoad = null; }
  20070. if (onError === void 0) { onError = null; }
  20071. if (buffer === void 0) { buffer = null; }
  20072. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20073. var _this = _super.call(this, scene) || this;
  20074. _this.uOffset = 0;
  20075. _this.vOffset = 0;
  20076. _this.uScale = 1.0;
  20077. _this.vScale = 1.0;
  20078. _this.uAng = 0;
  20079. _this.vAng = 0;
  20080. _this.wAng = 0;
  20081. _this._isBlocking = true;
  20082. _this.name = url;
  20083. _this.url = url;
  20084. _this._noMipmap = noMipmap;
  20085. _this._invertY = invertY;
  20086. _this._samplingMode = samplingMode;
  20087. _this._buffer = buffer;
  20088. _this._deleteBuffer = deleteBuffer;
  20089. _this._format = format;
  20090. scene = _this.getScene();
  20091. var load = function () {
  20092. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20093. _this.onLoadObservable.notifyObservers(_this);
  20094. }
  20095. if (onLoad) {
  20096. onLoad();
  20097. }
  20098. if (!_this.isBlocking) {
  20099. scene.resetCachedMaterial();
  20100. }
  20101. };
  20102. if (!url) {
  20103. _this._delayedOnLoad = load;
  20104. _this._delayedOnError = onError;
  20105. return _this;
  20106. }
  20107. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20108. if (!_this._texture) {
  20109. if (!scene.useDelayedTextureLoading) {
  20110. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20111. if (deleteBuffer) {
  20112. delete _this._buffer;
  20113. }
  20114. }
  20115. else {
  20116. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20117. _this._delayedOnLoad = load;
  20118. _this._delayedOnError = onError;
  20119. }
  20120. }
  20121. else {
  20122. if (_this._texture.isReady) {
  20123. BABYLON.Tools.SetImmediate(function () { return load(); });
  20124. }
  20125. else {
  20126. _this._texture.onLoadedCallbacks.push(load);
  20127. }
  20128. }
  20129. return _this;
  20130. }
  20131. Object.defineProperty(Texture.prototype, "noMipmap", {
  20132. get: function () {
  20133. return this._noMipmap;
  20134. },
  20135. enumerable: true,
  20136. configurable: true
  20137. });
  20138. Object.defineProperty(Texture.prototype, "isBlocking", {
  20139. get: function () {
  20140. return this._isBlocking;
  20141. },
  20142. set: function (value) {
  20143. this._isBlocking = value;
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. Object.defineProperty(Texture.prototype, "samplingMode", {
  20149. get: function () {
  20150. return this._samplingMode;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Texture.prototype.updateURL = function (url) {
  20156. this.url = url;
  20157. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20158. this.delayLoad();
  20159. };
  20160. Texture.prototype.delayLoad = function () {
  20161. var _this = this;
  20162. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20163. return;
  20164. }
  20165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20166. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20167. if (!this._texture) {
  20168. 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);
  20169. if (this._deleteBuffer) {
  20170. delete this._buffer;
  20171. }
  20172. }
  20173. else {
  20174. if (this._texture.isReady) {
  20175. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20176. }
  20177. else {
  20178. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  20179. }
  20180. }
  20181. };
  20182. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20183. if (!this._texture) {
  20184. return;
  20185. }
  20186. this._samplingMode = samplingMode;
  20187. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20188. };
  20189. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20190. x *= this.uScale;
  20191. y *= this.vScale;
  20192. x -= 0.5 * this.uScale;
  20193. y -= 0.5 * this.vScale;
  20194. z -= 0.5;
  20195. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20196. t.x += 0.5 * this.uScale + this.uOffset;
  20197. t.y += 0.5 * this.vScale + this.vOffset;
  20198. t.z += 0.5;
  20199. };
  20200. Texture.prototype.getTextureMatrix = function () {
  20201. var _this = this;
  20202. if (this.uOffset === this._cachedUOffset &&
  20203. this.vOffset === this._cachedVOffset &&
  20204. this.uScale === this._cachedUScale &&
  20205. this.vScale === this._cachedVScale &&
  20206. this.uAng === this._cachedUAng &&
  20207. this.vAng === this._cachedVAng &&
  20208. this.wAng === this._cachedWAng) {
  20209. return this._cachedTextureMatrix;
  20210. }
  20211. this._cachedUOffset = this.uOffset;
  20212. this._cachedVOffset = this.vOffset;
  20213. this._cachedUScale = this.uScale;
  20214. this._cachedVScale = this.vScale;
  20215. this._cachedUAng = this.uAng;
  20216. this._cachedVAng = this.vAng;
  20217. this._cachedWAng = this.wAng;
  20218. if (!this._cachedTextureMatrix) {
  20219. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20220. this._rowGenerationMatrix = new BABYLON.Matrix();
  20221. this._t0 = BABYLON.Vector3.Zero();
  20222. this._t1 = BABYLON.Vector3.Zero();
  20223. this._t2 = BABYLON.Vector3.Zero();
  20224. }
  20225. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20226. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20227. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20228. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20229. this._t1.subtractInPlace(this._t0);
  20230. this._t2.subtractInPlace(this._t0);
  20231. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20232. this._cachedTextureMatrix.m[0] = this._t1.x;
  20233. this._cachedTextureMatrix.m[1] = this._t1.y;
  20234. this._cachedTextureMatrix.m[2] = this._t1.z;
  20235. this._cachedTextureMatrix.m[4] = this._t2.x;
  20236. this._cachedTextureMatrix.m[5] = this._t2.y;
  20237. this._cachedTextureMatrix.m[6] = this._t2.z;
  20238. this._cachedTextureMatrix.m[8] = this._t0.x;
  20239. this._cachedTextureMatrix.m[9] = this._t0.y;
  20240. this._cachedTextureMatrix.m[10] = this._t0.z;
  20241. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20242. return mat.hasTexture(_this);
  20243. });
  20244. return this._cachedTextureMatrix;
  20245. };
  20246. Texture.prototype.getReflectionTextureMatrix = function () {
  20247. var _this = this;
  20248. var scene = this.getScene();
  20249. if (this.uOffset === this._cachedUOffset &&
  20250. this.vOffset === this._cachedVOffset &&
  20251. this.uScale === this._cachedUScale &&
  20252. this.vScale === this._cachedVScale &&
  20253. this.coordinatesMode === this._cachedCoordinatesMode) {
  20254. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20255. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20256. return this._cachedTextureMatrix;
  20257. }
  20258. }
  20259. else {
  20260. return this._cachedTextureMatrix;
  20261. }
  20262. }
  20263. if (!this._cachedTextureMatrix) {
  20264. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20265. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20266. }
  20267. this._cachedUOffset = this.uOffset;
  20268. this._cachedVOffset = this.vOffset;
  20269. this._cachedUScale = this.uScale;
  20270. this._cachedVScale = this.vScale;
  20271. this._cachedCoordinatesMode = this.coordinatesMode;
  20272. switch (this.coordinatesMode) {
  20273. case Texture.PLANAR_MODE:
  20274. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20275. this._cachedTextureMatrix[0] = this.uScale;
  20276. this._cachedTextureMatrix[5] = this.vScale;
  20277. this._cachedTextureMatrix[12] = this.uOffset;
  20278. this._cachedTextureMatrix[13] = this.vOffset;
  20279. break;
  20280. case Texture.PROJECTION_MODE:
  20281. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20282. this._projectionModeMatrix.m[0] = 0.5;
  20283. this._projectionModeMatrix.m[5] = -0.5;
  20284. this._projectionModeMatrix.m[10] = 0.0;
  20285. this._projectionModeMatrix.m[12] = 0.5;
  20286. this._projectionModeMatrix.m[13] = 0.5;
  20287. this._projectionModeMatrix.m[14] = 1.0;
  20288. this._projectionModeMatrix.m[15] = 1.0;
  20289. var projectionMatrix = scene.getProjectionMatrix();
  20290. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20291. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20292. break;
  20293. default:
  20294. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20295. break;
  20296. }
  20297. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20298. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20299. });
  20300. return this._cachedTextureMatrix;
  20301. };
  20302. Texture.prototype.clone = function () {
  20303. var _this = this;
  20304. return BABYLON.SerializationHelper.Clone(function () {
  20305. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20306. }, this);
  20307. };
  20308. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20309. get: function () {
  20310. if (!this._onLoadObservable) {
  20311. this._onLoadObservable = new BABYLON.Observable();
  20312. }
  20313. return this._onLoadObservable;
  20314. },
  20315. enumerable: true,
  20316. configurable: true
  20317. });
  20318. Texture.prototype.serialize = function () {
  20319. var serializationObject = _super.prototype.serialize.call(this);
  20320. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20321. serializationObject.base64String = this._buffer;
  20322. serializationObject.name = serializationObject.name.replace("data:", "");
  20323. }
  20324. return serializationObject;
  20325. };
  20326. Texture.prototype.getClassName = function () {
  20327. return "Texture";
  20328. };
  20329. Texture.prototype.dispose = function () {
  20330. _super.prototype.dispose.call(this);
  20331. if (this.onLoadObservable) {
  20332. this.onLoadObservable.clear();
  20333. this._onLoadObservable = null;
  20334. }
  20335. this._delayedOnLoad = null;
  20336. this._delayedOnError = null;
  20337. };
  20338. // Statics
  20339. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20340. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20341. if (onLoad === void 0) { onLoad = null; }
  20342. if (onError === void 0) { onError = null; }
  20343. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20344. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20345. };
  20346. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20347. if (parsedTexture.customType) {
  20348. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20349. // Update Sampling Mode
  20350. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20351. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20352. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20353. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20354. }
  20355. }
  20356. return parsedCustomTexture;
  20357. }
  20358. if (parsedTexture.isCube) {
  20359. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20360. }
  20361. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20362. return null;
  20363. }
  20364. var texture = BABYLON.SerializationHelper.Parse(function () {
  20365. if (parsedTexture.mirrorPlane) {
  20366. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20367. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20368. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20369. return mirrorTexture;
  20370. }
  20371. else if (parsedTexture.isRenderTarget) {
  20372. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20373. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20374. return renderTargetTexture;
  20375. }
  20376. else {
  20377. var texture;
  20378. if (parsedTexture.base64String) {
  20379. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20380. }
  20381. else {
  20382. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20383. }
  20384. return texture;
  20385. }
  20386. }, parsedTexture, scene);
  20387. // Update Sampling Mode
  20388. if (parsedTexture.samplingMode) {
  20389. var sampling = parsedTexture.samplingMode;
  20390. if (texture._samplingMode !== sampling) {
  20391. texture.updateSamplingMode(sampling);
  20392. }
  20393. }
  20394. // Animations
  20395. if (parsedTexture.animations) {
  20396. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20397. var parsedAnimation = parsedTexture.animations[animationIndex];
  20398. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20399. }
  20400. }
  20401. return texture;
  20402. };
  20403. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20404. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20405. if (noMipmap === void 0) { noMipmap = false; }
  20406. if (invertY === void 0) { invertY = true; }
  20407. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20408. if (onLoad === void 0) { onLoad = null; }
  20409. if (onError === void 0) { onError = null; }
  20410. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20411. if (name.substr(0, 5) !== "data:") {
  20412. name = "data:" + name;
  20413. }
  20414. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20415. };
  20416. // Constants
  20417. Texture.NEAREST_SAMPLINGMODE = 1;
  20418. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20419. Texture.BILINEAR_SAMPLINGMODE = 2;
  20420. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20421. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20422. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20423. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20424. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20425. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20426. Texture.NEAREST_LINEAR = 7;
  20427. Texture.NEAREST_NEAREST = 8;
  20428. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20429. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20430. Texture.LINEAR_LINEAR = 11;
  20431. Texture.LINEAR_NEAREST = 12;
  20432. Texture.EXPLICIT_MODE = 0;
  20433. Texture.SPHERICAL_MODE = 1;
  20434. Texture.PLANAR_MODE = 2;
  20435. Texture.CUBIC_MODE = 3;
  20436. Texture.PROJECTION_MODE = 4;
  20437. Texture.SKYBOX_MODE = 5;
  20438. Texture.INVCUBIC_MODE = 6;
  20439. Texture.EQUIRECTANGULAR_MODE = 7;
  20440. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20441. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20442. Texture.CLAMP_ADDRESSMODE = 0;
  20443. Texture.WRAP_ADDRESSMODE = 1;
  20444. Texture.MIRROR_ADDRESSMODE = 2;
  20445. __decorate([
  20446. BABYLON.serialize()
  20447. ], Texture.prototype, "url", void 0);
  20448. __decorate([
  20449. BABYLON.serialize()
  20450. ], Texture.prototype, "uOffset", void 0);
  20451. __decorate([
  20452. BABYLON.serialize()
  20453. ], Texture.prototype, "vOffset", void 0);
  20454. __decorate([
  20455. BABYLON.serialize()
  20456. ], Texture.prototype, "uScale", void 0);
  20457. __decorate([
  20458. BABYLON.serialize()
  20459. ], Texture.prototype, "vScale", void 0);
  20460. __decorate([
  20461. BABYLON.serialize()
  20462. ], Texture.prototype, "uAng", void 0);
  20463. __decorate([
  20464. BABYLON.serialize()
  20465. ], Texture.prototype, "vAng", void 0);
  20466. __decorate([
  20467. BABYLON.serialize()
  20468. ], Texture.prototype, "wAng", void 0);
  20469. __decorate([
  20470. BABYLON.serialize()
  20471. ], Texture.prototype, "isBlocking", null);
  20472. return Texture;
  20473. }(BABYLON.BaseTexture));
  20474. BABYLON.Texture = Texture;
  20475. })(BABYLON || (BABYLON = {}));
  20476. //# sourceMappingURL=babylon.texture.js.map
  20477. var BABYLON;
  20478. (function (BABYLON) {
  20479. var _InstancesBatch = (function () {
  20480. function _InstancesBatch() {
  20481. this.mustReturn = false;
  20482. this.visibleInstances = new Array();
  20483. this.renderSelf = new Array();
  20484. }
  20485. return _InstancesBatch;
  20486. }());
  20487. BABYLON._InstancesBatch = _InstancesBatch;
  20488. var Mesh = (function (_super) {
  20489. __extends(Mesh, _super);
  20490. /**
  20491. * @constructor
  20492. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20493. * @param {Scene} scene The scene to add this mesh to.
  20494. * @param {Node} parent The parent of this mesh, if it has one
  20495. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20496. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20497. * When false, achieved by calling a clone(), also passing False.
  20498. * This will make creation of children, recursive.
  20499. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20500. */
  20501. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20502. if (parent === void 0) { parent = null; }
  20503. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20504. var _this = _super.call(this, name, scene) || this;
  20505. // Events
  20506. /**
  20507. * An event triggered before rendering the mesh
  20508. * @type {BABYLON.Observable}
  20509. */
  20510. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20511. /**
  20512. * An event triggered after rendering the mesh
  20513. * @type {BABYLON.Observable}
  20514. */
  20515. _this.onAfterRenderObservable = new BABYLON.Observable();
  20516. /**
  20517. * An event triggered before drawing the mesh
  20518. * @type {BABYLON.Observable}
  20519. */
  20520. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20521. // Members
  20522. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20523. _this.instances = new Array();
  20524. _this._LODLevels = new Array();
  20525. _this._visibleInstances = {};
  20526. _this._renderIdForInstances = new Array();
  20527. _this._batchCache = new _InstancesBatch();
  20528. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20529. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20530. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20531. // Will be used to save a source mesh reference, If any
  20532. _this._source = null;
  20533. if (source) {
  20534. // Source mesh
  20535. _this._source = source;
  20536. // Geometry
  20537. if (source._geometry) {
  20538. source._geometry.applyToMesh(_this);
  20539. }
  20540. // Deep copy
  20541. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20542. // Parent
  20543. _this.parent = source.parent;
  20544. // Pivot
  20545. _this.setPivotMatrix(source.getPivotMatrix());
  20546. _this.id = name + "." + source.id;
  20547. // Material
  20548. _this.material = source.material;
  20549. var index;
  20550. if (!doNotCloneChildren) {
  20551. // Children
  20552. for (index = 0; index < scene.meshes.length; index++) {
  20553. var mesh = scene.meshes[index];
  20554. if (mesh.parent === source) {
  20555. // doNotCloneChildren is always going to be False
  20556. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20557. }
  20558. }
  20559. }
  20560. // Physics clone
  20561. var physicsEngine = _this.getScene().getPhysicsEngine();
  20562. if (clonePhysicsImpostor && physicsEngine) {
  20563. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20564. if (impostor) {
  20565. _this.physicsImpostor = impostor.clone(_this);
  20566. }
  20567. }
  20568. // Particles
  20569. for (index = 0; index < scene.particleSystems.length; index++) {
  20570. var system = scene.particleSystems[index];
  20571. if (system.emitter === source) {
  20572. system.clone(system.name, _this);
  20573. }
  20574. }
  20575. _this.computeWorldMatrix(true);
  20576. }
  20577. // Parent
  20578. if (parent !== null) {
  20579. _this.parent = parent;
  20580. }
  20581. return _this;
  20582. }
  20583. Object.defineProperty(Mesh, "FRONTSIDE", {
  20584. /**
  20585. * Mesh side orientation : usually the external or front surface
  20586. */
  20587. get: function () {
  20588. return Mesh._FRONTSIDE;
  20589. },
  20590. enumerable: true,
  20591. configurable: true
  20592. });
  20593. Object.defineProperty(Mesh, "BACKSIDE", {
  20594. /**
  20595. * Mesh side orientation : usually the internal or back surface
  20596. */
  20597. get: function () {
  20598. return Mesh._BACKSIDE;
  20599. },
  20600. enumerable: true,
  20601. configurable: true
  20602. });
  20603. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20604. /**
  20605. * Mesh side orientation : both internal and external or front and back surfaces
  20606. */
  20607. get: function () {
  20608. return Mesh._DOUBLESIDE;
  20609. },
  20610. enumerable: true,
  20611. configurable: true
  20612. });
  20613. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20614. /**
  20615. * Mesh side orientation : by default, `FRONTSIDE`
  20616. */
  20617. get: function () {
  20618. return Mesh._DEFAULTSIDE;
  20619. },
  20620. enumerable: true,
  20621. configurable: true
  20622. });
  20623. Object.defineProperty(Mesh, "NO_CAP", {
  20624. /**
  20625. * Mesh cap setting : no cap
  20626. */
  20627. get: function () {
  20628. return Mesh._NO_CAP;
  20629. },
  20630. enumerable: true,
  20631. configurable: true
  20632. });
  20633. Object.defineProperty(Mesh, "CAP_START", {
  20634. /**
  20635. * Mesh cap setting : one cap at the beginning of the mesh
  20636. */
  20637. get: function () {
  20638. return Mesh._CAP_START;
  20639. },
  20640. enumerable: true,
  20641. configurable: true
  20642. });
  20643. Object.defineProperty(Mesh, "CAP_END", {
  20644. /**
  20645. * Mesh cap setting : one cap at the end of the mesh
  20646. */
  20647. get: function () {
  20648. return Mesh._CAP_END;
  20649. },
  20650. enumerable: true,
  20651. configurable: true
  20652. });
  20653. Object.defineProperty(Mesh, "CAP_ALL", {
  20654. /**
  20655. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20656. */
  20657. get: function () {
  20658. return Mesh._CAP_ALL;
  20659. },
  20660. enumerable: true,
  20661. configurable: true
  20662. });
  20663. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20664. set: function (callback) {
  20665. if (this._onBeforeDrawObserver) {
  20666. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20667. }
  20668. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20669. },
  20670. enumerable: true,
  20671. configurable: true
  20672. });
  20673. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  20674. get: function () {
  20675. return this._morphTargetManager;
  20676. },
  20677. set: function (value) {
  20678. if (this._morphTargetManager === value) {
  20679. return;
  20680. }
  20681. this._morphTargetManager = value;
  20682. this._syncGeometryWithMorphTargetManager();
  20683. },
  20684. enumerable: true,
  20685. configurable: true
  20686. });
  20687. Object.defineProperty(Mesh.prototype, "source", {
  20688. get: function () {
  20689. return this._source;
  20690. },
  20691. enumerable: true,
  20692. configurable: true
  20693. });
  20694. // Methods
  20695. /**
  20696. * Returns the string "Mesh".
  20697. */
  20698. Mesh.prototype.getClassName = function () {
  20699. return "Mesh";
  20700. };
  20701. /**
  20702. * Returns a string.
  20703. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20704. */
  20705. Mesh.prototype.toString = function (fullDetails) {
  20706. var ret = _super.prototype.toString.call(this, fullDetails);
  20707. ret += ", n vertices: " + this.getTotalVertices();
  20708. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20709. if (this.animations) {
  20710. for (var i = 0; i < this.animations.length; i++) {
  20711. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20712. }
  20713. }
  20714. if (fullDetails) {
  20715. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20716. }
  20717. return ret;
  20718. };
  20719. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20720. /**
  20721. * True if the mesh has some Levels Of Details (LOD).
  20722. * Returns a boolean.
  20723. */
  20724. get: function () {
  20725. return this._LODLevels.length > 0;
  20726. },
  20727. enumerable: true,
  20728. configurable: true
  20729. });
  20730. Mesh.prototype._sortLODLevels = function () {
  20731. this._LODLevels.sort(function (a, b) {
  20732. if (a.distance < b.distance) {
  20733. return 1;
  20734. }
  20735. if (a.distance > b.distance) {
  20736. return -1;
  20737. }
  20738. return 0;
  20739. });
  20740. };
  20741. /**
  20742. * Add a mesh as LOD level triggered at the given distance.
  20743. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20744. * @param {number} distance The distance from the center of the object to show this level
  20745. * @param {Mesh} mesh The mesh to be added as LOD level
  20746. * @return {Mesh} This mesh (for chaining)
  20747. */
  20748. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20749. if (mesh && mesh._masterMesh) {
  20750. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20751. return this;
  20752. }
  20753. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20754. this._LODLevels.push(level);
  20755. if (mesh) {
  20756. mesh._masterMesh = this;
  20757. }
  20758. this._sortLODLevels();
  20759. return this;
  20760. };
  20761. /**
  20762. * Returns the LOD level mesh at the passed distance or null if not found.
  20763. * It is related to the method `addLODLevel(distance, mesh)`.
  20764. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20765. * Returns an object Mesh or `null`.
  20766. */
  20767. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20768. for (var index = 0; index < this._LODLevels.length; index++) {
  20769. var level = this._LODLevels[index];
  20770. if (level.distance === distance) {
  20771. return level.mesh;
  20772. }
  20773. }
  20774. return null;
  20775. };
  20776. /**
  20777. * Remove a mesh from the LOD array
  20778. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20779. * @param {Mesh} mesh The mesh to be removed.
  20780. * @return {Mesh} This mesh (for chaining)
  20781. */
  20782. Mesh.prototype.removeLODLevel = function (mesh) {
  20783. for (var index = 0; index < this._LODLevels.length; index++) {
  20784. if (this._LODLevels[index].mesh === mesh) {
  20785. this._LODLevels.splice(index, 1);
  20786. if (mesh) {
  20787. mesh._masterMesh = null;
  20788. }
  20789. }
  20790. }
  20791. this._sortLODLevels();
  20792. return this;
  20793. };
  20794. /**
  20795. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20796. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20797. */
  20798. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20799. if (!this._LODLevels || this._LODLevels.length === 0) {
  20800. return this;
  20801. }
  20802. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20803. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20804. if (this.onLODLevelSelection) {
  20805. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20806. }
  20807. return this;
  20808. }
  20809. for (var index = 0; index < this._LODLevels.length; index++) {
  20810. var level = this._LODLevels[index];
  20811. if (level.distance < distanceToCamera) {
  20812. if (level.mesh) {
  20813. level.mesh._preActivate();
  20814. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20815. }
  20816. if (this.onLODLevelSelection) {
  20817. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20818. }
  20819. return level.mesh;
  20820. }
  20821. }
  20822. if (this.onLODLevelSelection) {
  20823. this.onLODLevelSelection(distanceToCamera, this, this);
  20824. }
  20825. return this;
  20826. };
  20827. Object.defineProperty(Mesh.prototype, "geometry", {
  20828. /**
  20829. * Returns the mesh internal Geometry object.
  20830. */
  20831. get: function () {
  20832. return this._geometry;
  20833. },
  20834. enumerable: true,
  20835. configurable: true
  20836. });
  20837. /**
  20838. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20839. */
  20840. Mesh.prototype.getTotalVertices = function () {
  20841. if (!this._geometry) {
  20842. return 0;
  20843. }
  20844. return this._geometry.getTotalVertices();
  20845. };
  20846. /**
  20847. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20848. * 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.
  20849. * You can force the copy with forceCopy === true
  20850. * Returns null if the mesh has no geometry or no vertex buffer.
  20851. * Possible `kind` values :
  20852. * - BABYLON.VertexBuffer.PositionKind
  20853. * - BABYLON.VertexBuffer.UVKind
  20854. * - BABYLON.VertexBuffer.UV2Kind
  20855. * - BABYLON.VertexBuffer.UV3Kind
  20856. * - BABYLON.VertexBuffer.UV4Kind
  20857. * - BABYLON.VertexBuffer.UV5Kind
  20858. * - BABYLON.VertexBuffer.UV6Kind
  20859. * - BABYLON.VertexBuffer.ColorKind
  20860. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20861. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20862. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20863. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20864. */
  20865. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  20866. if (!this._geometry) {
  20867. return null;
  20868. }
  20869. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  20870. };
  20871. /**
  20872. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20873. * Returns `undefined` if the mesh has no geometry.
  20874. * Possible `kind` values :
  20875. * - BABYLON.VertexBuffer.PositionKind
  20876. * - BABYLON.VertexBuffer.UVKind
  20877. * - BABYLON.VertexBuffer.UV2Kind
  20878. * - BABYLON.VertexBuffer.UV3Kind
  20879. * - BABYLON.VertexBuffer.UV4Kind
  20880. * - BABYLON.VertexBuffer.UV5Kind
  20881. * - BABYLON.VertexBuffer.UV6Kind
  20882. * - BABYLON.VertexBuffer.ColorKind
  20883. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20884. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20885. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20886. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20887. */
  20888. Mesh.prototype.getVertexBuffer = function (kind) {
  20889. if (!this._geometry) {
  20890. return undefined;
  20891. }
  20892. return this._geometry.getVertexBuffer(kind);
  20893. };
  20894. /**
  20895. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20896. * Possible `kind` values :
  20897. * - BABYLON.VertexBuffer.PositionKind
  20898. * - BABYLON.VertexBuffer.UVKind
  20899. * - BABYLON.VertexBuffer.UV2Kind
  20900. * - BABYLON.VertexBuffer.UV3Kind
  20901. * - BABYLON.VertexBuffer.UV4Kind
  20902. * - BABYLON.VertexBuffer.UV5Kind
  20903. * - BABYLON.VertexBuffer.UV6Kind
  20904. * - BABYLON.VertexBuffer.ColorKind
  20905. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20906. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20907. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20908. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20909. */
  20910. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20911. if (!this._geometry) {
  20912. if (this._delayInfo) {
  20913. return this._delayInfo.indexOf(kind) !== -1;
  20914. }
  20915. return false;
  20916. }
  20917. return this._geometry.isVerticesDataPresent(kind);
  20918. };
  20919. /**
  20920. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20921. * Possible `kind` values :
  20922. * - BABYLON.VertexBuffer.PositionKind
  20923. * - BABYLON.VertexBuffer.UVKind
  20924. * - BABYLON.VertexBuffer.UV2Kind
  20925. * - BABYLON.VertexBuffer.UV3Kind
  20926. * - BABYLON.VertexBuffer.UV4Kind
  20927. * - BABYLON.VertexBuffer.UV5Kind
  20928. * - BABYLON.VertexBuffer.UV6Kind
  20929. * - BABYLON.VertexBuffer.ColorKind
  20930. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20931. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20932. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20933. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20934. */
  20935. Mesh.prototype.getVerticesDataKinds = function () {
  20936. if (!this._geometry) {
  20937. var result = [];
  20938. if (this._delayInfo) {
  20939. this._delayInfo.forEach(function (kind, index, array) {
  20940. result.push(kind);
  20941. });
  20942. }
  20943. return result;
  20944. }
  20945. return this._geometry.getVerticesDataKinds();
  20946. };
  20947. /**
  20948. * Returns a positive integer : the total number of indices in this mesh geometry.
  20949. * Returns zero if the mesh has no geometry.
  20950. */
  20951. Mesh.prototype.getTotalIndices = function () {
  20952. if (!this._geometry) {
  20953. return 0;
  20954. }
  20955. return this._geometry.getTotalIndices();
  20956. };
  20957. /**
  20958. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20959. * 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.
  20960. * Returns an empty array if the mesh has no geometry.
  20961. */
  20962. Mesh.prototype.getIndices = function (copyWhenShared) {
  20963. if (!this._geometry) {
  20964. return [];
  20965. }
  20966. return this._geometry.getIndices(copyWhenShared);
  20967. };
  20968. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20969. get: function () {
  20970. return this._masterMesh !== null && this._masterMesh !== undefined;
  20971. },
  20972. enumerable: true,
  20973. configurable: true
  20974. });
  20975. /**
  20976. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20977. */
  20978. Mesh.prototype.isReady = function () {
  20979. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20980. return false;
  20981. }
  20982. return _super.prototype.isReady.call(this);
  20983. };
  20984. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20985. get: function () {
  20986. return this._sideOrientation;
  20987. },
  20988. /**
  20989. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20990. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20991. */
  20992. set: function (sideO) {
  20993. this._sideOrientation = sideO;
  20994. },
  20995. enumerable: true,
  20996. configurable: true
  20997. });
  20998. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20999. /**
  21000. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21001. * This property is pertinent only for updatable parametric shapes.
  21002. */
  21003. get: function () {
  21004. return this._areNormalsFrozen;
  21005. },
  21006. enumerable: true,
  21007. configurable: true
  21008. });
  21009. /**
  21010. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21011. * It has no effect at all on other shapes.
  21012. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21013. * Returns the Mesh.
  21014. */
  21015. Mesh.prototype.freezeNormals = function () {
  21016. this._areNormalsFrozen = true;
  21017. return this;
  21018. };
  21019. /**
  21020. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21021. * It has no effect at all on other shapes.
  21022. * It reactivates the mesh normals computation if it was previously frozen.
  21023. * Returns the Mesh.
  21024. */
  21025. Mesh.prototype.unfreezeNormals = function () {
  21026. this._areNormalsFrozen = false;
  21027. return this;
  21028. };
  21029. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21030. /**
  21031. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21032. */
  21033. set: function (count) {
  21034. this._overridenInstanceCount = count;
  21035. },
  21036. enumerable: true,
  21037. configurable: true
  21038. });
  21039. // Methods
  21040. Mesh.prototype._preActivate = function () {
  21041. var sceneRenderId = this.getScene().getRenderId();
  21042. if (this._preActivateId === sceneRenderId) {
  21043. return this;
  21044. }
  21045. this._preActivateId = sceneRenderId;
  21046. this._visibleInstances = null;
  21047. return this;
  21048. };
  21049. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21050. if (this._visibleInstances) {
  21051. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21052. }
  21053. return this;
  21054. };
  21055. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21056. if (!this._visibleInstances) {
  21057. this._visibleInstances = {};
  21058. this._visibleInstances.defaultRenderId = renderId;
  21059. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21060. }
  21061. if (!this._visibleInstances[renderId]) {
  21062. this._visibleInstances[renderId] = new Array();
  21063. }
  21064. this._visibleInstances[renderId].push(instance);
  21065. return this;
  21066. };
  21067. /**
  21068. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21069. * This means the mesh underlying bounding box and sphere are recomputed.
  21070. * Returns the Mesh.
  21071. */
  21072. Mesh.prototype.refreshBoundingInfo = function () {
  21073. if (this._boundingInfo.isLocked) {
  21074. return;
  21075. }
  21076. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21077. if (data) {
  21078. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21079. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21080. }
  21081. if (this.subMeshes) {
  21082. for (var index = 0; index < this.subMeshes.length; index++) {
  21083. this.subMeshes[index].refreshBoundingInfo();
  21084. }
  21085. }
  21086. this._updateBoundingInfo();
  21087. return this;
  21088. };
  21089. Mesh.prototype._createGlobalSubMesh = function (force) {
  21090. var totalVertices = this.getTotalVertices();
  21091. if (!totalVertices || !this.getIndices()) {
  21092. return null;
  21093. }
  21094. // Check if we need to recreate the submeshes
  21095. if (this.subMeshes && this.subMeshes.length > 0) {
  21096. var totalIndices = this.getIndices().length;
  21097. var needToRecreate = false;
  21098. if (force) {
  21099. needToRecreate = true;
  21100. }
  21101. else {
  21102. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21103. var submesh = _a[_i];
  21104. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21105. needToRecreate = true;
  21106. break;
  21107. }
  21108. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21109. needToRecreate = true;
  21110. break;
  21111. }
  21112. }
  21113. }
  21114. if (!needToRecreate) {
  21115. return;
  21116. }
  21117. }
  21118. this.releaseSubMeshes();
  21119. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21120. };
  21121. Mesh.prototype.subdivide = function (count) {
  21122. if (count < 1) {
  21123. return;
  21124. }
  21125. var totalIndices = this.getTotalIndices();
  21126. var subdivisionSize = (totalIndices / count) | 0;
  21127. var offset = 0;
  21128. // Ensure that subdivisionSize is a multiple of 3
  21129. while (subdivisionSize % 3 !== 0) {
  21130. subdivisionSize++;
  21131. }
  21132. this.releaseSubMeshes();
  21133. for (var index = 0; index < count; index++) {
  21134. if (offset >= totalIndices) {
  21135. break;
  21136. }
  21137. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21138. offset += subdivisionSize;
  21139. }
  21140. this.synchronizeInstances();
  21141. };
  21142. /**
  21143. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21144. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21145. * The `data` are either a numeric array either a Float32Array.
  21146. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21147. * 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).
  21148. * Note that a new underlying VertexBuffer object is created each call.
  21149. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21150. *
  21151. * Possible `kind` values :
  21152. * - BABYLON.VertexBuffer.PositionKind
  21153. * - BABYLON.VertexBuffer.UVKind
  21154. * - BABYLON.VertexBuffer.UV2Kind
  21155. * - BABYLON.VertexBuffer.UV3Kind
  21156. * - BABYLON.VertexBuffer.UV4Kind
  21157. * - BABYLON.VertexBuffer.UV5Kind
  21158. * - BABYLON.VertexBuffer.UV6Kind
  21159. * - BABYLON.VertexBuffer.ColorKind
  21160. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21161. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21162. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21163. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21164. *
  21165. * Returns the Mesh.
  21166. */
  21167. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21168. if (!this._geometry) {
  21169. var vertexData = new BABYLON.VertexData();
  21170. vertexData.set(data, kind);
  21171. var scene = this.getScene();
  21172. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21173. }
  21174. else {
  21175. this._geometry.setVerticesData(kind, data, updatable, stride);
  21176. }
  21177. return this;
  21178. };
  21179. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21180. if (updatable === void 0) { updatable = true; }
  21181. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21182. return;
  21183. }
  21184. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21185. };
  21186. /**
  21187. * Sets the mesh VertexBuffer.
  21188. * Returns the Mesh.
  21189. */
  21190. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21191. if (!this._geometry) {
  21192. var scene = this.getScene();
  21193. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21194. }
  21195. this._geometry.setVerticesBuffer(buffer);
  21196. return this;
  21197. };
  21198. /**
  21199. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21200. * If the mesh has no geometry, it is simply returned as it is.
  21201. * The `data` are either a numeric array either a Float32Array.
  21202. * No new underlying VertexBuffer object is created.
  21203. * 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.
  21204. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21205. *
  21206. * Possible `kind` values :
  21207. * - BABYLON.VertexBuffer.PositionKind
  21208. * - BABYLON.VertexBuffer.UVKind
  21209. * - BABYLON.VertexBuffer.UV2Kind
  21210. * - BABYLON.VertexBuffer.UV3Kind
  21211. * - BABYLON.VertexBuffer.UV4Kind
  21212. * - BABYLON.VertexBuffer.UV5Kind
  21213. * - BABYLON.VertexBuffer.UV6Kind
  21214. * - BABYLON.VertexBuffer.ColorKind
  21215. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21216. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21217. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21218. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21219. *
  21220. * Returns the Mesh.
  21221. */
  21222. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21223. if (!this._geometry) {
  21224. return;
  21225. }
  21226. if (!makeItUnique) {
  21227. this._geometry.updateVerticesData(kind, data, updateExtends);
  21228. }
  21229. else {
  21230. this.makeGeometryUnique();
  21231. this.updateVerticesData(kind, data, updateExtends, false);
  21232. }
  21233. return this;
  21234. };
  21235. /**
  21236. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21237. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21238. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21239. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21240. * Returns the Mesh.
  21241. */
  21242. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21243. if (computeNormals === void 0) { computeNormals = true; }
  21244. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21245. positionFunction(positions);
  21246. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21247. if (computeNormals) {
  21248. var indices = this.getIndices();
  21249. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21250. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21251. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21252. }
  21253. return this;
  21254. };
  21255. /**
  21256. * Creates a un-shared specific occurence of the geometry for the mesh.
  21257. * Returns the Mesh.
  21258. */
  21259. Mesh.prototype.makeGeometryUnique = function () {
  21260. if (!this._geometry) {
  21261. return;
  21262. }
  21263. var oldGeometry = this._geometry;
  21264. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21265. oldGeometry.releaseForMesh(this, true);
  21266. geometry.applyToMesh(this);
  21267. return this;
  21268. };
  21269. /**
  21270. * Sets the mesh indices.
  21271. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21272. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21273. * This method creates a new index buffer each call.
  21274. * Returns the Mesh.
  21275. */
  21276. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21277. if (!this._geometry) {
  21278. var vertexData = new BABYLON.VertexData();
  21279. vertexData.indices = indices;
  21280. var scene = this.getScene();
  21281. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21282. }
  21283. else {
  21284. this._geometry.setIndices(indices, totalVertices);
  21285. }
  21286. return this;
  21287. };
  21288. /**
  21289. * Invert the geometry to move from a right handed system to a left handed one.
  21290. * Returns the Mesh.
  21291. */
  21292. Mesh.prototype.toLeftHanded = function () {
  21293. if (!this._geometry) {
  21294. return;
  21295. }
  21296. this._geometry.toLeftHanded();
  21297. return this;
  21298. };
  21299. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21300. var engine = this.getScene().getEngine();
  21301. // Wireframe
  21302. var indexToBind;
  21303. if (this._unIndexed) {
  21304. indexToBind = null;
  21305. }
  21306. else {
  21307. switch (fillMode) {
  21308. case BABYLON.Material.PointFillMode:
  21309. indexToBind = null;
  21310. break;
  21311. case BABYLON.Material.WireFrameFillMode:
  21312. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21313. break;
  21314. default:
  21315. case BABYLON.Material.TriangleFillMode:
  21316. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21317. break;
  21318. }
  21319. }
  21320. // VBOs
  21321. this._geometry._bind(effect, indexToBind);
  21322. return this;
  21323. };
  21324. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21325. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21326. return this;
  21327. }
  21328. this.onBeforeDrawObservable.notifyObservers(this);
  21329. var engine = this.getScene().getEngine();
  21330. // Draw order
  21331. switch (fillMode) {
  21332. case BABYLON.Material.PointFillMode:
  21333. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21334. break;
  21335. case BABYLON.Material.WireFrameFillMode:
  21336. if (this._unIndexed) {
  21337. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21338. }
  21339. else {
  21340. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21341. }
  21342. break;
  21343. default:
  21344. if (this._unIndexed) {
  21345. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21346. }
  21347. else {
  21348. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21349. }
  21350. }
  21351. return this;
  21352. };
  21353. /**
  21354. * Registers for this mesh a javascript function called just before the rendering process.
  21355. * This function is passed the current mesh.
  21356. * Return the Mesh.
  21357. */
  21358. Mesh.prototype.registerBeforeRender = function (func) {
  21359. this.onBeforeRenderObservable.add(func);
  21360. return this;
  21361. };
  21362. /**
  21363. * Disposes a previously registered javascript function called before the rendering.
  21364. * This function is passed the current mesh.
  21365. * Returns the Mesh.
  21366. */
  21367. Mesh.prototype.unregisterBeforeRender = function (func) {
  21368. this.onBeforeRenderObservable.removeCallback(func);
  21369. return this;
  21370. };
  21371. /**
  21372. * Registers for this mesh a javascript function called just after the rendering is complete.
  21373. * This function is passed the current mesh.
  21374. * Returns the Mesh.
  21375. */
  21376. Mesh.prototype.registerAfterRender = function (func) {
  21377. this.onAfterRenderObservable.add(func);
  21378. return this;
  21379. };
  21380. /**
  21381. * Disposes a previously registered javascript function called after the rendering.
  21382. * This function is passed the current mesh.
  21383. * Return the Mesh.
  21384. */
  21385. Mesh.prototype.unregisterAfterRender = function (func) {
  21386. this.onAfterRenderObservable.removeCallback(func);
  21387. return this;
  21388. };
  21389. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21390. var scene = this.getScene();
  21391. this._batchCache.mustReturn = false;
  21392. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21393. this._batchCache.visibleInstances[subMeshId] = null;
  21394. if (this._visibleInstances) {
  21395. var currentRenderId = scene.getRenderId();
  21396. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21397. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21398. var selfRenderId = this._renderId;
  21399. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21400. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21401. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21402. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21403. }
  21404. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21405. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21406. this._batchCache.mustReturn = true;
  21407. return this._batchCache;
  21408. }
  21409. if (currentRenderId !== selfRenderId) {
  21410. this._batchCache.renderSelf[subMeshId] = false;
  21411. }
  21412. }
  21413. this._renderIdForInstances[subMeshId] = currentRenderId;
  21414. }
  21415. return this._batchCache;
  21416. };
  21417. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21418. var visibleInstances = batch.visibleInstances[subMesh._id];
  21419. var matricesCount = visibleInstances.length + 1;
  21420. var bufferSize = matricesCount * 16 * 4;
  21421. var currentInstancesBufferSize = this._instancesBufferSize;
  21422. var instancesBuffer = this._instancesBuffer;
  21423. while (this._instancesBufferSize < bufferSize) {
  21424. this._instancesBufferSize *= 2;
  21425. }
  21426. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21427. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21428. }
  21429. var offset = 0;
  21430. var instancesCount = 0;
  21431. var world = this.getWorldMatrix();
  21432. if (batch.renderSelf[subMesh._id]) {
  21433. world.copyToArray(this._instancesData, offset);
  21434. offset += 16;
  21435. instancesCount++;
  21436. }
  21437. if (visibleInstances) {
  21438. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21439. var instance = visibleInstances[instanceIndex];
  21440. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21441. offset += 16;
  21442. instancesCount++;
  21443. }
  21444. }
  21445. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21446. if (instancesBuffer) {
  21447. instancesBuffer.dispose();
  21448. }
  21449. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21450. this._instancesBuffer = instancesBuffer;
  21451. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21452. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21453. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21454. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21455. }
  21456. else {
  21457. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21458. }
  21459. this._bind(subMesh, effect, fillMode);
  21460. this._draw(subMesh, fillMode, instancesCount);
  21461. engine.unbindInstanceAttributes();
  21462. return this;
  21463. };
  21464. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21465. var scene = this.getScene();
  21466. var engine = scene.getEngine();
  21467. if (hardwareInstancedRendering) {
  21468. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21469. }
  21470. else {
  21471. if (batch.renderSelf[subMesh._id]) {
  21472. // Draw
  21473. if (onBeforeDraw) {
  21474. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21475. }
  21476. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21477. }
  21478. if (batch.visibleInstances[subMesh._id]) {
  21479. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21480. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21481. // World
  21482. var world = instance.getWorldMatrix();
  21483. if (onBeforeDraw) {
  21484. onBeforeDraw(true, world, effectiveMaterial);
  21485. }
  21486. // Draw
  21487. this._draw(subMesh, fillMode);
  21488. }
  21489. }
  21490. }
  21491. return this;
  21492. };
  21493. /**
  21494. * Triggers the draw call for the mesh.
  21495. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21496. * Returns the Mesh.
  21497. */
  21498. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21499. this.checkOcclusionQuery();
  21500. if (this._isOccluded) {
  21501. return;
  21502. }
  21503. var scene = this.getScene();
  21504. // Managing instances
  21505. var batch = this._getInstancesRenderList(subMesh._id);
  21506. if (batch.mustReturn) {
  21507. return this;
  21508. }
  21509. // Checking geometry state
  21510. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21511. return this;
  21512. }
  21513. var callbackIndex;
  21514. this.onBeforeRenderObservable.notifyObservers(this);
  21515. var engine = scene.getEngine();
  21516. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21517. // Material
  21518. var effectiveMaterial = subMesh.getMaterial();
  21519. if (!effectiveMaterial) {
  21520. return this;
  21521. }
  21522. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21523. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21524. return this;
  21525. }
  21526. }
  21527. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21528. return this;
  21529. }
  21530. // Alpha mode
  21531. if (enableAlphaMode) {
  21532. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21533. }
  21534. // Outline - step 1
  21535. var savedDepthWrite = engine.getDepthWrite();
  21536. if (this.renderOutline) {
  21537. engine.setDepthWrite(false);
  21538. scene.getOutlineRenderer().render(subMesh, batch);
  21539. engine.setDepthWrite(savedDepthWrite);
  21540. }
  21541. var effect;
  21542. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21543. effect = subMesh.effect;
  21544. }
  21545. else {
  21546. effect = effectiveMaterial.getEffect();
  21547. }
  21548. effectiveMaterial._preBind(effect);
  21549. // Bind
  21550. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21551. if (!hardwareInstancedRendering) {
  21552. this._bind(subMesh, effect, fillMode);
  21553. }
  21554. var world = this.getWorldMatrix();
  21555. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21556. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21557. }
  21558. else {
  21559. effectiveMaterial.bind(world, this);
  21560. }
  21561. // Draw
  21562. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21563. // Unbind
  21564. effectiveMaterial.unbind();
  21565. // Outline - step 2
  21566. if (this.renderOutline && savedDepthWrite) {
  21567. engine.setDepthWrite(true);
  21568. engine.setColorWrite(false);
  21569. scene.getOutlineRenderer().render(subMesh, batch);
  21570. engine.setColorWrite(true);
  21571. }
  21572. // Overlay
  21573. if (this.renderOverlay) {
  21574. var currentMode = engine.getAlphaMode();
  21575. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21576. scene.getOutlineRenderer().render(subMesh, batch, true);
  21577. engine.setAlphaMode(currentMode);
  21578. }
  21579. this.onAfterRenderObservable.notifyObservers(this);
  21580. return this;
  21581. };
  21582. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21583. if (isInstance) {
  21584. effectiveMaterial.bindOnlyWorldMatrix(world);
  21585. }
  21586. return this;
  21587. };
  21588. /**
  21589. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21590. */
  21591. Mesh.prototype.getEmittedParticleSystems = function () {
  21592. var results = new Array();
  21593. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21594. var particleSystem = this.getScene().particleSystems[index];
  21595. if (particleSystem.emitter === this) {
  21596. results.push(particleSystem);
  21597. }
  21598. }
  21599. return results;
  21600. };
  21601. /**
  21602. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21603. */
  21604. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21605. var results = new Array();
  21606. var descendants = this.getDescendants();
  21607. descendants.push(this);
  21608. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21609. var particleSystem = this.getScene().particleSystems[index];
  21610. var emitter = particleSystem.emitter;
  21611. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21612. results.push(particleSystem);
  21613. }
  21614. }
  21615. return results;
  21616. };
  21617. Mesh.prototype._checkDelayState = function () {
  21618. var scene = this.getScene();
  21619. if (this._geometry) {
  21620. this._geometry.load(scene);
  21621. }
  21622. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21623. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21624. this._queueLoad(this, scene);
  21625. }
  21626. return this;
  21627. };
  21628. Mesh.prototype._queueLoad = function (mesh, scene) {
  21629. var _this = this;
  21630. scene._addPendingData(mesh);
  21631. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21632. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21633. if (data instanceof ArrayBuffer) {
  21634. _this._delayLoadingFunction(data, _this);
  21635. }
  21636. else {
  21637. _this._delayLoadingFunction(JSON.parse(data), _this);
  21638. }
  21639. _this.instances.forEach(function (instance) {
  21640. instance._syncSubMeshes();
  21641. });
  21642. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21643. scene._removePendingData(_this);
  21644. }, function () { }, scene.database, getBinaryData);
  21645. return this;
  21646. };
  21647. /**
  21648. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21649. */
  21650. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21651. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21652. return false;
  21653. }
  21654. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21655. return false;
  21656. }
  21657. this._checkDelayState();
  21658. return true;
  21659. };
  21660. /**
  21661. * Sets the mesh material by the material or multiMaterial `id` property.
  21662. * The material `id` is a string identifying the material or the multiMaterial.
  21663. * This method returns the Mesh.
  21664. */
  21665. Mesh.prototype.setMaterialByID = function (id) {
  21666. var materials = this.getScene().materials;
  21667. var index;
  21668. for (index = materials.length - 1; index > -1; index--) {
  21669. if (materials[index].id === id) {
  21670. this.material = materials[index];
  21671. return this;
  21672. }
  21673. }
  21674. // Multi
  21675. var multiMaterials = this.getScene().multiMaterials;
  21676. for (index = multiMaterials.length - 1; index > -1; index--) {
  21677. if (multiMaterials[index].id === id) {
  21678. this.material = multiMaterials[index];
  21679. return this;
  21680. }
  21681. }
  21682. return this;
  21683. };
  21684. /**
  21685. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21686. */
  21687. Mesh.prototype.getAnimatables = function () {
  21688. var results = [];
  21689. if (this.material) {
  21690. results.push(this.material);
  21691. }
  21692. if (this.skeleton) {
  21693. results.push(this.skeleton);
  21694. }
  21695. return results;
  21696. };
  21697. /**
  21698. * Modifies the mesh geometry according to the passed transformation matrix.
  21699. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21700. * The mesh normals are modified accordingly the same transformation.
  21701. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21702. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21703. * Returns the Mesh.
  21704. */
  21705. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21706. // Position
  21707. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21708. return this;
  21709. }
  21710. var submeshes = this.subMeshes.splice(0);
  21711. this._resetPointsArrayCache();
  21712. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21713. var temp = [];
  21714. var index;
  21715. for (index = 0; index < data.length; index += 3) {
  21716. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21717. }
  21718. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21719. // Normals
  21720. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21721. return this;
  21722. }
  21723. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21724. temp = [];
  21725. for (index = 0; index < data.length; index += 3) {
  21726. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21727. }
  21728. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21729. // flip faces?
  21730. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21731. this.flipFaces();
  21732. }
  21733. // Restore submeshes
  21734. this.releaseSubMeshes();
  21735. this.subMeshes = submeshes;
  21736. return this;
  21737. };
  21738. /**
  21739. * Modifies the mesh geometry according to its own current World Matrix.
  21740. * The mesh World Matrix is then reset.
  21741. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21742. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21743. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21744. * Returns the Mesh.
  21745. */
  21746. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21747. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21748. this.scaling.copyFromFloats(1, 1, 1);
  21749. this.position.copyFromFloats(0, 0, 0);
  21750. this.rotation.copyFromFloats(0, 0, 0);
  21751. //only if quaternion is already set
  21752. if (this.rotationQuaternion) {
  21753. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21754. }
  21755. this._worldMatrix = BABYLON.Matrix.Identity();
  21756. return this;
  21757. };
  21758. Object.defineProperty(Mesh.prototype, "_positions", {
  21759. // Cache
  21760. get: function () {
  21761. if (this._geometry) {
  21762. return this._geometry._positions;
  21763. }
  21764. return null;
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. Mesh.prototype._resetPointsArrayCache = function () {
  21770. if (this._geometry) {
  21771. this._geometry._resetPointsArrayCache();
  21772. }
  21773. return this;
  21774. };
  21775. Mesh.prototype._generatePointsArray = function () {
  21776. if (this._geometry) {
  21777. return this._geometry._generatePointsArray();
  21778. }
  21779. return false;
  21780. };
  21781. /**
  21782. * Returns a new Mesh object generated from the current mesh properties.
  21783. * This method must not get confused with createInstance().
  21784. * The parameter `name` is a string, the name given to the new mesh.
  21785. * The optional parameter `newParent` can be any Node object (default `null`).
  21786. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21787. * 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.
  21788. */
  21789. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21790. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21791. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21792. };
  21793. /**
  21794. * Disposes the mesh.
  21795. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21796. */
  21797. Mesh.prototype.dispose = function (doNotRecurse) {
  21798. var _this = this;
  21799. this.morphTargetManager = undefined;
  21800. if (this._geometry) {
  21801. this._geometry.releaseForMesh(this, true);
  21802. }
  21803. // Sources
  21804. var meshes = this.getScene().meshes;
  21805. meshes.forEach(function (mesh) {
  21806. if (mesh._source && mesh._source === _this) {
  21807. mesh._source = null;
  21808. }
  21809. });
  21810. this._source = null;
  21811. // Instances
  21812. if (this._instancesBuffer) {
  21813. this._instancesBuffer.dispose();
  21814. this._instancesBuffer = null;
  21815. }
  21816. while (this.instances.length) {
  21817. this.instances[0].dispose();
  21818. }
  21819. // Highlight layers.
  21820. var highlightLayers = this.getScene().highlightLayers;
  21821. for (var i = 0; i < highlightLayers.length; i++) {
  21822. var highlightLayer = highlightLayers[i];
  21823. if (highlightLayer) {
  21824. highlightLayer.removeMesh(this);
  21825. highlightLayer.removeExcludedMesh(this);
  21826. }
  21827. }
  21828. _super.prototype.dispose.call(this, doNotRecurse);
  21829. };
  21830. /**
  21831. * Modifies the mesh geometry according to a displacement map.
  21832. * 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.
  21833. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21834. * This method returns nothing.
  21835. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21836. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21837. * 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.
  21838. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21839. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21840. *
  21841. * Returns the Mesh.
  21842. */
  21843. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21844. var _this = this;
  21845. var scene = this.getScene();
  21846. var onload = function (img) {
  21847. // Getting height map data
  21848. var canvas = document.createElement("canvas");
  21849. var context = canvas.getContext("2d");
  21850. var heightMapWidth = img.width;
  21851. var heightMapHeight = img.height;
  21852. canvas.width = heightMapWidth;
  21853. canvas.height = heightMapHeight;
  21854. context.drawImage(img, 0, 0);
  21855. // Create VertexData from map data
  21856. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21857. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21858. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21859. //execute success callback, if set
  21860. if (onSuccess) {
  21861. onSuccess(_this);
  21862. }
  21863. };
  21864. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21865. return this;
  21866. };
  21867. /**
  21868. * Modifies the mesh geometry according to a displacementMap buffer.
  21869. * 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.
  21870. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21871. * This method returns nothing.
  21872. * 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.
  21873. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21874. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21875. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21876. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21877. *
  21878. * Returns the Mesh.
  21879. */
  21880. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21881. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21882. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21883. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21884. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21885. return this;
  21886. }
  21887. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21888. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21889. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21890. var position = BABYLON.Vector3.Zero();
  21891. var normal = BABYLON.Vector3.Zero();
  21892. var uv = BABYLON.Vector2.Zero();
  21893. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21894. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21895. for (var index = 0; index < positions.length; index += 3) {
  21896. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21897. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21898. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21899. // Compute height
  21900. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21901. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21902. var pos = (u + v * heightMapWidth) * 4;
  21903. var r = buffer[pos] / 255.0;
  21904. var g = buffer[pos + 1] / 255.0;
  21905. var b = buffer[pos + 2] / 255.0;
  21906. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21907. normal.normalize();
  21908. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21909. position = position.add(normal);
  21910. position.toArray(positions, index);
  21911. }
  21912. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21913. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21914. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21915. return this;
  21916. };
  21917. /**
  21918. * Modify the mesh to get a flat shading rendering.
  21919. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21920. * This method returns the Mesh.
  21921. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21922. */
  21923. Mesh.prototype.convertToFlatShadedMesh = function () {
  21924. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21925. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21926. var kinds = this.getVerticesDataKinds();
  21927. var vbs = [];
  21928. var data = [];
  21929. var newdata = [];
  21930. var updatableNormals = false;
  21931. var kindIndex;
  21932. var kind;
  21933. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21934. kind = kinds[kindIndex];
  21935. var vertexBuffer = this.getVertexBuffer(kind);
  21936. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21937. updatableNormals = vertexBuffer.isUpdatable();
  21938. kinds.splice(kindIndex, 1);
  21939. kindIndex--;
  21940. continue;
  21941. }
  21942. vbs[kind] = vertexBuffer;
  21943. data[kind] = vbs[kind].getData();
  21944. newdata[kind] = [];
  21945. }
  21946. // Save previous submeshes
  21947. var previousSubmeshes = this.subMeshes.slice(0);
  21948. var indices = this.getIndices();
  21949. var totalIndices = this.getTotalIndices();
  21950. // Generating unique vertices per face
  21951. var index;
  21952. for (index = 0; index < totalIndices; index++) {
  21953. var vertexIndex = indices[index];
  21954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21955. kind = kinds[kindIndex];
  21956. var stride = vbs[kind].getStrideSize();
  21957. for (var offset = 0; offset < stride; offset++) {
  21958. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21959. }
  21960. }
  21961. }
  21962. // Updating faces & normal
  21963. var normals = [];
  21964. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21965. for (index = 0; index < totalIndices; index += 3) {
  21966. indices[index] = index;
  21967. indices[index + 1] = index + 1;
  21968. indices[index + 2] = index + 2;
  21969. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21970. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21971. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21972. var p1p2 = p1.subtract(p2);
  21973. var p3p2 = p3.subtract(p2);
  21974. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21975. // Store same normals for every vertex
  21976. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21977. normals.push(normal.x);
  21978. normals.push(normal.y);
  21979. normals.push(normal.z);
  21980. }
  21981. }
  21982. this.setIndices(indices);
  21983. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21984. // Updating vertex buffers
  21985. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21986. kind = kinds[kindIndex];
  21987. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21988. }
  21989. // Updating submeshes
  21990. this.releaseSubMeshes();
  21991. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21992. var previousOne = previousSubmeshes[submeshIndex];
  21993. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21994. }
  21995. this.synchronizeInstances();
  21996. return this;
  21997. };
  21998. /**
  21999. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22000. * In other words, more vertices, no more indices and a single bigger VBO.
  22001. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22002. * Returns the Mesh.
  22003. */
  22004. Mesh.prototype.convertToUnIndexedMesh = function () {
  22005. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22006. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22007. var kinds = this.getVerticesDataKinds();
  22008. var vbs = [];
  22009. var data = [];
  22010. var newdata = [];
  22011. var updatableNormals = false;
  22012. var kindIndex;
  22013. var kind;
  22014. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22015. kind = kinds[kindIndex];
  22016. var vertexBuffer = this.getVertexBuffer(kind);
  22017. vbs[kind] = vertexBuffer;
  22018. data[kind] = vbs[kind].getData();
  22019. newdata[kind] = [];
  22020. }
  22021. // Save previous submeshes
  22022. var previousSubmeshes = this.subMeshes.slice(0);
  22023. var indices = this.getIndices();
  22024. var totalIndices = this.getTotalIndices();
  22025. // Generating unique vertices per face
  22026. var index;
  22027. for (index = 0; index < totalIndices; index++) {
  22028. var vertexIndex = indices[index];
  22029. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22030. kind = kinds[kindIndex];
  22031. var stride = vbs[kind].getStrideSize();
  22032. for (var offset = 0; offset < stride; offset++) {
  22033. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22034. }
  22035. }
  22036. }
  22037. // Updating indices
  22038. for (index = 0; index < totalIndices; index += 3) {
  22039. indices[index] = index;
  22040. indices[index + 1] = index + 1;
  22041. indices[index + 2] = index + 2;
  22042. }
  22043. this.setIndices(indices);
  22044. // Updating vertex buffers
  22045. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22046. kind = kinds[kindIndex];
  22047. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22048. }
  22049. // Updating submeshes
  22050. this.releaseSubMeshes();
  22051. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22052. var previousOne = previousSubmeshes[submeshIndex];
  22053. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22054. }
  22055. this._unIndexed = true;
  22056. this.synchronizeInstances();
  22057. return this;
  22058. };
  22059. /**
  22060. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22061. * This method returns the Mesh.
  22062. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22063. */
  22064. Mesh.prototype.flipFaces = function (flipNormals) {
  22065. if (flipNormals === void 0) { flipNormals = false; }
  22066. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22067. var i;
  22068. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22069. for (i = 0; i < vertex_data.normals.length; i++) {
  22070. vertex_data.normals[i] *= -1;
  22071. }
  22072. }
  22073. var temp;
  22074. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22075. // reassign indices
  22076. temp = vertex_data.indices[i + 1];
  22077. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22078. vertex_data.indices[i + 2] = temp;
  22079. }
  22080. vertex_data.applyToMesh(this);
  22081. return this;
  22082. };
  22083. // Instances
  22084. /**
  22085. * Creates a new InstancedMesh object from the mesh model.
  22086. * An instance shares the same properties and the same material than its model.
  22087. * Only these properties of each instance can then be set individually :
  22088. * - position
  22089. * - rotation
  22090. * - rotationQuaternion
  22091. * - setPivotMatrix
  22092. * - scaling
  22093. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22094. * Warning : this method is not supported for Line mesh and LineSystem
  22095. */
  22096. Mesh.prototype.createInstance = function (name) {
  22097. return new BABYLON.InstancedMesh(name, this);
  22098. };
  22099. /**
  22100. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22101. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22102. * This method returns the Mesh.
  22103. */
  22104. Mesh.prototype.synchronizeInstances = function () {
  22105. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22106. var instance = this.instances[instanceIndex];
  22107. instance._syncSubMeshes();
  22108. }
  22109. return this;
  22110. };
  22111. /**
  22112. * Simplify the mesh according to the given array of settings.
  22113. * Function will return immediately and will simplify async. It returns the Mesh.
  22114. * @param settings a collection of simplification settings.
  22115. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22116. * @param type the type of simplification to run.
  22117. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22118. */
  22119. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22120. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22121. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22122. this.getScene().simplificationQueue.addTask({
  22123. settings: settings,
  22124. parallelProcessing: parallelProcessing,
  22125. mesh: this,
  22126. simplificationType: simplificationType,
  22127. successCallback: successCallback
  22128. });
  22129. return this;
  22130. };
  22131. /**
  22132. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22133. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22134. * This should be used together with the simplification to avoid disappearing triangles.
  22135. * Returns the Mesh.
  22136. * @param successCallback an optional success callback to be called after the optimization finished.
  22137. */
  22138. Mesh.prototype.optimizeIndices = function (successCallback) {
  22139. var _this = this;
  22140. var indices = this.getIndices();
  22141. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22142. var vectorPositions = [];
  22143. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22144. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22145. }
  22146. var dupes = [];
  22147. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22148. var realPos = vectorPositions.length - 1 - iteration;
  22149. var testedPosition = vectorPositions[realPos];
  22150. for (var j = 0; j < realPos; ++j) {
  22151. var againstPosition = vectorPositions[j];
  22152. if (testedPosition.equals(againstPosition)) {
  22153. dupes[realPos] = j;
  22154. break;
  22155. }
  22156. }
  22157. }, function () {
  22158. for (var i = 0; i < indices.length; ++i) {
  22159. indices[i] = dupes[indices[i]] || indices[i];
  22160. }
  22161. //indices are now reordered
  22162. var originalSubMeshes = _this.subMeshes.slice(0);
  22163. _this.setIndices(indices);
  22164. _this.subMeshes = originalSubMeshes;
  22165. if (successCallback) {
  22166. successCallback(_this);
  22167. }
  22168. });
  22169. return this;
  22170. };
  22171. Mesh.prototype.serialize = function (serializationObject) {
  22172. serializationObject.name = this.name;
  22173. serializationObject.id = this.id;
  22174. serializationObject.type = this.getClassName();
  22175. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22176. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22177. }
  22178. serializationObject.position = this.position.asArray();
  22179. if (this.rotationQuaternion) {
  22180. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22181. }
  22182. else if (this.rotation) {
  22183. serializationObject.rotation = this.rotation.asArray();
  22184. }
  22185. serializationObject.scaling = this.scaling.asArray();
  22186. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22187. serializationObject.isEnabled = this.isEnabled();
  22188. serializationObject.isVisible = this.isVisible;
  22189. serializationObject.infiniteDistance = this.infiniteDistance;
  22190. serializationObject.pickable = this.isPickable;
  22191. serializationObject.receiveShadows = this.receiveShadows;
  22192. serializationObject.billboardMode = this.billboardMode;
  22193. serializationObject.visibility = this.visibility;
  22194. serializationObject.checkCollisions = this.checkCollisions;
  22195. serializationObject.isBlocker = this.isBlocker;
  22196. // Parent
  22197. if (this.parent) {
  22198. serializationObject.parentId = this.parent.id;
  22199. }
  22200. // Geometry
  22201. var geometry = this._geometry;
  22202. if (geometry) {
  22203. var geometryId = geometry.id;
  22204. serializationObject.geometryId = geometryId;
  22205. // SubMeshes
  22206. serializationObject.subMeshes = [];
  22207. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22208. var subMesh = this.subMeshes[subIndex];
  22209. serializationObject.subMeshes.push({
  22210. materialIndex: subMesh.materialIndex,
  22211. verticesStart: subMesh.verticesStart,
  22212. verticesCount: subMesh.verticesCount,
  22213. indexStart: subMesh.indexStart,
  22214. indexCount: subMesh.indexCount
  22215. });
  22216. }
  22217. }
  22218. // Material
  22219. if (this.material) {
  22220. serializationObject.materialId = this.material.id;
  22221. }
  22222. else {
  22223. this.material = null;
  22224. }
  22225. // Morph targets
  22226. if (this.morphTargetManager) {
  22227. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22228. }
  22229. // Skeleton
  22230. if (this.skeleton) {
  22231. serializationObject.skeletonId = this.skeleton.id;
  22232. }
  22233. // Physics
  22234. //TODO implement correct serialization for physics impostors.
  22235. if (this.getPhysicsImpostor()) {
  22236. var impostor = this.getPhysicsImpostor();
  22237. serializationObject.physicsMass = impostor.getParam("mass");
  22238. serializationObject.physicsFriction = impostor.getParam("friction");
  22239. serializationObject.physicsRestitution = impostor.getParam("mass");
  22240. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22241. }
  22242. // Metadata
  22243. if (this.metadata) {
  22244. serializationObject.metadata = this.metadata;
  22245. }
  22246. // Instances
  22247. serializationObject.instances = [];
  22248. for (var index = 0; index < this.instances.length; index++) {
  22249. var instance = this.instances[index];
  22250. var serializationInstance = {
  22251. name: instance.name,
  22252. position: instance.position.asArray(),
  22253. scaling: instance.scaling.asArray()
  22254. };
  22255. if (instance.rotationQuaternion) {
  22256. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22257. }
  22258. else if (instance.rotation) {
  22259. serializationInstance.rotation = instance.rotation.asArray();
  22260. }
  22261. serializationObject.instances.push(serializationInstance);
  22262. // Animations
  22263. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22264. serializationInstance.ranges = instance.serializeAnimationRanges();
  22265. }
  22266. //
  22267. // Animations
  22268. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22269. serializationObject.ranges = this.serializeAnimationRanges();
  22270. // Layer mask
  22271. serializationObject.layerMask = this.layerMask;
  22272. // Alpha
  22273. serializationObject.alphaIndex = this.alphaIndex;
  22274. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22275. // Overlay
  22276. serializationObject.overlayAlpha = this.overlayAlpha;
  22277. serializationObject.overlayColor = this.overlayColor.asArray();
  22278. serializationObject.renderOverlay = this.renderOverlay;
  22279. // Fog
  22280. serializationObject.applyFog = this.applyFog;
  22281. // Action Manager
  22282. if (this.actionManager) {
  22283. serializationObject.actions = this.actionManager.serialize(this.name);
  22284. }
  22285. };
  22286. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22287. if (!this.geometry) {
  22288. return;
  22289. }
  22290. this._markSubMeshesAsAttributesDirty();
  22291. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22292. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22293. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22294. this.morphTargetManager = undefined;
  22295. return;
  22296. }
  22297. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22298. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22299. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22300. if (morphTarget.hasNormals) {
  22301. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22302. }
  22303. if (morphTarget.hasTangents) {
  22304. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22305. }
  22306. }
  22307. }
  22308. else {
  22309. var index = 0;
  22310. // Positions
  22311. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22312. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22313. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22314. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22315. }
  22316. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22317. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22318. }
  22319. index++;
  22320. }
  22321. }
  22322. };
  22323. // Statics
  22324. /**
  22325. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22326. * The parameter `parsedMesh` is the mesh to be copied.
  22327. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22328. */
  22329. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22330. var mesh;
  22331. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22332. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22333. }
  22334. else {
  22335. mesh = new Mesh(parsedMesh.name, scene);
  22336. }
  22337. mesh.id = parsedMesh.id;
  22338. if (BABYLON.Tags) {
  22339. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22340. }
  22341. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22342. if (parsedMesh.metadata !== undefined) {
  22343. mesh.metadata = parsedMesh.metadata;
  22344. }
  22345. if (parsedMesh.rotationQuaternion) {
  22346. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22347. }
  22348. else if (parsedMesh.rotation) {
  22349. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22350. }
  22351. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22352. if (parsedMesh.localMatrix) {
  22353. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22354. }
  22355. else if (parsedMesh.pivotMatrix) {
  22356. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22357. }
  22358. mesh.setEnabled(parsedMesh.isEnabled);
  22359. mesh.isVisible = parsedMesh.isVisible;
  22360. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22361. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22362. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22363. if (parsedMesh.applyFog !== undefined) {
  22364. mesh.applyFog = parsedMesh.applyFog;
  22365. }
  22366. if (parsedMesh.pickable !== undefined) {
  22367. mesh.isPickable = parsedMesh.pickable;
  22368. }
  22369. if (parsedMesh.alphaIndex !== undefined) {
  22370. mesh.alphaIndex = parsedMesh.alphaIndex;
  22371. }
  22372. mesh.receiveShadows = parsedMesh.receiveShadows;
  22373. mesh.billboardMode = parsedMesh.billboardMode;
  22374. if (parsedMesh.visibility !== undefined) {
  22375. mesh.visibility = parsedMesh.visibility;
  22376. }
  22377. mesh.checkCollisions = parsedMesh.checkCollisions;
  22378. if (parsedMesh.isBlocker !== undefined) {
  22379. mesh.isBlocker = parsedMesh.isBlocker;
  22380. }
  22381. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22382. // freezeWorldMatrix
  22383. if (parsedMesh.freezeWorldMatrix) {
  22384. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22385. }
  22386. // Parent
  22387. if (parsedMesh.parentId) {
  22388. mesh._waitingParentId = parsedMesh.parentId;
  22389. }
  22390. // Actions
  22391. if (parsedMesh.actions !== undefined) {
  22392. mesh._waitingActions = parsedMesh.actions;
  22393. }
  22394. // Overlay
  22395. if (parsedMesh.overlayAlpha !== undefined) {
  22396. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22397. }
  22398. if (parsedMesh.overlayColor !== undefined) {
  22399. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22400. }
  22401. if (parsedMesh.renderOverlay !== undefined) {
  22402. mesh.renderOverlay = parsedMesh.renderOverlay;
  22403. }
  22404. // Geometry
  22405. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22406. if (parsedMesh.delayLoadingFile) {
  22407. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22408. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22409. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22410. if (parsedMesh._binaryInfo) {
  22411. mesh._binaryInfo = parsedMesh._binaryInfo;
  22412. }
  22413. mesh._delayInfo = [];
  22414. if (parsedMesh.hasUVs) {
  22415. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22416. }
  22417. if (parsedMesh.hasUVs2) {
  22418. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22419. }
  22420. if (parsedMesh.hasUVs3) {
  22421. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22422. }
  22423. if (parsedMesh.hasUVs4) {
  22424. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22425. }
  22426. if (parsedMesh.hasUVs5) {
  22427. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22428. }
  22429. if (parsedMesh.hasUVs6) {
  22430. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22431. }
  22432. if (parsedMesh.hasColors) {
  22433. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22434. }
  22435. if (parsedMesh.hasMatricesIndices) {
  22436. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22437. }
  22438. if (parsedMesh.hasMatricesWeights) {
  22439. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22440. }
  22441. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22442. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22443. mesh._checkDelayState();
  22444. }
  22445. }
  22446. else {
  22447. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22448. }
  22449. // Material
  22450. if (parsedMesh.materialId) {
  22451. mesh.setMaterialByID(parsedMesh.materialId);
  22452. }
  22453. else {
  22454. mesh.material = null;
  22455. }
  22456. // Morph targets
  22457. if (parsedMesh.morphTargetManagerId > -1) {
  22458. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22459. }
  22460. // Skeleton
  22461. if (parsedMesh.skeletonId > -1) {
  22462. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22463. if (parsedMesh.numBoneInfluencers) {
  22464. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22465. }
  22466. }
  22467. // Animations
  22468. if (parsedMesh.animations) {
  22469. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22470. var parsedAnimation = parsedMesh.animations[animationIndex];
  22471. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22472. }
  22473. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22474. }
  22475. if (parsedMesh.autoAnimate) {
  22476. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22477. }
  22478. // Layer Mask
  22479. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22480. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22481. }
  22482. else {
  22483. mesh.layerMask = 0x0FFFFFFF;
  22484. }
  22485. // Physics
  22486. if (parsedMesh.physicsImpostor) {
  22487. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22488. mass: parsedMesh.physicsMass,
  22489. friction: parsedMesh.physicsFriction,
  22490. restitution: parsedMesh.physicsRestitution
  22491. }, scene);
  22492. }
  22493. // Instances
  22494. if (parsedMesh.instances) {
  22495. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22496. var parsedInstance = parsedMesh.instances[index];
  22497. var instance = mesh.createInstance(parsedInstance.name);
  22498. if (BABYLON.Tags) {
  22499. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22500. }
  22501. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22502. if (parsedInstance.parentId) {
  22503. instance._waitingParentId = parsedInstance.parentId;
  22504. }
  22505. if (parsedInstance.rotationQuaternion) {
  22506. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22507. }
  22508. else if (parsedInstance.rotation) {
  22509. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22510. }
  22511. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22512. instance.checkCollisions = mesh.checkCollisions;
  22513. if (parsedMesh.animations) {
  22514. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22515. parsedAnimation = parsedMesh.animations[animationIndex];
  22516. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22517. }
  22518. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22519. }
  22520. }
  22521. }
  22522. return mesh;
  22523. };
  22524. /**
  22525. * Creates a ribbon mesh.
  22526. * Please consider using the same method from the MeshBuilder class instead.
  22527. * 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.
  22528. *
  22529. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22530. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22531. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22532. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22533. * 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.
  22534. * 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.
  22535. * 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
  22536. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22537. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22538. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22539. */
  22540. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22541. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22542. pathArray: pathArray,
  22543. closeArray: closeArray,
  22544. closePath: closePath,
  22545. offset: offset,
  22546. updatable: updatable,
  22547. sideOrientation: sideOrientation,
  22548. instance: instance
  22549. }, scene);
  22550. };
  22551. /**
  22552. * Creates a plane polygonal mesh. By default, this is a disc.
  22553. * Please consider using the same method from the MeshBuilder class instead.
  22554. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22555. * 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.
  22556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22557. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22559. */
  22560. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22561. var options = {
  22562. radius: radius,
  22563. tessellation: tessellation,
  22564. sideOrientation: sideOrientation,
  22565. updatable: updatable
  22566. };
  22567. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22568. };
  22569. /**
  22570. * Creates a box mesh.
  22571. * Please consider using the same method from the MeshBuilder class instead.
  22572. * The parameter `size` sets the size (float) of each box side (default 1).
  22573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22576. */
  22577. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22578. var options = {
  22579. size: size,
  22580. sideOrientation: sideOrientation,
  22581. updatable: updatable
  22582. };
  22583. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22584. };
  22585. /**
  22586. * Creates a sphere mesh.
  22587. * Please consider using the same method from the MeshBuilder class instead.
  22588. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22589. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22593. */
  22594. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22595. var options = {
  22596. segments: segments,
  22597. diameterX: diameter,
  22598. diameterY: diameter,
  22599. diameterZ: diameter,
  22600. sideOrientation: sideOrientation,
  22601. updatable: updatable
  22602. };
  22603. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22604. };
  22605. /**
  22606. * Creates a cylinder or a cone mesh.
  22607. * Please consider using the same method from the MeshBuilder class instead.
  22608. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22609. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22610. * 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.
  22611. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22612. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  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.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22618. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22619. if (scene !== undefined) {
  22620. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22621. updatable = scene;
  22622. }
  22623. scene = subdivisions;
  22624. subdivisions = 1;
  22625. }
  22626. var options = {
  22627. height: height,
  22628. diameterTop: diameterTop,
  22629. diameterBottom: diameterBottom,
  22630. tessellation: tessellation,
  22631. subdivisions: subdivisions,
  22632. sideOrientation: sideOrientation,
  22633. updatable: updatable
  22634. };
  22635. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22636. };
  22637. // Torus (Code from SharpDX.org)
  22638. /**
  22639. * Creates a torus mesh.
  22640. * Please consider using the same method from the MeshBuilder class instead.
  22641. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22642. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22643. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22647. */
  22648. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22649. var options = {
  22650. diameter: diameter,
  22651. thickness: thickness,
  22652. tessellation: tessellation,
  22653. sideOrientation: sideOrientation,
  22654. updatable: updatable
  22655. };
  22656. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22657. };
  22658. /**
  22659. * Creates a torus knot mesh.
  22660. * Please consider using the same method from the MeshBuilder class instead.
  22661. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22662. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22663. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22664. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22668. */
  22669. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22670. var options = {
  22671. radius: radius,
  22672. tube: tube,
  22673. radialSegments: radialSegments,
  22674. tubularSegments: tubularSegments,
  22675. p: p,
  22676. q: q,
  22677. sideOrientation: sideOrientation,
  22678. updatable: updatable
  22679. };
  22680. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22681. };
  22682. /**
  22683. * Creates a line mesh.
  22684. * Please consider using the same method from the MeshBuilder class instead.
  22685. * 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.
  22686. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22687. * The parameter `points` is an array successive Vector3.
  22688. * 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
  22689. * When updating an instance, remember that only point positions can change, not the number of points.
  22690. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22691. */
  22692. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22693. var options = {
  22694. points: points,
  22695. updatable: updatable,
  22696. instance: instance
  22697. };
  22698. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22699. };
  22700. /**
  22701. * Creates a dashed line mesh.
  22702. * Please consider using the same method from the MeshBuilder class instead.
  22703. * 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.
  22704. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22705. * The parameter `points` is an array successive Vector3.
  22706. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22707. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22708. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22709. * 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
  22710. * When updating an instance, remember that only point positions can change, not the number of points.
  22711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22712. */
  22713. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22714. var options = {
  22715. points: points,
  22716. dashSize: dashSize,
  22717. gapSize: gapSize,
  22718. dashNb: dashNb,
  22719. updatable: updatable,
  22720. instance: instance
  22721. };
  22722. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22723. };
  22724. /**
  22725. * Creates a polygon mesh.
  22726. * Please consider using the same method from the MeshBuilder class instead.
  22727. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  22728. * 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.
  22729. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22731. * Remember you can only change the shape positions, not their number when updating a polygon.
  22732. */
  22733. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  22734. var options = {
  22735. shape: shape,
  22736. holes: holes,
  22737. updatable: updatable,
  22738. sideOrientation: sideOrientation
  22739. };
  22740. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  22741. };
  22742. /**
  22743. * Creates an extruded polygon mesh, with depth in the Y direction.
  22744. * Please consider using the same method from the MeshBuilder class instead.
  22745. */
  22746. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  22747. var options = {
  22748. shape: shape,
  22749. holes: holes,
  22750. depth: depth,
  22751. updatable: updatable,
  22752. sideOrientation: sideOrientation
  22753. };
  22754. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  22755. };
  22756. /**
  22757. * Creates an extruded shape mesh.
  22758. * 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.
  22759. * Please consider using the same method from the MeshBuilder class instead.
  22760. *
  22761. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22762. * 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
  22763. * extruded along the Z axis.
  22764. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22765. * 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.
  22766. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22767. * 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
  22768. * 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
  22769. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22770. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22771. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22772. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22773. */
  22774. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22775. var options = {
  22776. shape: shape,
  22777. path: path,
  22778. scale: scale,
  22779. rotation: rotation,
  22780. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22781. sideOrientation: sideOrientation,
  22782. instance: instance,
  22783. updatable: updatable
  22784. };
  22785. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22786. };
  22787. /**
  22788. * Creates an custom extruded shape mesh.
  22789. * 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.
  22790. * Please consider using the same method from the MeshBuilder class instead.
  22791. *
  22792. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22793. * 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
  22794. * extruded along the Z axis.
  22795. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22796. * 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
  22797. * and the distance of this point from the begining of the path :
  22798. * ```javascript
  22799. * var rotationFunction = function(i, distance) {
  22800. * // do things
  22801. * return rotationValue; }
  22802. * ```
  22803. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22804. * 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
  22805. * and the distance of this point from the begining of the path :
  22806. * ```javascript
  22807. * var scaleFunction = function(i, distance) {
  22808. * // do things
  22809. * return scaleValue;}
  22810. * ```
  22811. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22812. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22813. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22814. * 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
  22815. * 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
  22816. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22820. */
  22821. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22822. var options = {
  22823. shape: shape,
  22824. path: path,
  22825. scaleFunction: scaleFunction,
  22826. rotationFunction: rotationFunction,
  22827. ribbonCloseArray: ribbonCloseArray,
  22828. ribbonClosePath: ribbonClosePath,
  22829. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22830. sideOrientation: sideOrientation,
  22831. instance: instance,
  22832. updatable: updatable
  22833. };
  22834. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22835. };
  22836. /**
  22837. * Creates lathe mesh.
  22838. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22839. * Please consider using the same method from the MeshBuilder class instead.
  22840. * 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
  22841. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22842. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22843. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22845. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22847. */
  22848. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22849. var options = {
  22850. shape: shape,
  22851. radius: radius,
  22852. tessellation: tessellation,
  22853. sideOrientation: sideOrientation,
  22854. updatable: updatable
  22855. };
  22856. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22857. };
  22858. /**
  22859. * Creates a plane mesh.
  22860. * Please consider using the same method from the MeshBuilder class instead.
  22861. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22862. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22863. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22864. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22865. */
  22866. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22867. var options = {
  22868. size: size,
  22869. width: size,
  22870. height: size,
  22871. sideOrientation: sideOrientation,
  22872. updatable: updatable
  22873. };
  22874. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22875. };
  22876. /**
  22877. * Creates a ground mesh.
  22878. * Please consider using the same method from the MeshBuilder class instead.
  22879. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22880. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22881. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22882. */
  22883. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22884. var options = {
  22885. width: width,
  22886. height: height,
  22887. subdivisions: subdivisions,
  22888. updatable: updatable
  22889. };
  22890. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22891. };
  22892. /**
  22893. * Creates a tiled ground mesh.
  22894. * Please consider using the same method from the MeshBuilder class instead.
  22895. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22896. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22897. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22898. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22899. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22900. * numbers of subdivisions on the ground width and height of each tile.
  22901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22902. */
  22903. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22904. var options = {
  22905. xmin: xmin,
  22906. zmin: zmin,
  22907. xmax: xmax,
  22908. zmax: zmax,
  22909. subdivisions: subdivisions,
  22910. precision: precision,
  22911. updatable: updatable
  22912. };
  22913. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22914. };
  22915. /**
  22916. * Creates a ground mesh from a height map.
  22917. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22918. * Please consider using the same method from the MeshBuilder class instead.
  22919. * The parameter `url` sets the URL of the height map image resource.
  22920. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22921. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22922. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22923. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22924. * 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).
  22925. * This function is passed the newly built mesh :
  22926. * ```javascript
  22927. * function(mesh) { // do things
  22928. * return; }
  22929. * ```
  22930. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22931. */
  22932. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22933. var options = {
  22934. width: width,
  22935. height: height,
  22936. subdivisions: subdivisions,
  22937. minHeight: minHeight,
  22938. maxHeight: maxHeight,
  22939. updatable: updatable,
  22940. onReady: onReady
  22941. };
  22942. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22943. };
  22944. /**
  22945. * Creates a tube mesh.
  22946. * 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.
  22947. * Please consider using the same method from the MeshBuilder class instead.
  22948. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22949. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22950. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22951. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22952. * 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.
  22953. * It must return a radius value (positive float) :
  22954. * ```javascript
  22955. * var radiusFunction = function(i, distance) {
  22956. * // do things
  22957. * return radius; }
  22958. * ```
  22959. * 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
  22960. * 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
  22961. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22962. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22964. */
  22965. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22966. var options = {
  22967. path: path,
  22968. radius: radius,
  22969. tessellation: tessellation,
  22970. radiusFunction: radiusFunction,
  22971. arc: 1,
  22972. cap: cap,
  22973. updatable: updatable,
  22974. sideOrientation: sideOrientation,
  22975. instance: instance
  22976. };
  22977. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22978. };
  22979. /**
  22980. * Creates a polyhedron mesh.
  22981. * Please consider using the same method from the MeshBuilder class instead.
  22982. * 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
  22983. * to choose the wanted type.
  22984. * The parameter `size` (positive float, default 1) sets the polygon size.
  22985. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22986. * 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`.
  22987. * 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
  22988. * 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)`).
  22989. * 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
  22990. * 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.
  22991. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22992. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22993. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22994. */
  22995. Mesh.CreatePolyhedron = function (name, options, scene) {
  22996. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22997. };
  22998. /**
  22999. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23000. * Please consider using the same method from the MeshBuilder class instead.
  23001. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23002. * 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`).
  23003. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23004. * 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.
  23005. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23006. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23008. */
  23009. Mesh.CreateIcoSphere = function (name, options, scene) {
  23010. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23011. };
  23012. /**
  23013. * Creates a decal mesh.
  23014. * Please consider using the same method from the MeshBuilder class instead.
  23015. * 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.
  23016. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23017. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23018. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23019. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23020. */
  23021. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23022. var options = {
  23023. position: position,
  23024. normal: normal,
  23025. size: size,
  23026. angle: angle
  23027. };
  23028. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23029. };
  23030. // Skeletons
  23031. /**
  23032. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23033. */
  23034. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23035. var source;
  23036. if (!this._sourcePositions) {
  23037. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23038. this._sourcePositions = new Float32Array(source);
  23039. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23040. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23041. }
  23042. }
  23043. return this._sourcePositions;
  23044. };
  23045. /**
  23046. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23047. */
  23048. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23049. var source;
  23050. if (!this._sourceNormals) {
  23051. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23052. this._sourceNormals = new Float32Array(source);
  23053. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23054. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23055. }
  23056. }
  23057. return this._sourceNormals;
  23058. };
  23059. /**
  23060. * Updates the vertex buffer by applying transformation from the bones.
  23061. * Returns the Mesh.
  23062. *
  23063. * @param {skeleton} skeleton to apply
  23064. */
  23065. Mesh.prototype.applySkeleton = function (skeleton) {
  23066. if (!this.geometry) {
  23067. return this;
  23068. }
  23069. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23070. return this;
  23071. }
  23072. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23073. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23074. return this;
  23075. }
  23076. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23077. return this;
  23078. }
  23079. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23080. return this;
  23081. }
  23082. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23083. return this;
  23084. }
  23085. if (!this._sourcePositions) {
  23086. var submeshes = this.subMeshes.slice();
  23087. this.setPositionsForCPUSkinning();
  23088. this.subMeshes = submeshes;
  23089. }
  23090. if (!this._sourceNormals) {
  23091. this.setNormalsForCPUSkinning();
  23092. }
  23093. // positionsData checks for not being Float32Array will only pass at most once
  23094. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23095. if (!(positionsData instanceof Float32Array)) {
  23096. positionsData = new Float32Array(positionsData);
  23097. }
  23098. // normalsData checks for not being Float32Array will only pass at most once
  23099. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23100. if (!(normalsData instanceof Float32Array)) {
  23101. normalsData = new Float32Array(normalsData);
  23102. }
  23103. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23104. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23105. var needExtras = this.numBoneInfluencers > 4;
  23106. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23107. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23108. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23109. var tempVector3 = BABYLON.Vector3.Zero();
  23110. var finalMatrix = new BABYLON.Matrix();
  23111. var tempMatrix = new BABYLON.Matrix();
  23112. var matWeightIdx = 0;
  23113. var inf;
  23114. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23115. var weight;
  23116. for (inf = 0; inf < 4; inf++) {
  23117. weight = matricesWeightsData[matWeightIdx + inf];
  23118. if (weight > 0) {
  23119. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23120. finalMatrix.addToSelf(tempMatrix);
  23121. }
  23122. else
  23123. break;
  23124. }
  23125. if (needExtras) {
  23126. for (inf = 0; inf < 4; inf++) {
  23127. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23128. if (weight > 0) {
  23129. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23130. finalMatrix.addToSelf(tempMatrix);
  23131. }
  23132. else
  23133. break;
  23134. }
  23135. }
  23136. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23137. tempVector3.toArray(positionsData, index);
  23138. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23139. tempVector3.toArray(normalsData, index);
  23140. finalMatrix.reset();
  23141. }
  23142. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23143. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23144. return this;
  23145. };
  23146. // Tools
  23147. /**
  23148. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23149. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23150. */
  23151. Mesh.MinMax = function (meshes) {
  23152. var minVector = null;
  23153. var maxVector = null;
  23154. meshes.forEach(function (mesh, index, array) {
  23155. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23156. if (!minVector) {
  23157. minVector = boundingBox.minimumWorld;
  23158. maxVector = boundingBox.maximumWorld;
  23159. }
  23160. else {
  23161. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23162. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23163. }
  23164. });
  23165. return {
  23166. min: minVector,
  23167. max: maxVector
  23168. };
  23169. };
  23170. /**
  23171. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23172. */
  23173. Mesh.Center = function (meshesOrMinMaxVector) {
  23174. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23175. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23176. };
  23177. /**
  23178. * Merge the array of meshes into a single mesh for performance reasons.
  23179. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23180. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23181. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23182. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23183. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23184. */
  23185. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23186. if (disposeSource === void 0) { disposeSource = true; }
  23187. var index;
  23188. if (!allow32BitsIndices) {
  23189. var totalVertices = 0;
  23190. // Counting vertices
  23191. for (index = 0; index < meshes.length; index++) {
  23192. if (meshes[index]) {
  23193. totalVertices += meshes[index].getTotalVertices();
  23194. if (totalVertices > 65536) {
  23195. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23196. return null;
  23197. }
  23198. }
  23199. }
  23200. }
  23201. // Merge
  23202. var vertexData;
  23203. var otherVertexData;
  23204. var indiceArray = new Array();
  23205. var source;
  23206. for (index = 0; index < meshes.length; index++) {
  23207. if (meshes[index]) {
  23208. meshes[index].computeWorldMatrix(true);
  23209. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23210. otherVertexData.transform(meshes[index].getWorldMatrix());
  23211. if (vertexData) {
  23212. vertexData.merge(otherVertexData);
  23213. }
  23214. else {
  23215. vertexData = otherVertexData;
  23216. source = meshes[index];
  23217. }
  23218. if (subdivideWithSubMeshes) {
  23219. indiceArray.push(meshes[index].getTotalIndices());
  23220. }
  23221. }
  23222. }
  23223. if (!meshSubclass) {
  23224. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23225. }
  23226. vertexData.applyToMesh(meshSubclass);
  23227. // Setting properties
  23228. meshSubclass.material = source.material;
  23229. meshSubclass.checkCollisions = source.checkCollisions;
  23230. // Cleaning
  23231. if (disposeSource) {
  23232. for (index = 0; index < meshes.length; index++) {
  23233. if (meshes[index]) {
  23234. meshes[index].dispose();
  23235. }
  23236. }
  23237. }
  23238. // Subdivide
  23239. if (subdivideWithSubMeshes) {
  23240. //-- Suppresions du submesh global
  23241. meshSubclass.releaseSubMeshes();
  23242. index = 0;
  23243. var offset = 0;
  23244. //-- aplique la subdivision en fonction du tableau d'indices
  23245. while (index < indiceArray.length) {
  23246. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23247. offset += indiceArray[index];
  23248. index++;
  23249. }
  23250. }
  23251. return meshSubclass;
  23252. };
  23253. // Consts
  23254. Mesh._FRONTSIDE = 0;
  23255. Mesh._BACKSIDE = 1;
  23256. Mesh._DOUBLESIDE = 2;
  23257. Mesh._DEFAULTSIDE = 0;
  23258. Mesh._NO_CAP = 0;
  23259. Mesh._CAP_START = 1;
  23260. Mesh._CAP_END = 2;
  23261. Mesh._CAP_ALL = 3;
  23262. return Mesh;
  23263. }(BABYLON.AbstractMesh));
  23264. BABYLON.Mesh = Mesh;
  23265. })(BABYLON || (BABYLON = {}));
  23266. //# sourceMappingURL=babylon.mesh.js.map
  23267. var BABYLON;
  23268. (function (BABYLON) {
  23269. var BaseSubMesh = (function () {
  23270. function BaseSubMesh() {
  23271. }
  23272. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23273. get: function () {
  23274. return this._materialEffect;
  23275. },
  23276. enumerable: true,
  23277. configurable: true
  23278. });
  23279. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23280. if (this._materialEffect === effect) {
  23281. if (!effect) {
  23282. this._materialDefines = undefined;
  23283. }
  23284. return;
  23285. }
  23286. this._materialDefines = defines;
  23287. this._materialEffect = effect;
  23288. };
  23289. return BaseSubMesh;
  23290. }());
  23291. BABYLON.BaseSubMesh = BaseSubMesh;
  23292. var SubMesh = (function (_super) {
  23293. __extends(SubMesh, _super);
  23294. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23295. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23296. var _this = _super.call(this) || this;
  23297. _this.materialIndex = materialIndex;
  23298. _this.verticesStart = verticesStart;
  23299. _this.verticesCount = verticesCount;
  23300. _this.indexStart = indexStart;
  23301. _this.indexCount = indexCount;
  23302. _this._renderId = 0;
  23303. _this._mesh = mesh;
  23304. _this._renderingMesh = renderingMesh || mesh;
  23305. mesh.subMeshes.push(_this);
  23306. _this._trianglePlanes = [];
  23307. _this._id = mesh.subMeshes.length - 1;
  23308. if (createBoundingBox) {
  23309. _this.refreshBoundingInfo();
  23310. mesh.computeWorldMatrix(true);
  23311. }
  23312. return _this;
  23313. }
  23314. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23315. get: function () {
  23316. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23317. },
  23318. enumerable: true,
  23319. configurable: true
  23320. });
  23321. /**
  23322. * Returns the submesh BoudingInfo object.
  23323. */
  23324. SubMesh.prototype.getBoundingInfo = function () {
  23325. if (this.IsGlobal) {
  23326. return this._mesh.getBoundingInfo();
  23327. }
  23328. return this._boundingInfo;
  23329. };
  23330. /**
  23331. * Sets the submesh BoundingInfo.
  23332. * Return the SubMesh.
  23333. */
  23334. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23335. this._boundingInfo = boundingInfo;
  23336. return this;
  23337. };
  23338. /**
  23339. * Returns the mesh of the current submesh.
  23340. */
  23341. SubMesh.prototype.getMesh = function () {
  23342. return this._mesh;
  23343. };
  23344. /**
  23345. * Returns the rendering mesh of the submesh.
  23346. */
  23347. SubMesh.prototype.getRenderingMesh = function () {
  23348. return this._renderingMesh;
  23349. };
  23350. /**
  23351. * Returns the submesh material.
  23352. */
  23353. SubMesh.prototype.getMaterial = function () {
  23354. var rootMaterial = this._renderingMesh.material;
  23355. if (rootMaterial && rootMaterial.getSubMaterial) {
  23356. var multiMaterial = rootMaterial;
  23357. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23358. if (this._currentMaterial !== effectiveMaterial) {
  23359. this._currentMaterial = effectiveMaterial;
  23360. this._materialDefines = undefined;
  23361. }
  23362. return effectiveMaterial;
  23363. }
  23364. if (!rootMaterial) {
  23365. return this._mesh.getScene().defaultMaterial;
  23366. }
  23367. return rootMaterial;
  23368. };
  23369. // Methods
  23370. /**
  23371. * Sets a new updated BoundingInfo object to the submesh.
  23372. * Returns the SubMesh.
  23373. */
  23374. SubMesh.prototype.refreshBoundingInfo = function () {
  23375. this._lastColliderWorldVertices = null;
  23376. if (this.IsGlobal) {
  23377. return;
  23378. }
  23379. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23380. if (!data) {
  23381. this._boundingInfo = this._mesh._boundingInfo;
  23382. return;
  23383. }
  23384. var indices = this._renderingMesh.getIndices();
  23385. var extend;
  23386. //is this the only submesh?
  23387. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23388. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23389. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23390. }
  23391. else {
  23392. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23393. }
  23394. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23395. return this;
  23396. };
  23397. SubMesh.prototype._checkCollision = function (collider) {
  23398. return this.getBoundingInfo()._checkCollision(collider);
  23399. };
  23400. /**
  23401. * Updates the submesh BoundingInfo.
  23402. * Returns the Submesh.
  23403. */
  23404. SubMesh.prototype.updateBoundingInfo = function (world) {
  23405. if (!this.getBoundingInfo()) {
  23406. this.refreshBoundingInfo();
  23407. }
  23408. this.getBoundingInfo().update(world);
  23409. return this;
  23410. };
  23411. /**
  23412. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23413. * Boolean returned.
  23414. */
  23415. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23416. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23417. };
  23418. /**
  23419. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23420. * Boolean returned.
  23421. */
  23422. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23423. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23424. };
  23425. /**
  23426. * Renders the submesh.
  23427. * Returns it.
  23428. */
  23429. SubMesh.prototype.render = function (enableAlphaMode) {
  23430. this._renderingMesh.render(this, enableAlphaMode);
  23431. return this;
  23432. };
  23433. /**
  23434. * Returns a new Index Buffer.
  23435. * Type returned : WebGLBuffer.
  23436. */
  23437. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23438. if (!this._linesIndexBuffer) {
  23439. var linesIndices = [];
  23440. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23441. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23442. }
  23443. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23444. this.linesIndexCount = linesIndices.length;
  23445. }
  23446. return this._linesIndexBuffer;
  23447. };
  23448. /**
  23449. * True is the passed Ray intersects the submesh bounding box.
  23450. * Boolean returned.
  23451. */
  23452. SubMesh.prototype.canIntersects = function (ray) {
  23453. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23454. };
  23455. /**
  23456. * Returns an object IntersectionInfo.
  23457. */
  23458. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23459. var intersectInfo = null;
  23460. // LineMesh first as it's also a Mesh...
  23461. if (this._mesh instanceof BABYLON.LinesMesh) {
  23462. var lineMesh = this._mesh;
  23463. // Line test
  23464. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23465. var p0 = positions[indices[index]];
  23466. var p1 = positions[indices[index + 1]];
  23467. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23468. if (length < 0) {
  23469. continue;
  23470. }
  23471. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23472. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23473. if (fastCheck) {
  23474. break;
  23475. }
  23476. }
  23477. }
  23478. }
  23479. else {
  23480. // Triangles test
  23481. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23482. var p0 = positions[indices[index]];
  23483. var p1 = positions[indices[index + 1]];
  23484. var p2 = positions[indices[index + 2]];
  23485. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23486. if (currentIntersectInfo) {
  23487. if (currentIntersectInfo.distance < 0) {
  23488. continue;
  23489. }
  23490. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23491. intersectInfo = currentIntersectInfo;
  23492. intersectInfo.faceId = index / 3;
  23493. if (fastCheck) {
  23494. break;
  23495. }
  23496. }
  23497. }
  23498. }
  23499. }
  23500. return intersectInfo;
  23501. };
  23502. // Clone
  23503. /**
  23504. * Creates a new Submesh from the passed Mesh.
  23505. */
  23506. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23507. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23508. if (!this.IsGlobal) {
  23509. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23510. }
  23511. return result;
  23512. };
  23513. // Dispose
  23514. /**
  23515. * Disposes the Submesh.
  23516. * Returns nothing.
  23517. */
  23518. SubMesh.prototype.dispose = function () {
  23519. if (this._linesIndexBuffer) {
  23520. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23521. this._linesIndexBuffer = null;
  23522. }
  23523. // Remove from mesh
  23524. var index = this._mesh.subMeshes.indexOf(this);
  23525. this._mesh.subMeshes.splice(index, 1);
  23526. };
  23527. // Statics
  23528. /**
  23529. * Creates a new Submesh from the passed parameters :
  23530. * - materialIndex (integer) : the index of the main mesh material.
  23531. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23532. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23533. * - mesh (Mesh) : the main mesh to create the submesh from.
  23534. * - renderingMesh (optional Mesh) : rendering mesh.
  23535. */
  23536. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23537. var minVertexIndex = Number.MAX_VALUE;
  23538. var maxVertexIndex = -Number.MAX_VALUE;
  23539. renderingMesh = renderingMesh || mesh;
  23540. var indices = renderingMesh.getIndices();
  23541. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23542. var vertexIndex = indices[index];
  23543. if (vertexIndex < minVertexIndex)
  23544. minVertexIndex = vertexIndex;
  23545. if (vertexIndex > maxVertexIndex)
  23546. maxVertexIndex = vertexIndex;
  23547. }
  23548. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23549. };
  23550. return SubMesh;
  23551. }(BaseSubMesh));
  23552. BABYLON.SubMesh = SubMesh;
  23553. })(BABYLON || (BABYLON = {}));
  23554. //# sourceMappingURL=babylon.subMesh.js.map
  23555. var BABYLON;
  23556. (function (BABYLON) {
  23557. var EffectFallbacks = (function () {
  23558. function EffectFallbacks() {
  23559. this._defines = {};
  23560. this._currentRank = 32;
  23561. this._maxRank = -1;
  23562. }
  23563. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23564. if (!this._defines[rank]) {
  23565. if (rank < this._currentRank) {
  23566. this._currentRank = rank;
  23567. }
  23568. if (rank > this._maxRank) {
  23569. this._maxRank = rank;
  23570. }
  23571. this._defines[rank] = new Array();
  23572. }
  23573. this._defines[rank].push(define);
  23574. };
  23575. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23576. this._meshRank = rank;
  23577. this._mesh = mesh;
  23578. if (rank < this._currentRank) {
  23579. this._currentRank = rank;
  23580. }
  23581. if (rank > this._maxRank) {
  23582. this._maxRank = rank;
  23583. }
  23584. };
  23585. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23586. get: function () {
  23587. return this._currentRank <= this._maxRank;
  23588. },
  23589. enumerable: true,
  23590. configurable: true
  23591. });
  23592. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23593. // First we try to switch to CPU skinning
  23594. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23595. this._mesh.computeBonesUsingShaders = false;
  23596. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23597. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23598. var scene = this._mesh.getScene();
  23599. for (var index = 0; index < scene.meshes.length; index++) {
  23600. var otherMesh = scene.meshes[index];
  23601. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23602. otherMesh.computeBonesUsingShaders = false;
  23603. }
  23604. }
  23605. }
  23606. else {
  23607. var currentFallbacks = this._defines[this._currentRank];
  23608. if (currentFallbacks) {
  23609. for (var index = 0; index < currentFallbacks.length; index++) {
  23610. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23611. }
  23612. }
  23613. this._currentRank++;
  23614. }
  23615. return currentDefines;
  23616. };
  23617. return EffectFallbacks;
  23618. }());
  23619. BABYLON.EffectFallbacks = EffectFallbacks;
  23620. var EffectCreationOptions = (function () {
  23621. function EffectCreationOptions() {
  23622. }
  23623. return EffectCreationOptions;
  23624. }());
  23625. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23626. var Effect = (function () {
  23627. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23628. var _this = this;
  23629. this.uniqueId = 0;
  23630. this.onCompileObservable = new BABYLON.Observable();
  23631. this.onErrorObservable = new BABYLON.Observable();
  23632. this.onBindObservable = new BABYLON.Observable();
  23633. this._uniformBuffersNames = {};
  23634. this._isReady = false;
  23635. this._compilationError = "";
  23636. this._valueCache = {};
  23637. this.name = baseName;
  23638. if (attributesNamesOrOptions.attributes) {
  23639. var options = attributesNamesOrOptions;
  23640. this._engine = uniformsNamesOrEngine;
  23641. this._attributesNames = options.attributes;
  23642. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  23643. this._samplers = options.samplers;
  23644. this.defines = options.defines;
  23645. this.onError = options.onError;
  23646. this.onCompiled = options.onCompiled;
  23647. this._fallbacks = options.fallbacks;
  23648. this._indexParameters = options.indexParameters;
  23649. if (options.uniformBuffersNames) {
  23650. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  23651. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  23652. }
  23653. }
  23654. }
  23655. else {
  23656. this._engine = engine;
  23657. this.defines = defines;
  23658. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  23659. this._samplers = samplers;
  23660. this._attributesNames = attributesNamesOrOptions;
  23661. this.onError = onError;
  23662. this.onCompiled = onCompiled;
  23663. this._indexParameters = indexParameters;
  23664. this._fallbacks = fallbacks;
  23665. }
  23666. this.uniqueId = Effect._uniqueIdSeed++;
  23667. var vertexSource;
  23668. var fragmentSource;
  23669. if (baseName.vertexElement) {
  23670. vertexSource = document.getElementById(baseName.vertexElement);
  23671. if (!vertexSource) {
  23672. vertexSource = baseName.vertexElement;
  23673. }
  23674. }
  23675. else {
  23676. vertexSource = baseName.vertex || baseName;
  23677. }
  23678. if (baseName.fragmentElement) {
  23679. fragmentSource = document.getElementById(baseName.fragmentElement);
  23680. if (!fragmentSource) {
  23681. fragmentSource = baseName.fragmentElement;
  23682. }
  23683. }
  23684. else {
  23685. fragmentSource = baseName.fragment || baseName;
  23686. }
  23687. this._loadVertexShader(vertexSource, function (vertexCode) {
  23688. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23689. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  23690. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23691. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23692. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  23693. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks, baseName);
  23694. });
  23695. });
  23696. });
  23697. });
  23698. });
  23699. });
  23700. }
  23701. Object.defineProperty(Effect.prototype, "key", {
  23702. get: function () {
  23703. return this._key;
  23704. },
  23705. enumerable: true,
  23706. configurable: true
  23707. });
  23708. // Properties
  23709. Effect.prototype.isReady = function () {
  23710. return this._isReady;
  23711. };
  23712. Effect.prototype.getEngine = function () {
  23713. return this._engine;
  23714. };
  23715. Effect.prototype.getProgram = function () {
  23716. return this._program;
  23717. };
  23718. Effect.prototype.getAttributesNames = function () {
  23719. return this._attributesNames;
  23720. };
  23721. Effect.prototype.getAttributeLocation = function (index) {
  23722. return this._attributes[index];
  23723. };
  23724. Effect.prototype.getAttributeLocationByName = function (name) {
  23725. var index = this._attributesNames.indexOf(name);
  23726. return this._attributes[index];
  23727. };
  23728. Effect.prototype.getAttributesCount = function () {
  23729. return this._attributes.length;
  23730. };
  23731. Effect.prototype.getUniformIndex = function (uniformName) {
  23732. return this._uniformsNames.indexOf(uniformName);
  23733. };
  23734. Effect.prototype.getUniform = function (uniformName) {
  23735. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23736. };
  23737. Effect.prototype.getSamplers = function () {
  23738. return this._samplers;
  23739. };
  23740. Effect.prototype.getCompilationError = function () {
  23741. return this._compilationError;
  23742. };
  23743. // Methods
  23744. Effect.prototype.executeWhenCompiled = function (func) {
  23745. if (this.isReady()) {
  23746. func(this);
  23747. return;
  23748. }
  23749. this.onCompileObservable.add(function (effect) {
  23750. func(effect);
  23751. });
  23752. };
  23753. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23754. // DOM element ?
  23755. if (vertex instanceof HTMLElement) {
  23756. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23757. callback(vertexCode);
  23758. return;
  23759. }
  23760. // Base64 encoded ?
  23761. if (vertex.substr(0, 7) === "base64:") {
  23762. var vertexBinary = window.atob(vertex.substr(7));
  23763. callback(vertexBinary);
  23764. return;
  23765. }
  23766. // Is in local store ?
  23767. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23768. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23769. return;
  23770. }
  23771. var vertexShaderUrl;
  23772. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23773. vertexShaderUrl = vertex;
  23774. }
  23775. else {
  23776. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23777. }
  23778. // Vertex shader
  23779. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23780. };
  23781. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23782. // DOM element ?
  23783. if (fragment instanceof HTMLElement) {
  23784. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23785. callback(fragmentCode);
  23786. return;
  23787. }
  23788. // Base64 encoded ?
  23789. if (fragment.substr(0, 7) === "base64:") {
  23790. var fragmentBinary = window.atob(fragment.substr(7));
  23791. callback(fragmentBinary);
  23792. return;
  23793. }
  23794. // Is in local store ?
  23795. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23796. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23797. return;
  23798. }
  23799. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23800. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23801. return;
  23802. }
  23803. var fragmentShaderUrl;
  23804. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23805. fragmentShaderUrl = fragment;
  23806. }
  23807. else {
  23808. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23809. }
  23810. // Fragment shader
  23811. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23812. };
  23813. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  23814. // Rebuild shaders source code
  23815. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  23816. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  23817. vertexCode = prefix + vertexCode;
  23818. fragmentCode = prefix + fragmentCode;
  23819. // Number lines of shaders source code
  23820. var i = 2;
  23821. var regex = /\n/gm;
  23822. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23823. i = 2;
  23824. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23825. // Dump shaders name and formatted source code
  23826. if (this.name.vertexElement) {
  23827. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  23828. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  23829. }
  23830. else if (this.name.vertex) {
  23831. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  23832. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  23833. }
  23834. else {
  23835. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  23836. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  23837. }
  23838. };
  23839. ;
  23840. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  23841. var preparedSourceCode = this._processPrecision(sourceCode);
  23842. if (this._engine.webGLVersion == 1) {
  23843. callback(preparedSourceCode);
  23844. return;
  23845. }
  23846. // Already converted
  23847. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  23848. callback(preparedSourceCode.replace("#version 300 es", ""));
  23849. return;
  23850. }
  23851. // Remove extensions
  23852. // #extension GL_OES_standard_derivatives : enable
  23853. // #extension GL_EXT_shader_texture_lod : enable
  23854. // #extension GL_EXT_frag_depth : enable
  23855. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  23856. var result = preparedSourceCode.replace(regex, "");
  23857. // Migrate to GLSL v300
  23858. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  23859. result = result.replace(/attribute[ \t]/g, "in ");
  23860. result = result.replace(/[ \t]attribute/g, " in");
  23861. if (isFragment) {
  23862. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  23863. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  23864. result = result.replace(/texture2D\(/g, "texture(");
  23865. result = result.replace(/textureCube\(/g, "texture(");
  23866. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  23867. result = result.replace(/gl_FragColor/g, "glFragColor");
  23868. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  23869. }
  23870. callback(result);
  23871. };
  23872. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23873. var _this = this;
  23874. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23875. var match = regex.exec(sourceCode);
  23876. var returnValue = new String(sourceCode);
  23877. while (match != null) {
  23878. var includeFile = match[1];
  23879. // Uniform declaration
  23880. if (includeFile.indexOf("__decl__") !== -1) {
  23881. includeFile = includeFile.replace(/__decl__/, "");
  23882. if (this._engine.webGLVersion != 1) {
  23883. includeFile = includeFile.replace(/Vertex/, "Ubo");
  23884. includeFile = includeFile.replace(/Fragment/, "Ubo");
  23885. }
  23886. includeFile = includeFile + "Declaration";
  23887. }
  23888. if (Effect.IncludesShadersStore[includeFile]) {
  23889. // Substitution
  23890. var includeContent = Effect.IncludesShadersStore[includeFile];
  23891. if (match[2]) {
  23892. var splits = match[3].split(",");
  23893. for (var index = 0; index < splits.length; index += 2) {
  23894. var source = new RegExp(splits[index], "g");
  23895. var dest = splits[index + 1];
  23896. includeContent = includeContent.replace(source, dest);
  23897. }
  23898. }
  23899. if (match[4]) {
  23900. var indexString = match[5];
  23901. if (indexString.indexOf("..") !== -1) {
  23902. var indexSplits = indexString.split("..");
  23903. var minIndex = parseInt(indexSplits[0]);
  23904. var maxIndex = parseInt(indexSplits[1]);
  23905. var sourceIncludeContent = includeContent.slice(0);
  23906. includeContent = "";
  23907. if (isNaN(maxIndex)) {
  23908. maxIndex = this._indexParameters[indexSplits[1]];
  23909. }
  23910. for (var i = minIndex; i < maxIndex; i++) {
  23911. if (this._engine.webGLVersion === 1) {
  23912. // Ubo replacement
  23913. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23914. return p1 + "{X}";
  23915. });
  23916. }
  23917. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23918. }
  23919. }
  23920. else {
  23921. if (this._engine.webGLVersion === 1) {
  23922. // Ubo replacement
  23923. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23924. return p1 + "{X}";
  23925. });
  23926. }
  23927. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23928. }
  23929. }
  23930. // Replace
  23931. returnValue = returnValue.replace(match[0], includeContent);
  23932. }
  23933. else {
  23934. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23935. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23936. Effect.IncludesShadersStore[includeFile] = fileContent;
  23937. _this._processIncludes(returnValue, callback);
  23938. });
  23939. return;
  23940. }
  23941. match = regex.exec(sourceCode);
  23942. }
  23943. callback(returnValue);
  23944. };
  23945. Effect.prototype._processPrecision = function (source) {
  23946. if (source.indexOf("precision highp float") === -1) {
  23947. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23948. source = "precision mediump float;\n" + source;
  23949. }
  23950. else {
  23951. source = "precision highp float;\n" + source;
  23952. }
  23953. }
  23954. else {
  23955. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23956. source = source.replace("precision highp float", "precision mediump float");
  23957. }
  23958. }
  23959. return source;
  23960. };
  23961. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks, baseName) {
  23962. try {
  23963. var engine = this._engine;
  23964. if (baseName) {
  23965. vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + vertexSourceCode;
  23966. fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + fragmentSourceCode;
  23967. }
  23968. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23969. if (engine.webGLVersion > 1) {
  23970. for (var name in this._uniformBuffersNames) {
  23971. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23972. }
  23973. }
  23974. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23975. this._attributes = engine.getAttributes(this._program, attributesNames);
  23976. var index;
  23977. for (index = 0; index < this._samplers.length; index++) {
  23978. var sampler = this.getUniform(this._samplers[index]);
  23979. if (sampler == null) {
  23980. this._samplers.splice(index, 1);
  23981. index--;
  23982. }
  23983. }
  23984. engine.bindSamplers(this);
  23985. this._compilationError = "";
  23986. this._isReady = true;
  23987. if (this.onCompiled) {
  23988. this.onCompiled(this);
  23989. }
  23990. this.onCompileObservable.notifyObservers(this);
  23991. this.onCompileObservable.clear();
  23992. }
  23993. catch (e) {
  23994. this._compilationError = e.message;
  23995. // Let's go through fallbacks then
  23996. BABYLON.Tools.Error("Unable to compile effect:");
  23997. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23998. return " " + uniform;
  23999. }));
  24000. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24001. return " " + attribute;
  24002. }));
  24003. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  24004. BABYLON.Tools.Error("Error: " + this._compilationError);
  24005. if (fallbacks && fallbacks.isMoreFallbacks) {
  24006. BABYLON.Tools.Error("Trying next fallback.");
  24007. defines = fallbacks.reduce(defines);
  24008. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24009. }
  24010. else {
  24011. if (this.onError) {
  24012. this.onError(this, this._compilationError);
  24013. }
  24014. this.onErrorObservable.notifyObservers(this);
  24015. }
  24016. }
  24017. };
  24018. Object.defineProperty(Effect.prototype, "isSupported", {
  24019. get: function () {
  24020. return this._compilationError === "";
  24021. },
  24022. enumerable: true,
  24023. configurable: true
  24024. });
  24025. Effect.prototype._bindTexture = function (channel, texture) {
  24026. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24027. };
  24028. Effect.prototype.setTexture = function (channel, texture) {
  24029. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24030. };
  24031. Effect.prototype.setTextureArray = function (channel, textures) {
  24032. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24033. var initialPos = this._samplers.indexOf(channel);
  24034. for (var index = 1; index < textures.length; index++) {
  24035. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24036. }
  24037. }
  24038. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24039. };
  24040. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24041. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24042. };
  24043. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24044. var cache = this._valueCache[uniformName];
  24045. var flag = matrix.updateFlag;
  24046. if (cache !== undefined && cache === flag) {
  24047. return false;
  24048. }
  24049. this._valueCache[uniformName] = flag;
  24050. return true;
  24051. };
  24052. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24053. var cache = this._valueCache[uniformName];
  24054. if (!cache) {
  24055. cache = [x, y];
  24056. this._valueCache[uniformName] = cache;
  24057. return true;
  24058. }
  24059. var changed = false;
  24060. if (cache[0] !== x) {
  24061. cache[0] = x;
  24062. changed = true;
  24063. }
  24064. if (cache[1] !== y) {
  24065. cache[1] = y;
  24066. changed = true;
  24067. }
  24068. return changed;
  24069. };
  24070. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24071. var cache = this._valueCache[uniformName];
  24072. if (!cache) {
  24073. cache = [x, y, z];
  24074. this._valueCache[uniformName] = cache;
  24075. return true;
  24076. }
  24077. var changed = false;
  24078. if (cache[0] !== x) {
  24079. cache[0] = x;
  24080. changed = true;
  24081. }
  24082. if (cache[1] !== y) {
  24083. cache[1] = y;
  24084. changed = true;
  24085. }
  24086. if (cache[2] !== z) {
  24087. cache[2] = z;
  24088. changed = true;
  24089. }
  24090. return changed;
  24091. };
  24092. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24093. var cache = this._valueCache[uniformName];
  24094. if (!cache) {
  24095. cache = [x, y, z, w];
  24096. this._valueCache[uniformName] = cache;
  24097. return true;
  24098. }
  24099. var changed = false;
  24100. if (cache[0] !== x) {
  24101. cache[0] = x;
  24102. changed = true;
  24103. }
  24104. if (cache[1] !== y) {
  24105. cache[1] = y;
  24106. changed = true;
  24107. }
  24108. if (cache[2] !== z) {
  24109. cache[2] = z;
  24110. changed = true;
  24111. }
  24112. if (cache[3] !== w) {
  24113. cache[3] = w;
  24114. changed = true;
  24115. }
  24116. return changed;
  24117. };
  24118. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24119. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24120. return;
  24121. }
  24122. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24123. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24124. };
  24125. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24126. this._engine.bindUniformBlock(this._program, blockName, index);
  24127. };
  24128. Effect.prototype.setIntArray = function (uniformName, array) {
  24129. this._valueCache[uniformName] = null;
  24130. this._engine.setIntArray(this.getUniform(uniformName), array);
  24131. return this;
  24132. };
  24133. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24134. this._valueCache[uniformName] = null;
  24135. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24136. return this;
  24137. };
  24138. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24139. this._valueCache[uniformName] = null;
  24140. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24141. return this;
  24142. };
  24143. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24144. this._valueCache[uniformName] = null;
  24145. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24146. return this;
  24147. };
  24148. Effect.prototype.setFloatArray = function (uniformName, array) {
  24149. this._valueCache[uniformName] = null;
  24150. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24151. return this;
  24152. };
  24153. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24154. this._valueCache[uniformName] = null;
  24155. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24156. return this;
  24157. };
  24158. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24159. this._valueCache[uniformName] = null;
  24160. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24161. return this;
  24162. };
  24163. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24164. this._valueCache[uniformName] = null;
  24165. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24166. return this;
  24167. };
  24168. Effect.prototype.setArray = function (uniformName, array) {
  24169. this._valueCache[uniformName] = null;
  24170. this._engine.setArray(this.getUniform(uniformName), array);
  24171. return this;
  24172. };
  24173. Effect.prototype.setArray2 = function (uniformName, array) {
  24174. this._valueCache[uniformName] = null;
  24175. this._engine.setArray2(this.getUniform(uniformName), array);
  24176. return this;
  24177. };
  24178. Effect.prototype.setArray3 = function (uniformName, array) {
  24179. this._valueCache[uniformName] = null;
  24180. this._engine.setArray3(this.getUniform(uniformName), array);
  24181. return this;
  24182. };
  24183. Effect.prototype.setArray4 = function (uniformName, array) {
  24184. this._valueCache[uniformName] = null;
  24185. this._engine.setArray4(this.getUniform(uniformName), array);
  24186. return this;
  24187. };
  24188. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24189. if (!matrices) {
  24190. return;
  24191. }
  24192. this._valueCache[uniformName] = null;
  24193. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24194. return this;
  24195. };
  24196. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24197. if (this._cacheMatrix(uniformName, matrix)) {
  24198. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24199. }
  24200. return this;
  24201. };
  24202. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24203. this._valueCache[uniformName] = null;
  24204. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24205. return this;
  24206. };
  24207. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24208. this._valueCache[uniformName] = null;
  24209. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24210. return this;
  24211. };
  24212. Effect.prototype.setFloat = function (uniformName, value) {
  24213. var cache = this._valueCache[uniformName];
  24214. if (cache !== undefined && cache === value)
  24215. return this;
  24216. this._valueCache[uniformName] = value;
  24217. this._engine.setFloat(this.getUniform(uniformName), value);
  24218. return this;
  24219. };
  24220. Effect.prototype.setBool = function (uniformName, bool) {
  24221. var cache = this._valueCache[uniformName];
  24222. if (cache !== undefined && cache === bool)
  24223. return this;
  24224. this._valueCache[uniformName] = bool;
  24225. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24226. return this;
  24227. };
  24228. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24229. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24230. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24231. }
  24232. return this;
  24233. };
  24234. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24235. if (this._cacheFloat2(uniformName, x, y)) {
  24236. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24237. }
  24238. return this;
  24239. };
  24240. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24241. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24242. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24243. }
  24244. return this;
  24245. };
  24246. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24247. if (this._cacheFloat3(uniformName, x, y, z)) {
  24248. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24249. }
  24250. return this;
  24251. };
  24252. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24253. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24254. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24255. }
  24256. return this;
  24257. };
  24258. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24259. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24260. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24261. }
  24262. return this;
  24263. };
  24264. Effect.prototype.setColor3 = function (uniformName, color3) {
  24265. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24266. this._engine.setColor3(this.getUniform(uniformName), color3);
  24267. }
  24268. return this;
  24269. };
  24270. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24271. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24272. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24273. }
  24274. return this;
  24275. };
  24276. Effect.ResetCache = function () {
  24277. Effect._baseCache = {};
  24278. };
  24279. Effect._uniqueIdSeed = 0;
  24280. Effect._baseCache = {};
  24281. // Statics
  24282. Effect.ShadersStore = {};
  24283. Effect.IncludesShadersStore = {};
  24284. return Effect;
  24285. }());
  24286. BABYLON.Effect = Effect;
  24287. })(BABYLON || (BABYLON = {}));
  24288. //# sourceMappingURL=babylon.effect.js.map
  24289. var BABYLON;
  24290. (function (BABYLON) {
  24291. var MaterialHelper = (function () {
  24292. function MaterialHelper() {
  24293. }
  24294. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24295. defines._needUVs = true;
  24296. defines[key] = true;
  24297. if (texture.getTextureMatrix().isIdentity(true)) {
  24298. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24299. if (texture.coordinatesIndex === 0) {
  24300. defines["MAINUV1"] = true;
  24301. }
  24302. else {
  24303. defines["MAINUV2"] = true;
  24304. }
  24305. }
  24306. else {
  24307. defines[key + "DIRECTUV"] = 0;
  24308. }
  24309. };
  24310. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24311. var matrix = texture.getTextureMatrix();
  24312. if (!matrix.isIdentity(true)) {
  24313. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24314. }
  24315. };
  24316. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24317. if (defines._areMiscDirty) {
  24318. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24319. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24320. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24321. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24322. }
  24323. };
  24324. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24325. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24326. var changed = false;
  24327. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24328. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24329. changed = true;
  24330. }
  24331. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24332. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24333. changed = true;
  24334. }
  24335. if (defines["INSTANCES"] !== useInstances) {
  24336. defines["INSTANCES"] = useInstances;
  24337. changed = true;
  24338. }
  24339. if (changed) {
  24340. defines.markAsUnprocessed();
  24341. }
  24342. };
  24343. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24344. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24345. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24346. return false;
  24347. }
  24348. defines._normals = defines._needNormals;
  24349. defines._uvs = defines._needUVs;
  24350. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24351. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24352. defines["TANGENT"] = true;
  24353. }
  24354. if (defines._needUVs) {
  24355. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24356. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24357. }
  24358. else {
  24359. defines["UV1"] = false;
  24360. defines["UV2"] = false;
  24361. }
  24362. if (useVertexColor) {
  24363. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24364. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24365. }
  24366. if (useBones) {
  24367. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24368. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24369. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24370. }
  24371. else {
  24372. defines["NUM_BONE_INFLUENCERS"] = 0;
  24373. defines["BonesPerMesh"] = 0;
  24374. }
  24375. }
  24376. if (useMorphTargets) {
  24377. if (mesh.morphTargetManager) {
  24378. var manager = mesh.morphTargetManager;
  24379. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24380. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24381. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24382. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24383. }
  24384. else {
  24385. defines["MORPHTARGETS_TANGENT"] = false;
  24386. defines["MORPHTARGETS_NORMAL"] = false;
  24387. defines["MORPHTARGETS"] = false;
  24388. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24389. }
  24390. }
  24391. return true;
  24392. };
  24393. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24394. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24395. if (disableLighting === void 0) { disableLighting = false; }
  24396. if (!defines._areLightsDirty) {
  24397. return defines._needNormals;
  24398. }
  24399. var lightIndex = 0;
  24400. var needNormals = false;
  24401. var needRebuild = false;
  24402. var lightmapMode = false;
  24403. var shadowEnabled = false;
  24404. var specularEnabled = false;
  24405. if (scene.lightsEnabled && !disableLighting) {
  24406. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24407. var light = _a[_i];
  24408. needNormals = true;
  24409. if (defines["LIGHT" + lightIndex] === undefined) {
  24410. needRebuild = true;
  24411. }
  24412. defines["LIGHT" + lightIndex] = true;
  24413. defines["SPOTLIGHT" + lightIndex] = false;
  24414. defines["HEMILIGHT" + lightIndex] = false;
  24415. defines["POINTLIGHT" + lightIndex] = false;
  24416. defines["DIRLIGHT" + lightIndex] = false;
  24417. var type;
  24418. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24419. type = "SPOTLIGHT" + lightIndex;
  24420. }
  24421. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24422. type = "HEMILIGHT" + lightIndex;
  24423. }
  24424. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24425. type = "POINTLIGHT" + lightIndex;
  24426. }
  24427. else {
  24428. type = "DIRLIGHT" + lightIndex;
  24429. }
  24430. defines[type] = true;
  24431. // Specular
  24432. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24433. specularEnabled = true;
  24434. }
  24435. // Shadows
  24436. defines["SHADOW" + lightIndex] = false;
  24437. defines["SHADOWPCF" + lightIndex] = false;
  24438. defines["SHADOWESM" + lightIndex] = false;
  24439. defines["SHADOWCUBE" + lightIndex] = false;
  24440. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24441. var shadowGenerator = light.getShadowGenerator();
  24442. if (shadowGenerator) {
  24443. shadowEnabled = true;
  24444. shadowGenerator.prepareDefines(defines, lightIndex);
  24445. }
  24446. }
  24447. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24448. lightmapMode = true;
  24449. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24450. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24451. }
  24452. else {
  24453. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24454. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24455. }
  24456. lightIndex++;
  24457. if (lightIndex === maxSimultaneousLights)
  24458. break;
  24459. }
  24460. }
  24461. defines["SPECULARTERM"] = specularEnabled;
  24462. defines["SHADOWS"] = shadowEnabled;
  24463. // Resetting all other lights if any
  24464. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24465. if (defines["LIGHT" + index] !== undefined) {
  24466. defines["LIGHT" + index] = false;
  24467. defines["HEMILIGHT" + lightIndex] = false;
  24468. defines["POINTLIGHT" + lightIndex] = false;
  24469. defines["DIRLIGHT" + lightIndex] = false;
  24470. defines["SPOTLIGHT" + lightIndex] = false;
  24471. defines["SHADOW" + lightIndex] = false;
  24472. }
  24473. }
  24474. var caps = scene.getEngine().getCaps();
  24475. if (defines["SHADOWFLOAT"] === undefined) {
  24476. needRebuild = true;
  24477. }
  24478. defines["SHADOWFLOAT"] = shadowEnabled &&
  24479. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24480. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24481. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24482. if (needRebuild) {
  24483. defines.rebuild();
  24484. }
  24485. return needNormals;
  24486. };
  24487. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24488. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24489. var uniformsList, uniformBuffersList, samplersList, defines;
  24490. if (uniformsListOrOptions.uniformsNames) {
  24491. var options = uniformsListOrOptions;
  24492. uniformsList = options.uniformsNames;
  24493. uniformBuffersList = options.uniformBuffersNames;
  24494. samplersList = options.samplers;
  24495. defines = options.defines;
  24496. maxSimultaneousLights = options.maxSimultaneousLights;
  24497. }
  24498. else {
  24499. uniformsList = uniformsListOrOptions;
  24500. }
  24501. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24502. if (!defines["LIGHT" + lightIndex]) {
  24503. break;
  24504. }
  24505. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24506. if (uniformBuffersList) {
  24507. uniformBuffersList.push("Light" + lightIndex);
  24508. }
  24509. samplersList.push("shadowSampler" + lightIndex);
  24510. }
  24511. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24512. uniformsList.push("morphTargetInfluences");
  24513. }
  24514. };
  24515. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24516. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24517. if (!defines["SHADOWS"]) {
  24518. return;
  24519. }
  24520. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24521. if (!defines["LIGHT" + lightIndex]) {
  24522. break;
  24523. }
  24524. if (lightIndex > 0) {
  24525. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24526. }
  24527. if (defines["SHADOW" + lightIndex]) {
  24528. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24529. }
  24530. if (defines["SHADOWPCF" + lightIndex]) {
  24531. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24532. }
  24533. if (defines["SHADOWESM" + lightIndex]) {
  24534. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24535. }
  24536. }
  24537. };
  24538. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24539. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24540. if (influencers > 0) {
  24541. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24542. var manager = mesh.morphTargetManager;
  24543. var normal = manager.supportsNormals && defines["NORMAL"];
  24544. var tangent = manager.supportsTangents && defines["TANGENT"];
  24545. for (var index = 0; index < influencers; index++) {
  24546. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24547. if (normal) {
  24548. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24549. }
  24550. if (tangent) {
  24551. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24552. }
  24553. if (attribs.length > maxAttributesCount) {
  24554. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24555. }
  24556. }
  24557. }
  24558. };
  24559. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24560. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24561. fallbacks.addCPUSkinningFallback(0, mesh);
  24562. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24563. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24564. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24565. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24566. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24567. }
  24568. }
  24569. };
  24570. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24571. if (defines["INSTANCES"]) {
  24572. attribs.push("world0");
  24573. attribs.push("world1");
  24574. attribs.push("world2");
  24575. attribs.push("world3");
  24576. }
  24577. };
  24578. // Bindings
  24579. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24580. if (light.shadowEnabled && mesh.receiveShadows) {
  24581. var shadowGenerator = light.getShadowGenerator();
  24582. if (shadowGenerator) {
  24583. shadowGenerator.bindShadowLight(lightIndex, effect);
  24584. }
  24585. }
  24586. };
  24587. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24588. light.transferToEffect(effect, lightIndex + "");
  24589. };
  24590. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24591. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24592. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24593. var lightIndex = 0;
  24594. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24595. var light = _a[_i];
  24596. var scaledIntensity = light.getScaledIntensity();
  24597. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24598. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24599. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24600. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24601. if (defines["SPECULARTERM"]) {
  24602. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24603. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24604. }
  24605. // Shadows
  24606. if (scene.shadowsEnabled) {
  24607. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24608. }
  24609. light._uniformBuffer.update();
  24610. lightIndex++;
  24611. if (lightIndex === maxSimultaneousLights)
  24612. break;
  24613. }
  24614. };
  24615. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24616. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24617. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24618. effect.setColor3("vFogColor", scene.fogColor);
  24619. }
  24620. };
  24621. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24622. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24623. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24624. if (matrices) {
  24625. effect.setMatrices("mBones", matrices);
  24626. }
  24627. }
  24628. };
  24629. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  24630. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  24631. return;
  24632. }
  24633. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  24634. };
  24635. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24636. if (defines["LOGARITHMICDEPTH"]) {
  24637. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24638. }
  24639. };
  24640. MaterialHelper.BindClipPlane = function (effect, scene) {
  24641. if (scene.clipPlane) {
  24642. var clipPlane = scene.clipPlane;
  24643. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24644. }
  24645. };
  24646. return MaterialHelper;
  24647. }());
  24648. BABYLON.MaterialHelper = MaterialHelper;
  24649. })(BABYLON || (BABYLON = {}));
  24650. //# sourceMappingURL=babylon.materialHelper.js.map
  24651. var BABYLON;
  24652. (function (BABYLON) {
  24653. var MaterialDefines = (function () {
  24654. function MaterialDefines() {
  24655. this._isDirty = true;
  24656. this._areLightsDirty = true;
  24657. this._areAttributesDirty = true;
  24658. this._areTexturesDirty = true;
  24659. this._areFresnelDirty = true;
  24660. this._areMiscDirty = true;
  24661. this._areImageProcessingDirty = true;
  24662. this._normals = false;
  24663. this._uvs = false;
  24664. this._needNormals = false;
  24665. this._needUVs = false;
  24666. }
  24667. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  24668. get: function () {
  24669. return this._isDirty;
  24670. },
  24671. enumerable: true,
  24672. configurable: true
  24673. });
  24674. MaterialDefines.prototype.markAsProcessed = function () {
  24675. this._isDirty = false;
  24676. this._areAttributesDirty = false;
  24677. this._areTexturesDirty = false;
  24678. this._areFresnelDirty = false;
  24679. this._areLightsDirty = false;
  24680. this._areMiscDirty = false;
  24681. this._areImageProcessingDirty = false;
  24682. };
  24683. MaterialDefines.prototype.markAsUnprocessed = function () {
  24684. this._isDirty = true;
  24685. };
  24686. MaterialDefines.prototype.markAllAsDirty = function () {
  24687. this._areTexturesDirty = true;
  24688. this._areAttributesDirty = true;
  24689. this._areLightsDirty = true;
  24690. this._areFresnelDirty = true;
  24691. this._areMiscDirty = true;
  24692. this._areImageProcessingDirty = true;
  24693. this._isDirty = true;
  24694. };
  24695. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  24696. this._areImageProcessingDirty = true;
  24697. this._isDirty = true;
  24698. };
  24699. MaterialDefines.prototype.markAsLightDirty = function () {
  24700. this._areLightsDirty = true;
  24701. this._isDirty = true;
  24702. };
  24703. MaterialDefines.prototype.markAsAttributesDirty = function () {
  24704. this._areAttributesDirty = true;
  24705. this._isDirty = true;
  24706. };
  24707. MaterialDefines.prototype.markAsTexturesDirty = function () {
  24708. this._areTexturesDirty = true;
  24709. this._isDirty = true;
  24710. };
  24711. MaterialDefines.prototype.markAsFresnelDirty = function () {
  24712. this._areFresnelDirty = true;
  24713. this._isDirty = true;
  24714. };
  24715. MaterialDefines.prototype.markAsMiscDirty = function () {
  24716. this._areMiscDirty = true;
  24717. this._isDirty = true;
  24718. };
  24719. MaterialDefines.prototype.rebuild = function () {
  24720. if (this._keys) {
  24721. delete this._keys;
  24722. }
  24723. this._keys = [];
  24724. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  24725. var key = _a[_i];
  24726. if (key[0] === "_") {
  24727. continue;
  24728. }
  24729. this._keys.push(key);
  24730. }
  24731. };
  24732. MaterialDefines.prototype.isEqual = function (other) {
  24733. if (this._keys.length !== other._keys.length) {
  24734. return false;
  24735. }
  24736. for (var index = 0; index < this._keys.length; index++) {
  24737. var prop = this._keys[index];
  24738. if (this[prop] !== other[prop]) {
  24739. return false;
  24740. }
  24741. }
  24742. return true;
  24743. };
  24744. MaterialDefines.prototype.cloneTo = function (other) {
  24745. if (this._keys.length !== other._keys.length) {
  24746. other._keys = this._keys.slice(0);
  24747. }
  24748. for (var index = 0; index < this._keys.length; index++) {
  24749. var prop = this._keys[index];
  24750. other[prop] = this[prop];
  24751. }
  24752. };
  24753. MaterialDefines.prototype.reset = function () {
  24754. for (var index = 0; index < this._keys.length; index++) {
  24755. var prop = this._keys[index];
  24756. if (typeof (this[prop]) === "number") {
  24757. this[prop] = 0;
  24758. }
  24759. else {
  24760. this[prop] = false;
  24761. }
  24762. }
  24763. };
  24764. MaterialDefines.prototype.toString = function () {
  24765. var result = "";
  24766. for (var index = 0; index < this._keys.length; index++) {
  24767. var prop = this._keys[index];
  24768. var value = this[prop];
  24769. if (typeof (value) === "number") {
  24770. result += "#define " + prop + " " + this[prop] + "\n";
  24771. }
  24772. else if (value) {
  24773. result += "#define " + prop + "\n";
  24774. }
  24775. }
  24776. return result;
  24777. };
  24778. return MaterialDefines;
  24779. }());
  24780. BABYLON.MaterialDefines = MaterialDefines;
  24781. var Material = (function () {
  24782. function Material(name, scene, doNotAdd) {
  24783. this.checkReadyOnEveryCall = false;
  24784. this.checkReadyOnlyOnce = false;
  24785. this.state = "";
  24786. this.alpha = 1.0;
  24787. this._backFaceCulling = true;
  24788. this.doNotSerialize = false;
  24789. this.storeEffectOnSubMeshes = false;
  24790. /**
  24791. * An event triggered when the material is disposed.
  24792. * @type {BABYLON.Observable}
  24793. */
  24794. this.onDisposeObservable = new BABYLON.Observable();
  24795. /**
  24796. * An event triggered when the material is bound.
  24797. * @type {BABYLON.Observable}
  24798. */
  24799. this.onBindObservable = new BABYLON.Observable();
  24800. /**
  24801. * An event triggered when the material is unbound.
  24802. * @type {BABYLON.Observable}
  24803. */
  24804. this.onUnBindObservable = new BABYLON.Observable();
  24805. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24806. this.disableDepthWrite = false;
  24807. this._fogEnabled = true;
  24808. this.pointSize = 1.0;
  24809. this.zOffset = 0;
  24810. this._wasPreviouslyReady = false;
  24811. this._fillMode = Material.TriangleFillMode;
  24812. this.name = name;
  24813. this.id = name || BABYLON.Tools.RandomId();
  24814. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24815. if (this._scene.useRightHandedSystem) {
  24816. this.sideOrientation = Material.ClockWiseSideOrientation;
  24817. }
  24818. else {
  24819. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24820. }
  24821. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  24822. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  24823. if (!doNotAdd) {
  24824. this._scene.materials.push(this);
  24825. }
  24826. }
  24827. Object.defineProperty(Material, "TriangleFillMode", {
  24828. get: function () {
  24829. return Material._TriangleFillMode;
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. Object.defineProperty(Material, "WireFrameFillMode", {
  24835. get: function () {
  24836. return Material._WireFrameFillMode;
  24837. },
  24838. enumerable: true,
  24839. configurable: true
  24840. });
  24841. Object.defineProperty(Material, "PointFillMode", {
  24842. get: function () {
  24843. return Material._PointFillMode;
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24849. get: function () {
  24850. return Material._ClockWiseSideOrientation;
  24851. },
  24852. enumerable: true,
  24853. configurable: true
  24854. });
  24855. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24856. get: function () {
  24857. return Material._CounterClockWiseSideOrientation;
  24858. },
  24859. enumerable: true,
  24860. configurable: true
  24861. });
  24862. Object.defineProperty(Material, "TextureDirtyFlag", {
  24863. get: function () {
  24864. return Material._TextureDirtyFlag;
  24865. },
  24866. enumerable: true,
  24867. configurable: true
  24868. });
  24869. Object.defineProperty(Material, "LightDirtyFlag", {
  24870. get: function () {
  24871. return Material._LightDirtyFlag;
  24872. },
  24873. enumerable: true,
  24874. configurable: true
  24875. });
  24876. Object.defineProperty(Material, "FresnelDirtyFlag", {
  24877. get: function () {
  24878. return Material._FresnelDirtyFlag;
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24884. get: function () {
  24885. return Material._AttributesDirtyFlag;
  24886. },
  24887. enumerable: true,
  24888. configurable: true
  24889. });
  24890. Object.defineProperty(Material, "MiscDirtyFlag", {
  24891. get: function () {
  24892. return Material._MiscDirtyFlag;
  24893. },
  24894. enumerable: true,
  24895. configurable: true
  24896. });
  24897. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24898. get: function () {
  24899. return this._backFaceCulling;
  24900. },
  24901. set: function (value) {
  24902. if (this._backFaceCulling === value) {
  24903. return;
  24904. }
  24905. this._backFaceCulling = value;
  24906. this.markAsDirty(Material.TextureDirtyFlag);
  24907. },
  24908. enumerable: true,
  24909. configurable: true
  24910. });
  24911. Object.defineProperty(Material.prototype, "onDispose", {
  24912. set: function (callback) {
  24913. if (this._onDisposeObserver) {
  24914. this.onDisposeObservable.remove(this._onDisposeObserver);
  24915. }
  24916. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. Object.defineProperty(Material.prototype, "onBind", {
  24922. set: function (callback) {
  24923. if (this._onBindObserver) {
  24924. this.onBindObservable.remove(this._onBindObserver);
  24925. }
  24926. this._onBindObserver = this.onBindObservable.add(callback);
  24927. },
  24928. enumerable: true,
  24929. configurable: true
  24930. });
  24931. Object.defineProperty(Material.prototype, "fogEnabled", {
  24932. get: function () {
  24933. return this._fogEnabled;
  24934. },
  24935. set: function (value) {
  24936. if (this._fogEnabled === value) {
  24937. return;
  24938. }
  24939. this._fogEnabled = value;
  24940. this.markAsDirty(Material.MiscDirtyFlag);
  24941. },
  24942. enumerable: true,
  24943. configurable: true
  24944. });
  24945. Object.defineProperty(Material.prototype, "wireframe", {
  24946. get: function () {
  24947. return this._fillMode === Material.WireFrameFillMode;
  24948. },
  24949. set: function (value) {
  24950. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24951. },
  24952. enumerable: true,
  24953. configurable: true
  24954. });
  24955. Object.defineProperty(Material.prototype, "pointsCloud", {
  24956. get: function () {
  24957. return this._fillMode === Material.PointFillMode;
  24958. },
  24959. set: function (value) {
  24960. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24961. },
  24962. enumerable: true,
  24963. configurable: true
  24964. });
  24965. Object.defineProperty(Material.prototype, "fillMode", {
  24966. get: function () {
  24967. return this._fillMode;
  24968. },
  24969. set: function (value) {
  24970. if (this._fillMode === value) {
  24971. return;
  24972. }
  24973. this._fillMode = value;
  24974. this.markAsDirty(Material.MiscDirtyFlag);
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. /**
  24980. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24981. * subclasses should override adding information pertainent to themselves
  24982. */
  24983. Material.prototype.toString = function (fullDetails) {
  24984. var ret = "Name: " + this.name;
  24985. if (fullDetails) {
  24986. }
  24987. return ret;
  24988. };
  24989. /**
  24990. * Child classes can use it to update shaders
  24991. */
  24992. Material.prototype.getClassName = function () {
  24993. return "Material";
  24994. };
  24995. Object.defineProperty(Material.prototype, "isFrozen", {
  24996. get: function () {
  24997. return this.checkReadyOnlyOnce;
  24998. },
  24999. enumerable: true,
  25000. configurable: true
  25001. });
  25002. Material.prototype.freeze = function () {
  25003. this.checkReadyOnlyOnce = true;
  25004. };
  25005. Material.prototype.unfreeze = function () {
  25006. this.checkReadyOnlyOnce = false;
  25007. };
  25008. Material.prototype.isReady = function (mesh, useInstances) {
  25009. return true;
  25010. };
  25011. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25012. return false;
  25013. };
  25014. Material.prototype.getEffect = function () {
  25015. return this._effect;
  25016. };
  25017. Material.prototype.getScene = function () {
  25018. return this._scene;
  25019. };
  25020. Material.prototype.needAlphaBlending = function () {
  25021. return (this.alpha < 1.0);
  25022. };
  25023. Material.prototype.needAlphaTesting = function () {
  25024. return false;
  25025. };
  25026. Material.prototype.getAlphaTestTexture = function () {
  25027. return null;
  25028. };
  25029. Material.prototype.markDirty = function () {
  25030. this._wasPreviouslyReady = false;
  25031. };
  25032. Material.prototype._preBind = function (effect) {
  25033. var engine = this._scene.getEngine();
  25034. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25035. engine.enableEffect(effect ? effect : this._effect);
  25036. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25037. };
  25038. Material.prototype.bind = function (world, mesh) {
  25039. };
  25040. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25041. };
  25042. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25043. };
  25044. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25045. sceneUbo.bindToEffect(effect, "Scene");
  25046. };
  25047. Material.prototype.bindView = function (effect) {
  25048. if (!this._useUBO) {
  25049. effect.setMatrix("view", this.getScene().getViewMatrix());
  25050. }
  25051. else {
  25052. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25053. }
  25054. };
  25055. Material.prototype.bindViewProjection = function (effect) {
  25056. if (!this._useUBO) {
  25057. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25058. }
  25059. else {
  25060. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25061. }
  25062. };
  25063. Material.prototype._afterBind = function (mesh) {
  25064. this._scene._cachedMaterial = this;
  25065. if (mesh) {
  25066. this._scene._cachedVisibility = mesh.visibility;
  25067. }
  25068. else {
  25069. this._scene._cachedVisibility = 1;
  25070. }
  25071. this.onBindObservable.notifyObservers(mesh);
  25072. if (this.disableDepthWrite) {
  25073. var engine = this._scene.getEngine();
  25074. this._cachedDepthWriteState = engine.getDepthWrite();
  25075. engine.setDepthWrite(false);
  25076. }
  25077. };
  25078. Material.prototype.unbind = function () {
  25079. this.onUnBindObservable.notifyObservers(this);
  25080. if (this.disableDepthWrite) {
  25081. var engine = this._scene.getEngine();
  25082. engine.setDepthWrite(this._cachedDepthWriteState);
  25083. }
  25084. };
  25085. Material.prototype.getActiveTextures = function () {
  25086. return [];
  25087. };
  25088. Material.prototype.hasTexture = function (texture) {
  25089. return false;
  25090. };
  25091. Material.prototype.clone = function (name) {
  25092. return null;
  25093. };
  25094. Material.prototype.getBindedMeshes = function () {
  25095. var result = new Array();
  25096. for (var index = 0; index < this._scene.meshes.length; index++) {
  25097. var mesh = this._scene.meshes[index];
  25098. if (mesh.material === this) {
  25099. result.push(mesh);
  25100. }
  25101. }
  25102. return result;
  25103. };
  25104. /**
  25105. * Force shader compilation including textures ready check
  25106. */
  25107. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25108. var _this = this;
  25109. var subMesh = new BABYLON.BaseSubMesh();
  25110. var scene = this.getScene();
  25111. var engine = scene.getEngine();
  25112. var checkReady = function () {
  25113. if (!_this._scene || !_this._scene.getEngine()) {
  25114. return;
  25115. }
  25116. if (subMesh._materialDefines) {
  25117. subMesh._materialDefines._renderId = -1;
  25118. }
  25119. var alphaTestState = engine.getAlphaTesting();
  25120. var clipPlaneState = scene.clipPlane;
  25121. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25122. if (options && options.clipPlane) {
  25123. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25124. }
  25125. if (_this.storeEffectOnSubMeshes) {
  25126. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25127. if (onCompiled) {
  25128. onCompiled(_this);
  25129. }
  25130. }
  25131. else {
  25132. setTimeout(checkReady, 16);
  25133. }
  25134. }
  25135. else {
  25136. if (_this.isReady(mesh)) {
  25137. if (onCompiled) {
  25138. onCompiled(_this);
  25139. }
  25140. }
  25141. else {
  25142. setTimeout(checkReady, 16);
  25143. }
  25144. }
  25145. engine.setAlphaTesting(alphaTestState);
  25146. if (options && options.clipPlane) {
  25147. scene.clipPlane = clipPlaneState;
  25148. }
  25149. };
  25150. checkReady();
  25151. };
  25152. Material.prototype.markAsDirty = function (flag) {
  25153. if (flag & Material.TextureDirtyFlag) {
  25154. this._markAllSubMeshesAsTexturesDirty();
  25155. }
  25156. if (flag & Material.LightDirtyFlag) {
  25157. this._markAllSubMeshesAsLightsDirty();
  25158. }
  25159. if (flag & Material.FresnelDirtyFlag) {
  25160. this._markAllSubMeshesAsFresnelDirty();
  25161. }
  25162. if (flag & Material.AttributesDirtyFlag) {
  25163. this._markAllSubMeshesAsAttributesDirty();
  25164. }
  25165. if (flag & Material.MiscDirtyFlag) {
  25166. this._markAllSubMeshesAsMiscDirty();
  25167. }
  25168. this.getScene().resetCachedMaterial();
  25169. };
  25170. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25171. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25172. var mesh = _a[_i];
  25173. if (!mesh.subMeshes) {
  25174. continue;
  25175. }
  25176. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25177. var subMesh = _c[_b];
  25178. if (subMesh.getMaterial() !== this) {
  25179. continue;
  25180. }
  25181. if (!subMesh._materialDefines) {
  25182. continue;
  25183. }
  25184. func(subMesh._materialDefines);
  25185. }
  25186. }
  25187. };
  25188. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25189. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25190. };
  25191. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25192. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25193. };
  25194. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25195. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25196. };
  25197. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25198. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25199. };
  25200. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25201. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25202. };
  25203. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25204. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25205. };
  25206. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25207. // Animations
  25208. this.getScene().stopAnimation(this);
  25209. // Remove from scene
  25210. var index = this._scene.materials.indexOf(this);
  25211. if (index >= 0) {
  25212. this._scene.materials.splice(index, 1);
  25213. }
  25214. // Remove from meshes
  25215. for (index = 0; index < this._scene.meshes.length; index++) {
  25216. var mesh = this._scene.meshes[index];
  25217. if (mesh.material === this) {
  25218. mesh.material = null;
  25219. if (mesh.geometry) {
  25220. var geometry = mesh.geometry;
  25221. if (this.storeEffectOnSubMeshes) {
  25222. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25223. var subMesh = _a[_i];
  25224. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25225. }
  25226. }
  25227. else {
  25228. geometry._releaseVertexArrayObject(this._effect);
  25229. }
  25230. }
  25231. }
  25232. }
  25233. this._uniformBuffer.dispose();
  25234. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25235. if (forceDisposeEffect && this._effect) {
  25236. if (this.storeEffectOnSubMeshes) {
  25237. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25238. var subMesh = _c[_b];
  25239. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25240. }
  25241. }
  25242. else {
  25243. this._scene.getEngine()._releaseEffect(this._effect);
  25244. }
  25245. this._effect = null;
  25246. }
  25247. // Callback
  25248. this.onDisposeObservable.notifyObservers(this);
  25249. this.onDisposeObservable.clear();
  25250. this.onBindObservable.clear();
  25251. this.onUnBindObservable.clear();
  25252. };
  25253. Material.prototype.serialize = function () {
  25254. return BABYLON.SerializationHelper.Serialize(this);
  25255. };
  25256. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25257. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25258. multiMaterial.id = parsedMultiMaterial.id;
  25259. if (BABYLON.Tags) {
  25260. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25261. }
  25262. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25263. var subMatId = parsedMultiMaterial.materials[matIndex];
  25264. if (subMatId) {
  25265. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25266. }
  25267. else {
  25268. multiMaterial.subMaterials.push(null);
  25269. }
  25270. }
  25271. return multiMaterial;
  25272. };
  25273. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25274. if (!parsedMaterial.customType) {
  25275. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25276. }
  25277. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25278. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25279. if (!BABYLON.LegacyPBRMaterial) {
  25280. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25281. return;
  25282. }
  25283. }
  25284. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25285. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25286. ;
  25287. };
  25288. Material._TriangleFillMode = 0;
  25289. Material._WireFrameFillMode = 1;
  25290. Material._PointFillMode = 2;
  25291. Material._ClockWiseSideOrientation = 0;
  25292. Material._CounterClockWiseSideOrientation = 1;
  25293. Material._TextureDirtyFlag = 1;
  25294. Material._LightDirtyFlag = 2;
  25295. Material._FresnelDirtyFlag = 4;
  25296. Material._AttributesDirtyFlag = 8;
  25297. Material._MiscDirtyFlag = 16;
  25298. __decorate([
  25299. BABYLON.serialize()
  25300. ], Material.prototype, "id", void 0);
  25301. __decorate([
  25302. BABYLON.serialize()
  25303. ], Material.prototype, "name", void 0);
  25304. __decorate([
  25305. BABYLON.serialize()
  25306. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25307. __decorate([
  25308. BABYLON.serialize()
  25309. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25310. __decorate([
  25311. BABYLON.serialize()
  25312. ], Material.prototype, "state", void 0);
  25313. __decorate([
  25314. BABYLON.serialize()
  25315. ], Material.prototype, "alpha", void 0);
  25316. __decorate([
  25317. BABYLON.serialize("backFaceCulling")
  25318. ], Material.prototype, "_backFaceCulling", void 0);
  25319. __decorate([
  25320. BABYLON.serialize()
  25321. ], Material.prototype, "sideOrientation", void 0);
  25322. __decorate([
  25323. BABYLON.serialize()
  25324. ], Material.prototype, "alphaMode", void 0);
  25325. __decorate([
  25326. BABYLON.serialize()
  25327. ], Material.prototype, "disableDepthWrite", void 0);
  25328. __decorate([
  25329. BABYLON.serialize("fogEnabled")
  25330. ], Material.prototype, "_fogEnabled", void 0);
  25331. __decorate([
  25332. BABYLON.serialize()
  25333. ], Material.prototype, "pointSize", void 0);
  25334. __decorate([
  25335. BABYLON.serialize()
  25336. ], Material.prototype, "zOffset", void 0);
  25337. __decorate([
  25338. BABYLON.serialize()
  25339. ], Material.prototype, "wireframe", null);
  25340. __decorate([
  25341. BABYLON.serialize()
  25342. ], Material.prototype, "pointsCloud", null);
  25343. __decorate([
  25344. BABYLON.serialize()
  25345. ], Material.prototype, "fillMode", null);
  25346. return Material;
  25347. }());
  25348. BABYLON.Material = Material;
  25349. })(BABYLON || (BABYLON = {}));
  25350. //# sourceMappingURL=babylon.material.js.map
  25351. var BABYLON;
  25352. (function (BABYLON) {
  25353. var UniformBuffer = (function () {
  25354. /**
  25355. * Uniform buffer objects.
  25356. *
  25357. * Handles blocks of uniform on the GPU.
  25358. *
  25359. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25360. *
  25361. * For more information, please refer to :
  25362. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25363. */
  25364. function UniformBuffer(engine, data, dynamic) {
  25365. this._engine = engine;
  25366. this._noUBO = engine.webGLVersion === 1;
  25367. this._dynamic = dynamic;
  25368. this._data = data || [];
  25369. this._uniformLocations = {};
  25370. this._uniformSizes = {};
  25371. this._uniformLocationPointer = 0;
  25372. this._needSync = false;
  25373. if (this._noUBO) {
  25374. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25375. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25376. this.updateFloat = this._updateFloatForEffect;
  25377. this.updateFloat2 = this._updateFloat2ForEffect;
  25378. this.updateFloat3 = this._updateFloat3ForEffect;
  25379. this.updateFloat4 = this._updateFloat4ForEffect;
  25380. this.updateMatrix = this._updateMatrixForEffect;
  25381. this.updateVector3 = this._updateVector3ForEffect;
  25382. this.updateVector4 = this._updateVector4ForEffect;
  25383. this.updateColor3 = this._updateColor3ForEffect;
  25384. this.updateColor4 = this._updateColor4ForEffect;
  25385. }
  25386. else {
  25387. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25388. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25389. this.updateFloat = this._updateFloatForUniform;
  25390. this.updateFloat2 = this._updateFloat2ForUniform;
  25391. this.updateFloat3 = this._updateFloat3ForUniform;
  25392. this.updateFloat4 = this._updateFloat4ForUniform;
  25393. this.updateMatrix = this._updateMatrixForUniform;
  25394. this.updateVector3 = this._updateVector3ForUniform;
  25395. this.updateVector4 = this._updateVector4ForUniform;
  25396. this.updateColor3 = this._updateColor3ForUniform;
  25397. this.updateColor4 = this._updateColor4ForUniform;
  25398. }
  25399. }
  25400. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25401. // Properties
  25402. /**
  25403. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25404. * or just falling back on setUniformXXX calls.
  25405. */
  25406. get: function () {
  25407. return !this._noUBO;
  25408. },
  25409. enumerable: true,
  25410. configurable: true
  25411. });
  25412. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25413. /**
  25414. * Indicates if the WebGL underlying uniform buffer is in sync
  25415. * with the javascript cache data.
  25416. */
  25417. get: function () {
  25418. return !this._needSync;
  25419. },
  25420. enumerable: true,
  25421. configurable: true
  25422. });
  25423. /**
  25424. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25425. * Also, a dynamic UniformBuffer will disable cache verification and always
  25426. * update the underlying WebGL uniform buffer to the GPU.
  25427. */
  25428. UniformBuffer.prototype.isDynamic = function () {
  25429. return this._dynamic;
  25430. };
  25431. /**
  25432. * The data cache on JS side.
  25433. */
  25434. UniformBuffer.prototype.getData = function () {
  25435. return this._bufferData;
  25436. };
  25437. /**
  25438. * The underlying WebGL Uniform buffer.
  25439. */
  25440. UniformBuffer.prototype.getBuffer = function () {
  25441. return this._buffer;
  25442. };
  25443. /**
  25444. * std140 layout specifies how to align data within an UBO structure.
  25445. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25446. * for specs.
  25447. */
  25448. UniformBuffer.prototype._fillAlignment = function (size) {
  25449. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25450. // and 4x4 matrices
  25451. // TODO : change if other types are used
  25452. var alignment;
  25453. if (size <= 2) {
  25454. alignment = size;
  25455. }
  25456. else {
  25457. alignment = 4;
  25458. }
  25459. if ((this._uniformLocationPointer % alignment) !== 0) {
  25460. var oldPointer = this._uniformLocationPointer;
  25461. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25462. var diff = this._uniformLocationPointer - oldPointer;
  25463. for (var i = 0; i < diff; i++) {
  25464. this._data.push(0);
  25465. }
  25466. }
  25467. };
  25468. /**
  25469. * Adds an uniform in the buffer.
  25470. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25471. * for the layout to be correct !
  25472. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25473. * @param {number|number[]} size Data size, or data directly.
  25474. */
  25475. UniformBuffer.prototype.addUniform = function (name, size) {
  25476. if (this._noUBO) {
  25477. return;
  25478. }
  25479. if (this._uniformLocations[name] !== undefined) {
  25480. // Already existing uniform
  25481. return;
  25482. }
  25483. // This function must be called in the order of the shader layout !
  25484. // size can be the size of the uniform, or data directly
  25485. var data;
  25486. if (size instanceof Array) {
  25487. data = size;
  25488. size = data.length;
  25489. }
  25490. else {
  25491. size = size;
  25492. data = [];
  25493. // Fill with zeros
  25494. for (var i = 0; i < size; i++) {
  25495. data.push(0);
  25496. }
  25497. }
  25498. this._fillAlignment(size);
  25499. this._uniformSizes[name] = size;
  25500. this._uniformLocations[name] = this._uniformLocationPointer;
  25501. this._uniformLocationPointer += size;
  25502. for (var i = 0; i < size; i++) {
  25503. this._data.push(data[i]);
  25504. }
  25505. this._needSync = true;
  25506. };
  25507. /**
  25508. * Wrapper for addUniform.
  25509. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25510. * @param {Matrix} mat A 4x4 matrix.
  25511. */
  25512. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25513. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25514. };
  25515. /**
  25516. * Wrapper for addUniform.
  25517. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25518. * @param {number} x
  25519. * @param {number} y
  25520. */
  25521. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25522. var temp = [x, y];
  25523. this.addUniform(name, temp);
  25524. };
  25525. /**
  25526. * Wrapper for addUniform.
  25527. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25528. * @param {number} x
  25529. * @param {number} y
  25530. * @param {number} z
  25531. */
  25532. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25533. var temp = [x, y, z];
  25534. this.addUniform(name, temp);
  25535. };
  25536. /**
  25537. * Wrapper for addUniform.
  25538. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25539. * @param {Color3} color
  25540. */
  25541. UniformBuffer.prototype.addColor3 = function (name, color) {
  25542. var temp = [];
  25543. color.toArray(temp);
  25544. this.addUniform(name, temp);
  25545. };
  25546. /**
  25547. * Wrapper for addUniform.
  25548. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25549. * @param {Color3} color
  25550. * @param {number} alpha
  25551. */
  25552. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25553. var temp = [];
  25554. color.toArray(temp);
  25555. temp.push(alpha);
  25556. this.addUniform(name, temp);
  25557. };
  25558. /**
  25559. * Wrapper for addUniform.
  25560. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25561. * @param {Vector3} vector
  25562. */
  25563. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25564. var temp = [];
  25565. vector.toArray(temp);
  25566. this.addUniform(name, temp);
  25567. };
  25568. /**
  25569. * Wrapper for addUniform.
  25570. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25571. */
  25572. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25573. this.addUniform(name, 12);
  25574. };
  25575. /**
  25576. * Wrapper for addUniform.
  25577. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25578. */
  25579. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25580. this.addUniform(name, 8);
  25581. };
  25582. /**
  25583. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25584. */
  25585. UniformBuffer.prototype.create = function () {
  25586. if (this._noUBO) {
  25587. return;
  25588. }
  25589. if (this._buffer) {
  25590. return; // nothing to do
  25591. }
  25592. // See spec, alignment must be filled as a vec4
  25593. this._fillAlignment(4);
  25594. this._bufferData = new Float32Array(this._data);
  25595. if (this._dynamic) {
  25596. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25597. }
  25598. else {
  25599. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25600. }
  25601. this._needSync = true;
  25602. };
  25603. /**
  25604. * Updates the WebGL Uniform Buffer on the GPU.
  25605. * If the `dynamic` flag is set to true, no cache comparison is done.
  25606. * Otherwise, the buffer will be updated only if the cache differs.
  25607. */
  25608. UniformBuffer.prototype.update = function () {
  25609. if (!this._buffer) {
  25610. this.create();
  25611. return;
  25612. }
  25613. if (!this._dynamic && !this._needSync) {
  25614. return;
  25615. }
  25616. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25617. this._needSync = false;
  25618. };
  25619. /**
  25620. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  25621. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25622. * @param {number[]|Float32Array} data Flattened data
  25623. * @param {number} size Size of the data.
  25624. */
  25625. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  25626. var location = this._uniformLocations[uniformName];
  25627. if (location === undefined) {
  25628. if (this._buffer) {
  25629. // Cannot add an uniform if the buffer is already created
  25630. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  25631. return;
  25632. }
  25633. this.addUniform(uniformName, size);
  25634. location = this._uniformLocations[uniformName];
  25635. }
  25636. if (!this._buffer) {
  25637. this.create();
  25638. }
  25639. if (!this._dynamic) {
  25640. // Cache for static uniform buffers
  25641. var changed = false;
  25642. for (var i = 0; i < size; i++) {
  25643. if (this._bufferData[location + i] !== data[i]) {
  25644. changed = true;
  25645. this._bufferData[location + i] = data[i];
  25646. }
  25647. }
  25648. this._needSync = this._needSync || changed;
  25649. }
  25650. else {
  25651. // No cache for dynamic
  25652. for (var i = 0; i < size; i++) {
  25653. this._bufferData[location + i] = data[i];
  25654. }
  25655. }
  25656. };
  25657. // Update methods
  25658. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  25659. // To match std140, matrix must be realigned
  25660. for (var i = 0; i < 3; i++) {
  25661. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  25662. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  25663. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  25664. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25665. }
  25666. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  25667. };
  25668. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  25669. this._currentEffect.setMatrix3x3(name, matrix);
  25670. };
  25671. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  25672. this._currentEffect.setMatrix2x2(name, matrix);
  25673. };
  25674. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  25675. // To match std140, matrix must be realigned
  25676. for (var i = 0; i < 2; i++) {
  25677. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  25678. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  25679. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  25680. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  25681. }
  25682. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  25683. };
  25684. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  25685. this._currentEffect.setFloat(name, x);
  25686. };
  25687. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  25688. UniformBuffer._tempBuffer[0] = x;
  25689. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  25690. };
  25691. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  25692. if (suffix === void 0) { suffix = ""; }
  25693. this._currentEffect.setFloat2(name + suffix, x, y);
  25694. };
  25695. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  25696. if (suffix === void 0) { suffix = ""; }
  25697. UniformBuffer._tempBuffer[0] = x;
  25698. UniformBuffer._tempBuffer[1] = y;
  25699. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  25700. };
  25701. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  25702. if (suffix === void 0) { suffix = ""; }
  25703. this._currentEffect.setFloat3(name + suffix, x, y, z);
  25704. };
  25705. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  25706. if (suffix === void 0) { suffix = ""; }
  25707. UniformBuffer._tempBuffer[0] = x;
  25708. UniformBuffer._tempBuffer[1] = y;
  25709. UniformBuffer._tempBuffer[2] = z;
  25710. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25711. };
  25712. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  25713. if (suffix === void 0) { suffix = ""; }
  25714. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  25715. };
  25716. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  25717. if (suffix === void 0) { suffix = ""; }
  25718. UniformBuffer._tempBuffer[0] = x;
  25719. UniformBuffer._tempBuffer[1] = y;
  25720. UniformBuffer._tempBuffer[2] = z;
  25721. UniformBuffer._tempBuffer[3] = w;
  25722. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25723. };
  25724. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  25725. this._currentEffect.setMatrix(name, mat);
  25726. };
  25727. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  25728. this.updateUniform(name, mat.toArray(), 16);
  25729. };
  25730. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  25731. this._currentEffect.setVector3(name, vector);
  25732. };
  25733. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  25734. vector.toArray(UniformBuffer._tempBuffer);
  25735. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25736. };
  25737. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  25738. this._currentEffect.setVector4(name, vector);
  25739. };
  25740. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  25741. vector.toArray(UniformBuffer._tempBuffer);
  25742. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25743. };
  25744. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  25745. if (suffix === void 0) { suffix = ""; }
  25746. this._currentEffect.setColor3(name + suffix, color);
  25747. };
  25748. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  25749. if (suffix === void 0) { suffix = ""; }
  25750. color.toArray(UniformBuffer._tempBuffer);
  25751. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25752. };
  25753. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  25754. if (suffix === void 0) { suffix = ""; }
  25755. this._currentEffect.setColor4(name + suffix, color, alpha);
  25756. };
  25757. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  25758. if (suffix === void 0) { suffix = ""; }
  25759. color.toArray(UniformBuffer._tempBuffer);
  25760. UniformBuffer._tempBuffer[3] = alpha;
  25761. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25762. };
  25763. /**
  25764. * Sets a sampler uniform on the effect.
  25765. * @param {string} name Name of the sampler.
  25766. * @param {Texture} texture
  25767. */
  25768. UniformBuffer.prototype.setTexture = function (name, texture) {
  25769. this._currentEffect.setTexture(name, texture);
  25770. };
  25771. /**
  25772. * Directly updates the value of the uniform in the cache AND on the GPU.
  25773. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25774. * @param {number[]|Float32Array} data Flattened data
  25775. */
  25776. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  25777. this.updateUniform(uniformName, data, data.length);
  25778. this.update();
  25779. };
  25780. /**
  25781. * Binds this uniform buffer to an effect.
  25782. * @param {Effect} effect
  25783. * @param {string} name Name of the uniform block in the shader.
  25784. */
  25785. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  25786. this._currentEffect = effect;
  25787. if (this._noUBO) {
  25788. return;
  25789. }
  25790. effect.bindUniformBuffer(this._buffer, name);
  25791. };
  25792. /**
  25793. * Disposes the uniform buffer.
  25794. */
  25795. UniformBuffer.prototype.dispose = function () {
  25796. if (!this._buffer) {
  25797. return;
  25798. }
  25799. if (this._engine._releaseBuffer(this._buffer)) {
  25800. this._buffer = null;
  25801. }
  25802. };
  25803. // Pool for avoiding memory leaks
  25804. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  25805. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  25806. return UniformBuffer;
  25807. }());
  25808. BABYLON.UniformBuffer = UniformBuffer;
  25809. })(BABYLON || (BABYLON = {}));
  25810. //# sourceMappingURL=babylon.uniformBuffer.js.map
  25811. var BABYLON;
  25812. (function (BABYLON) {
  25813. var PushMaterial = (function (_super) {
  25814. __extends(PushMaterial, _super);
  25815. function PushMaterial(name, scene) {
  25816. var _this = _super.call(this, name, scene) || this;
  25817. _this.storeEffectOnSubMeshes = true;
  25818. return _this;
  25819. }
  25820. PushMaterial.prototype.getEffect = function () {
  25821. return this._activeEffect;
  25822. };
  25823. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  25824. if (!mesh) {
  25825. return false;
  25826. }
  25827. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25828. return true;
  25829. }
  25830. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  25831. };
  25832. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25833. this._activeEffect.setMatrix("world", world);
  25834. };
  25835. PushMaterial.prototype.bind = function (world, mesh) {
  25836. if (!mesh) {
  25837. return;
  25838. }
  25839. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  25840. };
  25841. PushMaterial.prototype._afterBind = function (mesh, effect) {
  25842. _super.prototype._afterBind.call(this, mesh);
  25843. this.getScene()._cachedEffect = effect;
  25844. };
  25845. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  25846. if (visibility === void 0) { visibility = 1; }
  25847. return scene.isCachedMaterialInvalid(this, effect, visibility);
  25848. };
  25849. return PushMaterial;
  25850. }(BABYLON.Material));
  25851. BABYLON.PushMaterial = PushMaterial;
  25852. })(BABYLON || (BABYLON = {}));
  25853. //# sourceMappingURL=babylon.pushMaterial.js.map
  25854. var BABYLON;
  25855. (function (BABYLON) {
  25856. var VertexData = (function () {
  25857. function VertexData() {
  25858. }
  25859. VertexData.prototype.set = function (data, kind) {
  25860. switch (kind) {
  25861. case BABYLON.VertexBuffer.PositionKind:
  25862. this.positions = data;
  25863. break;
  25864. case BABYLON.VertexBuffer.NormalKind:
  25865. this.normals = data;
  25866. break;
  25867. case BABYLON.VertexBuffer.TangentKind:
  25868. this.tangents = data;
  25869. break;
  25870. case BABYLON.VertexBuffer.UVKind:
  25871. this.uvs = data;
  25872. break;
  25873. case BABYLON.VertexBuffer.UV2Kind:
  25874. this.uvs2 = data;
  25875. break;
  25876. case BABYLON.VertexBuffer.UV3Kind:
  25877. this.uvs3 = data;
  25878. break;
  25879. case BABYLON.VertexBuffer.UV4Kind:
  25880. this.uvs4 = data;
  25881. break;
  25882. case BABYLON.VertexBuffer.UV5Kind:
  25883. this.uvs5 = data;
  25884. break;
  25885. case BABYLON.VertexBuffer.UV6Kind:
  25886. this.uvs6 = data;
  25887. break;
  25888. case BABYLON.VertexBuffer.ColorKind:
  25889. this.colors = data;
  25890. break;
  25891. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25892. this.matricesIndices = data;
  25893. break;
  25894. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25895. this.matricesWeights = data;
  25896. break;
  25897. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25898. this.matricesIndicesExtra = data;
  25899. break;
  25900. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25901. this.matricesWeightsExtra = data;
  25902. break;
  25903. }
  25904. };
  25905. /**
  25906. * Associates the vertexData to the passed Mesh.
  25907. * Sets it as updatable or not (default `false`).
  25908. * Returns the VertexData.
  25909. */
  25910. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25911. this._applyTo(mesh, updatable);
  25912. return this;
  25913. };
  25914. /**
  25915. * Associates the vertexData to the passed Geometry.
  25916. * Sets it as updatable or not (default `false`).
  25917. * Returns the VertexData.
  25918. */
  25919. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25920. this._applyTo(geometry, updatable);
  25921. return this;
  25922. };
  25923. /**
  25924. * Updates the associated mesh.
  25925. * Returns the VertexData.
  25926. */
  25927. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25928. this._update(mesh);
  25929. return this;
  25930. };
  25931. /**
  25932. * Updates the associated geometry.
  25933. * Returns the VertexData.
  25934. */
  25935. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25936. this._update(geometry);
  25937. return this;
  25938. };
  25939. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25940. if (this.positions) {
  25941. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25942. }
  25943. if (this.normals) {
  25944. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25945. }
  25946. if (this.tangents) {
  25947. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25948. }
  25949. if (this.uvs) {
  25950. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25951. }
  25952. if (this.uvs2) {
  25953. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25954. }
  25955. if (this.uvs3) {
  25956. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25957. }
  25958. if (this.uvs4) {
  25959. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25960. }
  25961. if (this.uvs5) {
  25962. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25963. }
  25964. if (this.uvs6) {
  25965. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25966. }
  25967. if (this.colors) {
  25968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25969. }
  25970. if (this.matricesIndices) {
  25971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25972. }
  25973. if (this.matricesWeights) {
  25974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25975. }
  25976. if (this.matricesIndicesExtra) {
  25977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25978. }
  25979. if (this.matricesWeightsExtra) {
  25980. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25981. }
  25982. if (this.indices) {
  25983. meshOrGeometry.setIndices(this.indices);
  25984. }
  25985. return this;
  25986. };
  25987. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25988. if (this.positions) {
  25989. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25990. }
  25991. if (this.normals) {
  25992. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25993. }
  25994. if (this.tangents) {
  25995. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25996. }
  25997. if (this.uvs) {
  25998. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25999. }
  26000. if (this.uvs2) {
  26001. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26002. }
  26003. if (this.uvs3) {
  26004. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26005. }
  26006. if (this.uvs4) {
  26007. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26008. }
  26009. if (this.uvs5) {
  26010. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26011. }
  26012. if (this.uvs6) {
  26013. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26014. }
  26015. if (this.colors) {
  26016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26017. }
  26018. if (this.matricesIndices) {
  26019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26020. }
  26021. if (this.matricesWeights) {
  26022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26023. }
  26024. if (this.matricesIndicesExtra) {
  26025. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26026. }
  26027. if (this.matricesWeightsExtra) {
  26028. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26029. }
  26030. if (this.indices) {
  26031. meshOrGeometry.setIndices(this.indices);
  26032. }
  26033. return this;
  26034. };
  26035. /**
  26036. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26037. * Returns the VertexData.
  26038. */
  26039. VertexData.prototype.transform = function (matrix) {
  26040. var transformed = BABYLON.Vector3.Zero();
  26041. var index;
  26042. if (this.positions) {
  26043. var position = BABYLON.Vector3.Zero();
  26044. for (index = 0; index < this.positions.length; index += 3) {
  26045. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26046. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26047. this.positions[index] = transformed.x;
  26048. this.positions[index + 1] = transformed.y;
  26049. this.positions[index + 2] = transformed.z;
  26050. }
  26051. }
  26052. if (this.normals) {
  26053. var normal = BABYLON.Vector3.Zero();
  26054. for (index = 0; index < this.normals.length; index += 3) {
  26055. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26056. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26057. this.normals[index] = transformed.x;
  26058. this.normals[index + 1] = transformed.y;
  26059. this.normals[index + 2] = transformed.z;
  26060. }
  26061. }
  26062. if (this.tangents) {
  26063. var tangent = BABYLON.Vector4.Zero();
  26064. var tangentTransformed = BABYLON.Vector4.Zero();
  26065. for (index = 0; index < this.tangents.length; index += 4) {
  26066. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26067. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26068. this.tangents[index] = tangentTransformed.x;
  26069. this.tangents[index + 1] = tangentTransformed.y;
  26070. this.tangents[index + 2] = tangentTransformed.z;
  26071. this.tangents[index + 3] = tangentTransformed.w;
  26072. }
  26073. }
  26074. return this;
  26075. };
  26076. /**
  26077. * Merges the passed VertexData into the current one.
  26078. * Returns the modified VertexData.
  26079. */
  26080. VertexData.prototype.merge = function (other) {
  26081. if (other.indices) {
  26082. if (!this.indices) {
  26083. this.indices = [];
  26084. }
  26085. var offset = this.positions ? this.positions.length / 3 : 0;
  26086. for (var index = 0; index < other.indices.length; index++) {
  26087. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26088. this.indices.push(other.indices[index] + offset);
  26089. }
  26090. }
  26091. this.positions = this._mergeElement(this.positions, other.positions);
  26092. this.normals = this._mergeElement(this.normals, other.normals);
  26093. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26094. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26095. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26096. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26097. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26098. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26099. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26100. this.colors = this._mergeElement(this.colors, other.colors);
  26101. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26102. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26103. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26104. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26105. return this;
  26106. };
  26107. VertexData.prototype._mergeElement = function (source, other) {
  26108. if (!other)
  26109. return source;
  26110. if (!source)
  26111. return other;
  26112. var len = other.length + source.length;
  26113. var isSrcTypedArray = source instanceof Float32Array;
  26114. var isOthTypedArray = other instanceof Float32Array;
  26115. // use non-loop method when the source is Float32Array
  26116. if (isSrcTypedArray) {
  26117. var ret32 = new Float32Array(len);
  26118. ret32.set(source);
  26119. ret32.set(other, source.length);
  26120. return ret32;
  26121. // source is number[], when other is also use concat
  26122. }
  26123. else if (!isOthTypedArray) {
  26124. return source.concat(other);
  26125. // source is a number[], but other is a Float32Array, loop required
  26126. }
  26127. else {
  26128. var ret = source.slice(0); // copy source to a separate array
  26129. for (var i = 0, len = other.length; i < len; i++) {
  26130. ret.push(other[i]);
  26131. }
  26132. return ret;
  26133. }
  26134. };
  26135. /**
  26136. * Serializes the VertexData.
  26137. * Returns a serialized object.
  26138. */
  26139. VertexData.prototype.serialize = function () {
  26140. var serializationObject = this.serialize();
  26141. if (this.positions) {
  26142. serializationObject.positions = this.positions;
  26143. }
  26144. if (this.normals) {
  26145. serializationObject.normals = this.normals;
  26146. }
  26147. if (this.tangents) {
  26148. serializationObject.tangents = this.tangents;
  26149. }
  26150. if (this.uvs) {
  26151. serializationObject.uvs = this.uvs;
  26152. }
  26153. if (this.uvs2) {
  26154. serializationObject.uvs2 = this.uvs2;
  26155. }
  26156. if (this.uvs3) {
  26157. serializationObject.uvs3 = this.uvs3;
  26158. }
  26159. if (this.uvs4) {
  26160. serializationObject.uvs4 = this.uvs4;
  26161. }
  26162. if (this.uvs5) {
  26163. serializationObject.uvs5 = this.uvs5;
  26164. }
  26165. if (this.uvs6) {
  26166. serializationObject.uvs6 = this.uvs6;
  26167. }
  26168. if (this.colors) {
  26169. serializationObject.colors = this.colors;
  26170. }
  26171. if (this.matricesIndices) {
  26172. serializationObject.matricesIndices = this.matricesIndices;
  26173. serializationObject.matricesIndices._isExpanded = true;
  26174. }
  26175. if (this.matricesWeights) {
  26176. serializationObject.matricesWeights = this.matricesWeights;
  26177. }
  26178. if (this.matricesIndicesExtra) {
  26179. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26180. serializationObject.matricesIndicesExtra._isExpanded = true;
  26181. }
  26182. if (this.matricesWeightsExtra) {
  26183. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26184. }
  26185. serializationObject.indices = this.indices;
  26186. return serializationObject;
  26187. };
  26188. // Statics
  26189. /**
  26190. * Returns the object VertexData associated to the passed mesh.
  26191. */
  26192. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26193. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26194. };
  26195. /**
  26196. * Returns the object VertexData associated to the passed geometry.
  26197. */
  26198. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26199. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26200. };
  26201. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26202. var result = new VertexData();
  26203. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26204. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26205. }
  26206. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26207. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26208. }
  26209. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26210. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26211. }
  26212. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26213. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26214. }
  26215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26216. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26217. }
  26218. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26219. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26220. }
  26221. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26222. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26223. }
  26224. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26225. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26226. }
  26227. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26228. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26229. }
  26230. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26231. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26232. }
  26233. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26234. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26235. }
  26236. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26237. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26238. }
  26239. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26240. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26241. }
  26242. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26243. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26244. }
  26245. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26246. return result;
  26247. };
  26248. /**
  26249. * Creates the vertexData of the Ribbon.
  26250. */
  26251. VertexData.CreateRibbon = function (options) {
  26252. var pathArray = options.pathArray;
  26253. var closeArray = options.closeArray || false;
  26254. var closePath = options.closePath || false;
  26255. var invertUV = options.invertUV || false;
  26256. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26257. var offset = options.offset || defaultOffset;
  26258. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26259. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26260. var customUV = options.uvs;
  26261. var customColors = options.colors;
  26262. var positions = [];
  26263. var indices = [];
  26264. var normals = [];
  26265. var uvs = [];
  26266. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26267. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26268. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26269. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26270. var minlg; // minimal length among all paths from pathArray
  26271. var lg = []; // array of path lengths : nb of vertex per path
  26272. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26273. var p; // path iterator
  26274. var i; // point iterator
  26275. var j; // point iterator
  26276. // if single path in pathArray
  26277. if (pathArray.length < 2) {
  26278. var ar1 = [];
  26279. var ar2 = [];
  26280. for (i = 0; i < pathArray[0].length - offset; i++) {
  26281. ar1.push(pathArray[0][i]);
  26282. ar2.push(pathArray[0][i + offset]);
  26283. }
  26284. pathArray = [ar1, ar2];
  26285. }
  26286. // positions and horizontal distances (u)
  26287. var idc = 0;
  26288. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26289. var path;
  26290. var l;
  26291. minlg = pathArray[0].length;
  26292. var vectlg;
  26293. var dist;
  26294. for (p = 0; p < pathArray.length; p++) {
  26295. uTotalDistance[p] = 0;
  26296. us[p] = [0];
  26297. path = pathArray[p];
  26298. l = path.length;
  26299. minlg = (minlg < l) ? minlg : l;
  26300. j = 0;
  26301. while (j < l) {
  26302. positions.push(path[j].x, path[j].y, path[j].z);
  26303. if (j > 0) {
  26304. vectlg = path[j].subtract(path[j - 1]).length();
  26305. dist = vectlg + uTotalDistance[p];
  26306. us[p].push(dist);
  26307. uTotalDistance[p] = dist;
  26308. }
  26309. j++;
  26310. }
  26311. if (closePath) {
  26312. j--;
  26313. positions.push(path[0].x, path[0].y, path[0].z);
  26314. vectlg = path[j].subtract(path[0]).length();
  26315. dist = vectlg + uTotalDistance[p];
  26316. us[p].push(dist);
  26317. uTotalDistance[p] = dist;
  26318. }
  26319. lg[p] = l + closePathCorr;
  26320. idx[p] = idc;
  26321. idc += (l + closePathCorr);
  26322. }
  26323. // vertical distances (v)
  26324. var path1;
  26325. var path2;
  26326. var vertex1;
  26327. var vertex2;
  26328. for (i = 0; i < minlg + closePathCorr; i++) {
  26329. vTotalDistance[i] = 0;
  26330. vs[i] = [0];
  26331. for (p = 0; p < pathArray.length - 1; p++) {
  26332. path1 = pathArray[p];
  26333. path2 = pathArray[p + 1];
  26334. if (i === minlg) {
  26335. vertex1 = path1[0];
  26336. vertex2 = path2[0];
  26337. }
  26338. else {
  26339. vertex1 = path1[i];
  26340. vertex2 = path2[i];
  26341. }
  26342. vectlg = vertex2.subtract(vertex1).length();
  26343. dist = vectlg + vTotalDistance[i];
  26344. vs[i].push(dist);
  26345. vTotalDistance[i] = dist;
  26346. }
  26347. if (closeArray) {
  26348. path1 = pathArray[p];
  26349. path2 = pathArray[0];
  26350. if (i === minlg) {
  26351. vertex2 = path2[0];
  26352. }
  26353. vectlg = vertex2.subtract(vertex1).length();
  26354. dist = vectlg + vTotalDistance[i];
  26355. vTotalDistance[i] = dist;
  26356. }
  26357. }
  26358. // uvs
  26359. var u;
  26360. var v;
  26361. if (customUV) {
  26362. for (p = 0; p < customUV.length; p++) {
  26363. uvs.push(customUV[p].x, customUV[p].y);
  26364. }
  26365. }
  26366. else {
  26367. for (p = 0; p < pathArray.length; p++) {
  26368. for (i = 0; i < minlg + closePathCorr; i++) {
  26369. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26370. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26371. if (invertUV) {
  26372. uvs.push(v, u);
  26373. }
  26374. else {
  26375. uvs.push(u, v);
  26376. }
  26377. }
  26378. }
  26379. }
  26380. // indices
  26381. p = 0; // path index
  26382. var pi = 0; // positions array index
  26383. var l1 = lg[p] - 1; // path1 length
  26384. var l2 = lg[p + 1] - 1; // path2 length
  26385. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26386. var shft = idx[1] - idx[0]; // shift
  26387. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26388. while (pi <= min && p < path1nb) {
  26389. // 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
  26390. indices.push(pi, pi + shft, pi + 1);
  26391. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26392. pi += 1;
  26393. if (pi === min) {
  26394. p++;
  26395. if (p === lg.length - 1) {
  26396. shft = idx[0] - idx[p];
  26397. l1 = lg[p] - 1;
  26398. l2 = lg[0] - 1;
  26399. }
  26400. else {
  26401. shft = idx[p + 1] - idx[p];
  26402. l1 = lg[p] - 1;
  26403. l2 = lg[p + 1] - 1;
  26404. }
  26405. pi = idx[p];
  26406. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26407. }
  26408. }
  26409. // normals
  26410. VertexData.ComputeNormals(positions, indices, normals);
  26411. if (closePath) {
  26412. var indexFirst = 0;
  26413. var indexLast = 0;
  26414. for (p = 0; p < pathArray.length; p++) {
  26415. indexFirst = idx[p] * 3;
  26416. if (p + 1 < pathArray.length) {
  26417. indexLast = (idx[p + 1] - 1) * 3;
  26418. }
  26419. else {
  26420. indexLast = normals.length - 3;
  26421. }
  26422. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26423. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26424. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26425. normals[indexLast] = normals[indexFirst];
  26426. normals[indexLast + 1] = normals[indexFirst + 1];
  26427. normals[indexLast + 2] = normals[indexFirst + 2];
  26428. }
  26429. }
  26430. // sides
  26431. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26432. // Colors
  26433. if (customColors) {
  26434. var colors = new Float32Array(customColors.length * 4);
  26435. for (var c = 0; c < customColors.length; c++) {
  26436. colors[c * 4] = customColors[c].r;
  26437. colors[c * 4 + 1] = customColors[c].g;
  26438. colors[c * 4 + 2] = customColors[c].b;
  26439. colors[c * 4 + 3] = customColors[c].a;
  26440. }
  26441. }
  26442. // Result
  26443. var vertexData = new VertexData();
  26444. var positions32 = new Float32Array(positions);
  26445. var normals32 = new Float32Array(normals);
  26446. var uvs32 = new Float32Array(uvs);
  26447. vertexData.indices = indices;
  26448. vertexData.positions = positions32;
  26449. vertexData.normals = normals32;
  26450. vertexData.uvs = uvs32;
  26451. if (customColors) {
  26452. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26453. }
  26454. if (closePath) {
  26455. vertexData._idx = idx;
  26456. }
  26457. return vertexData;
  26458. };
  26459. /**
  26460. * Creates the VertexData of the Box.
  26461. */
  26462. VertexData.CreateBox = function (options) {
  26463. var normalsSource = [
  26464. new BABYLON.Vector3(0, 0, 1),
  26465. new BABYLON.Vector3(0, 0, -1),
  26466. new BABYLON.Vector3(1, 0, 0),
  26467. new BABYLON.Vector3(-1, 0, 0),
  26468. new BABYLON.Vector3(0, 1, 0),
  26469. new BABYLON.Vector3(0, -1, 0)
  26470. ];
  26471. var indices = [];
  26472. var positions = [];
  26473. var normals = [];
  26474. var uvs = [];
  26475. var width = options.width || options.size || 1;
  26476. var height = options.height || options.size || 1;
  26477. var depth = options.depth || options.size || 1;
  26478. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26479. var faceUV = options.faceUV || new Array(6);
  26480. var faceColors = options.faceColors;
  26481. var colors = [];
  26482. // default face colors and UV if undefined
  26483. for (var f = 0; f < 6; f++) {
  26484. if (faceUV[f] === undefined) {
  26485. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26486. }
  26487. if (faceColors && faceColors[f] === undefined) {
  26488. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26489. }
  26490. }
  26491. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26492. // Create each face in turn.
  26493. for (var index = 0; index < normalsSource.length; index++) {
  26494. var normal = normalsSource[index];
  26495. // Get two vectors perpendicular to the face normal and to each other.
  26496. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26497. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26498. // Six indices (two triangles) per face.
  26499. var verticesLength = positions.length / 3;
  26500. indices.push(verticesLength);
  26501. indices.push(verticesLength + 1);
  26502. indices.push(verticesLength + 2);
  26503. indices.push(verticesLength);
  26504. indices.push(verticesLength + 2);
  26505. indices.push(verticesLength + 3);
  26506. // Four vertices per face.
  26507. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26508. positions.push(vertex.x, vertex.y, vertex.z);
  26509. normals.push(normal.x, normal.y, normal.z);
  26510. uvs.push(faceUV[index].z, faceUV[index].w);
  26511. if (faceColors) {
  26512. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26513. }
  26514. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26515. positions.push(vertex.x, vertex.y, vertex.z);
  26516. normals.push(normal.x, normal.y, normal.z);
  26517. uvs.push(faceUV[index].x, faceUV[index].w);
  26518. if (faceColors) {
  26519. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26520. }
  26521. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26522. positions.push(vertex.x, vertex.y, vertex.z);
  26523. normals.push(normal.x, normal.y, normal.z);
  26524. uvs.push(faceUV[index].x, faceUV[index].y);
  26525. if (faceColors) {
  26526. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26527. }
  26528. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26529. positions.push(vertex.x, vertex.y, vertex.z);
  26530. normals.push(normal.x, normal.y, normal.z);
  26531. uvs.push(faceUV[index].z, faceUV[index].y);
  26532. if (faceColors) {
  26533. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26534. }
  26535. }
  26536. // sides
  26537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26538. // Result
  26539. var vertexData = new VertexData();
  26540. vertexData.indices = indices;
  26541. vertexData.positions = positions;
  26542. vertexData.normals = normals;
  26543. vertexData.uvs = uvs;
  26544. if (faceColors) {
  26545. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26546. vertexData.colors = totalColors;
  26547. }
  26548. return vertexData;
  26549. };
  26550. /**
  26551. * Creates the VertexData of the Sphere.
  26552. */
  26553. VertexData.CreateSphere = function (options) {
  26554. var segments = options.segments || 32;
  26555. var diameterX = options.diameterX || options.diameter || 1;
  26556. var diameterY = options.diameterY || options.diameter || 1;
  26557. var diameterZ = options.diameterZ || options.diameter || 1;
  26558. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26559. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26560. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26561. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26562. var totalZRotationSteps = 2 + segments;
  26563. var totalYRotationSteps = 2 * totalZRotationSteps;
  26564. var indices = [];
  26565. var positions = [];
  26566. var normals = [];
  26567. var uvs = [];
  26568. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26569. var normalizedZ = zRotationStep / totalZRotationSteps;
  26570. var angleZ = normalizedZ * Math.PI * slice;
  26571. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26572. var normalizedY = yRotationStep / totalYRotationSteps;
  26573. var angleY = normalizedY * Math.PI * 2 * arc;
  26574. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26575. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26576. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26577. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26578. var vertex = complete.multiply(radius);
  26579. var normal = complete.divide(radius).normalize();
  26580. positions.push(vertex.x, vertex.y, vertex.z);
  26581. normals.push(normal.x, normal.y, normal.z);
  26582. uvs.push(normalizedY, normalizedZ);
  26583. }
  26584. if (zRotationStep > 0) {
  26585. var verticesCount = positions.length / 3;
  26586. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26587. indices.push((firstIndex));
  26588. indices.push((firstIndex + 1));
  26589. indices.push(firstIndex + totalYRotationSteps + 1);
  26590. indices.push((firstIndex + totalYRotationSteps + 1));
  26591. indices.push((firstIndex + 1));
  26592. indices.push((firstIndex + totalYRotationSteps + 2));
  26593. }
  26594. }
  26595. }
  26596. // Sides
  26597. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26598. // Result
  26599. var vertexData = new VertexData();
  26600. vertexData.indices = indices;
  26601. vertexData.positions = positions;
  26602. vertexData.normals = normals;
  26603. vertexData.uvs = uvs;
  26604. return vertexData;
  26605. };
  26606. /**
  26607. * Creates the VertexData of the Cylinder or Cone.
  26608. */
  26609. VertexData.CreateCylinder = function (options) {
  26610. var height = options.height || 2;
  26611. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26612. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  26613. var tessellation = options.tessellation || 24;
  26614. var subdivisions = options.subdivisions || 1;
  26615. var hasRings = options.hasRings;
  26616. var enclose = options.enclose;
  26617. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26618. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26619. var faceUV = options.faceUV || new Array(3);
  26620. var faceColors = options.faceColors;
  26621. // default face colors and UV if undefined
  26622. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  26623. var ringNb = (hasRings) ? subdivisions : 1;
  26624. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  26625. var f;
  26626. for (f = 0; f < surfaceNb; f++) {
  26627. if (faceColors && faceColors[f] === undefined) {
  26628. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26629. }
  26630. }
  26631. for (f = 0; f < surfaceNb; f++) {
  26632. if (faceUV && faceUV[f] === undefined) {
  26633. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26634. }
  26635. }
  26636. var indices = [];
  26637. var positions = [];
  26638. var normals = [];
  26639. var uvs = [];
  26640. var colors = [];
  26641. var angle_step = Math.PI * 2 * arc / tessellation;
  26642. var angle;
  26643. var h;
  26644. var radius;
  26645. var tan = (diameterBottom - diameterTop) / 2 / height;
  26646. var ringVertex = BABYLON.Vector3.Zero();
  26647. var ringNormal = BABYLON.Vector3.Zero();
  26648. var ringFirstVertex = BABYLON.Vector3.Zero();
  26649. var ringFirstNormal = BABYLON.Vector3.Zero();
  26650. var quadNormal = BABYLON.Vector3.Zero();
  26651. var Y = BABYLON.Axis.Y;
  26652. // positions, normals, uvs
  26653. var i;
  26654. var j;
  26655. var r;
  26656. var ringIdx = 1;
  26657. var s = 1; // surface index
  26658. var cs = 0;
  26659. var v = 0;
  26660. for (i = 0; i <= subdivisions; i++) {
  26661. h = i / subdivisions;
  26662. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26663. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  26664. for (r = 0; r < ringIdx; r++) {
  26665. if (hasRings) {
  26666. s += r;
  26667. }
  26668. if (enclose) {
  26669. s += 2 * r;
  26670. }
  26671. for (j = 0; j <= tessellation; j++) {
  26672. angle = j * angle_step;
  26673. // position
  26674. ringVertex.x = Math.cos(-angle) * radius;
  26675. ringVertex.y = -height / 2 + h * height;
  26676. ringVertex.z = Math.sin(-angle) * radius;
  26677. // normal
  26678. if (diameterTop === 0 && i === subdivisions) {
  26679. // if no top cap, reuse former normals
  26680. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26681. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26682. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26683. }
  26684. else {
  26685. ringNormal.x = ringVertex.x;
  26686. ringNormal.z = ringVertex.z;
  26687. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26688. ringNormal.normalize();
  26689. }
  26690. // keep first ring vertex values for enclose
  26691. if (j === 0) {
  26692. ringFirstVertex.copyFrom(ringVertex);
  26693. ringFirstNormal.copyFrom(ringNormal);
  26694. }
  26695. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26696. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26697. if (hasRings) {
  26698. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  26699. }
  26700. else {
  26701. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  26702. }
  26703. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  26704. if (faceColors) {
  26705. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  26706. }
  26707. }
  26708. // if enclose, add four vertices and their dedicated normals
  26709. if (arc !== 1 && enclose) {
  26710. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26711. positions.push(0, ringVertex.y, 0);
  26712. positions.push(0, ringVertex.y, 0);
  26713. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  26714. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  26715. quadNormal.normalize();
  26716. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26717. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  26718. quadNormal.normalize();
  26719. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  26720. if (hasRings) {
  26721. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  26722. }
  26723. else {
  26724. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  26725. }
  26726. uvs.push(faceUV[s + 1].x, v);
  26727. uvs.push(faceUV[s + 1].z, v);
  26728. if (hasRings) {
  26729. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  26730. }
  26731. else {
  26732. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  26733. }
  26734. uvs.push(faceUV[s + 2].x, v);
  26735. uvs.push(faceUV[s + 2].z, v);
  26736. if (faceColors) {
  26737. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26738. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26739. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26740. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26741. }
  26742. }
  26743. if (cs !== s) {
  26744. cs = s;
  26745. }
  26746. }
  26747. }
  26748. // indices
  26749. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26750. var s;
  26751. i = 0;
  26752. for (s = 0; s < subdivisions; s++) {
  26753. for (j = 0; j < tessellation; j++) {
  26754. var i0 = i * (e + 1) + j;
  26755. var i1 = (i + 1) * (e + 1) + j;
  26756. var i2 = i * (e + 1) + (j + 1);
  26757. var i3 = (i + 1) * (e + 1) + (j + 1);
  26758. indices.push(i0, i1, i2);
  26759. indices.push(i3, i2, i1);
  26760. }
  26761. if (arc !== 1 && enclose) {
  26762. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26763. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26764. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26765. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26766. }
  26767. i = (hasRings) ? (i + 2) : (i + 1);
  26768. }
  26769. // Caps
  26770. var createCylinderCap = function (isTop) {
  26771. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26772. if (radius === 0) {
  26773. return;
  26774. }
  26775. // Cap positions, normals & uvs
  26776. var angle;
  26777. var circleVector;
  26778. var i;
  26779. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26780. var c;
  26781. if (faceColors) {
  26782. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26783. }
  26784. // cap center
  26785. var vbase = positions.length / 3;
  26786. var offset = isTop ? height / 2 : -height / 2;
  26787. var center = new BABYLON.Vector3(0, offset, 0);
  26788. positions.push(center.x, center.y, center.z);
  26789. normals.push(0, isTop ? 1 : -1, 0);
  26790. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26791. if (faceColors) {
  26792. colors.push(c.r, c.g, c.b, c.a);
  26793. }
  26794. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26795. for (i = 0; i <= tessellation; i++) {
  26796. angle = Math.PI * 2 * i * arc / tessellation;
  26797. var cos = Math.cos(-angle);
  26798. var sin = Math.sin(-angle);
  26799. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26800. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26801. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26802. normals.push(0, isTop ? 1 : -1, 0);
  26803. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26804. if (faceColors) {
  26805. colors.push(c.r, c.g, c.b, c.a);
  26806. }
  26807. }
  26808. // Cap indices
  26809. for (i = 0; i < tessellation; i++) {
  26810. if (!isTop) {
  26811. indices.push(vbase);
  26812. indices.push(vbase + (i + 1));
  26813. indices.push(vbase + (i + 2));
  26814. }
  26815. else {
  26816. indices.push(vbase);
  26817. indices.push(vbase + (i + 2));
  26818. indices.push(vbase + (i + 1));
  26819. }
  26820. }
  26821. };
  26822. // add caps to geometry
  26823. createCylinderCap(false);
  26824. createCylinderCap(true);
  26825. // Sides
  26826. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26827. var vertexData = new VertexData();
  26828. vertexData.indices = indices;
  26829. vertexData.positions = positions;
  26830. vertexData.normals = normals;
  26831. vertexData.uvs = uvs;
  26832. if (faceColors) {
  26833. vertexData.colors = colors;
  26834. }
  26835. return vertexData;
  26836. };
  26837. /**
  26838. * Creates the VertexData of the Torus.
  26839. */
  26840. VertexData.CreateTorus = function (options) {
  26841. var indices = [];
  26842. var positions = [];
  26843. var normals = [];
  26844. var uvs = [];
  26845. var diameter = options.diameter || 1;
  26846. var thickness = options.thickness || 0.5;
  26847. var tessellation = options.tessellation || 16;
  26848. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26849. var stride = tessellation + 1;
  26850. for (var i = 0; i <= tessellation; i++) {
  26851. var u = i / tessellation;
  26852. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26853. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26854. for (var j = 0; j <= tessellation; j++) {
  26855. var v = 1 - j / tessellation;
  26856. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26857. var dx = Math.cos(innerAngle);
  26858. var dy = Math.sin(innerAngle);
  26859. // Create a vertex.
  26860. var normal = new BABYLON.Vector3(dx, dy, 0);
  26861. var position = normal.scale(thickness / 2);
  26862. var textureCoordinate = new BABYLON.Vector2(u, v);
  26863. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26864. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26865. positions.push(position.x, position.y, position.z);
  26866. normals.push(normal.x, normal.y, normal.z);
  26867. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26868. // And create indices for two triangles.
  26869. var nextI = (i + 1) % stride;
  26870. var nextJ = (j + 1) % stride;
  26871. indices.push(i * stride + j);
  26872. indices.push(i * stride + nextJ);
  26873. indices.push(nextI * stride + j);
  26874. indices.push(i * stride + nextJ);
  26875. indices.push(nextI * stride + nextJ);
  26876. indices.push(nextI * stride + j);
  26877. }
  26878. }
  26879. // Sides
  26880. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26881. // Result
  26882. var vertexData = new VertexData();
  26883. vertexData.indices = indices;
  26884. vertexData.positions = positions;
  26885. vertexData.normals = normals;
  26886. vertexData.uvs = uvs;
  26887. return vertexData;
  26888. };
  26889. /**
  26890. * Creates the VertexData of the LineSystem.
  26891. */
  26892. VertexData.CreateLineSystem = function (options) {
  26893. var indices = [];
  26894. var positions = [];
  26895. var lines = options.lines;
  26896. var idx = 0;
  26897. for (var l = 0; l < lines.length; l++) {
  26898. var points = lines[l];
  26899. for (var index = 0; index < points.length; index++) {
  26900. positions.push(points[index].x, points[index].y, points[index].z);
  26901. if (index > 0) {
  26902. indices.push(idx - 1);
  26903. indices.push(idx);
  26904. }
  26905. idx++;
  26906. }
  26907. }
  26908. var vertexData = new VertexData();
  26909. vertexData.indices = indices;
  26910. vertexData.positions = positions;
  26911. return vertexData;
  26912. };
  26913. /**
  26914. * Create the VertexData of the DashedLines.
  26915. */
  26916. VertexData.CreateDashedLines = function (options) {
  26917. var dashSize = options.dashSize || 3;
  26918. var gapSize = options.gapSize || 1;
  26919. var dashNb = options.dashNb || 200;
  26920. var points = options.points;
  26921. var positions = new Array();
  26922. var indices = new Array();
  26923. var curvect = BABYLON.Vector3.Zero();
  26924. var lg = 0;
  26925. var nb = 0;
  26926. var shft = 0;
  26927. var dashshft = 0;
  26928. var curshft = 0;
  26929. var idx = 0;
  26930. var i = 0;
  26931. for (i = 0; i < points.length - 1; i++) {
  26932. points[i + 1].subtractToRef(points[i], curvect);
  26933. lg += curvect.length();
  26934. }
  26935. shft = lg / dashNb;
  26936. dashshft = dashSize * shft / (dashSize + gapSize);
  26937. for (i = 0; i < points.length - 1; i++) {
  26938. points[i + 1].subtractToRef(points[i], curvect);
  26939. nb = Math.floor(curvect.length() / shft);
  26940. curvect.normalize();
  26941. for (var j = 0; j < nb; j++) {
  26942. curshft = shft * j;
  26943. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26944. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26945. indices.push(idx, idx + 1);
  26946. idx += 2;
  26947. }
  26948. }
  26949. // Result
  26950. var vertexData = new VertexData();
  26951. vertexData.positions = positions;
  26952. vertexData.indices = indices;
  26953. return vertexData;
  26954. };
  26955. /**
  26956. * Creates the VertexData of the Ground.
  26957. */
  26958. VertexData.CreateGround = function (options) {
  26959. var indices = [];
  26960. var positions = [];
  26961. var normals = [];
  26962. var uvs = [];
  26963. var row, col;
  26964. var width = options.width || 1;
  26965. var height = options.height || 1;
  26966. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26967. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26968. for (row = 0; row <= subdivisionsY; row++) {
  26969. for (col = 0; col <= subdivisionsX; col++) {
  26970. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26971. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26972. positions.push(position.x, position.y, position.z);
  26973. normals.push(normal.x, normal.y, normal.z);
  26974. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26975. }
  26976. }
  26977. for (row = 0; row < subdivisionsY; row++) {
  26978. for (col = 0; col < subdivisionsX; col++) {
  26979. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26980. indices.push(col + 1 + row * (subdivisionsX + 1));
  26981. indices.push(col + row * (subdivisionsX + 1));
  26982. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26983. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26984. indices.push(col + row * (subdivisionsX + 1));
  26985. }
  26986. }
  26987. // Result
  26988. var vertexData = new VertexData();
  26989. vertexData.indices = indices;
  26990. vertexData.positions = positions;
  26991. vertexData.normals = normals;
  26992. vertexData.uvs = uvs;
  26993. return vertexData;
  26994. };
  26995. /**
  26996. * Creates the VertexData of the TiledGround.
  26997. */
  26998. VertexData.CreateTiledGround = function (options) {
  26999. var xmin = options.xmin || -1.0;
  27000. var zmin = options.zmin || -1.0;
  27001. var xmax = options.xmax || 1.0;
  27002. var zmax = options.zmax || 1.0;
  27003. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27004. var precision = options.precision || { w: 1, h: 1 };
  27005. var indices = [];
  27006. var positions = [];
  27007. var normals = [];
  27008. var uvs = [];
  27009. var row, col, tileRow, tileCol;
  27010. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27011. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27012. precision.w = (precision.w < 1) ? 1 : precision.w;
  27013. precision.h = (precision.h < 1) ? 1 : precision.h;
  27014. var tileSize = {
  27015. 'w': (xmax - xmin) / subdivisions.w,
  27016. 'h': (zmax - zmin) / subdivisions.h
  27017. };
  27018. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27019. // Indices
  27020. var base = positions.length / 3;
  27021. var rowLength = precision.w + 1;
  27022. for (row = 0; row < precision.h; row++) {
  27023. for (col = 0; col < precision.w; col++) {
  27024. var square = [
  27025. base + col + row * rowLength,
  27026. base + (col + 1) + row * rowLength,
  27027. base + (col + 1) + (row + 1) * rowLength,
  27028. base + col + (row + 1) * rowLength
  27029. ];
  27030. indices.push(square[1]);
  27031. indices.push(square[2]);
  27032. indices.push(square[3]);
  27033. indices.push(square[0]);
  27034. indices.push(square[1]);
  27035. indices.push(square[3]);
  27036. }
  27037. }
  27038. // Position, normals and uvs
  27039. var position = BABYLON.Vector3.Zero();
  27040. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27041. for (row = 0; row <= precision.h; row++) {
  27042. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27043. for (col = 0; col <= precision.w; col++) {
  27044. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27045. position.y = 0;
  27046. positions.push(position.x, position.y, position.z);
  27047. normals.push(normal.x, normal.y, normal.z);
  27048. uvs.push(col / precision.w, row / precision.h);
  27049. }
  27050. }
  27051. }
  27052. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27053. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27054. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27055. }
  27056. }
  27057. // Result
  27058. var vertexData = new VertexData();
  27059. vertexData.indices = indices;
  27060. vertexData.positions = positions;
  27061. vertexData.normals = normals;
  27062. vertexData.uvs = uvs;
  27063. return vertexData;
  27064. };
  27065. /**
  27066. * Creates the VertexData of the Ground designed from a heightmap.
  27067. */
  27068. VertexData.CreateGroundFromHeightMap = function (options) {
  27069. var indices = [];
  27070. var positions = [];
  27071. var normals = [];
  27072. var uvs = [];
  27073. var row, col;
  27074. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27075. // Vertices
  27076. for (row = 0; row <= options.subdivisions; row++) {
  27077. for (col = 0; col <= options.subdivisions; col++) {
  27078. 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));
  27079. // Compute height
  27080. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27081. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27082. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27083. var r = options.buffer[pos] / 255.0;
  27084. var g = options.buffer[pos + 1] / 255.0;
  27085. var b = options.buffer[pos + 2] / 255.0;
  27086. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27087. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27088. // Add vertex
  27089. positions.push(position.x, position.y, position.z);
  27090. normals.push(0, 0, 0);
  27091. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27092. }
  27093. }
  27094. // Indices
  27095. for (row = 0; row < options.subdivisions; row++) {
  27096. for (col = 0; col < options.subdivisions; col++) {
  27097. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27098. indices.push(col + 1 + row * (options.subdivisions + 1));
  27099. indices.push(col + row * (options.subdivisions + 1));
  27100. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27101. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27102. indices.push(col + row * (options.subdivisions + 1));
  27103. }
  27104. }
  27105. // Normals
  27106. VertexData.ComputeNormals(positions, indices, normals);
  27107. // Result
  27108. var vertexData = new VertexData();
  27109. vertexData.indices = indices;
  27110. vertexData.positions = positions;
  27111. vertexData.normals = normals;
  27112. vertexData.uvs = uvs;
  27113. return vertexData;
  27114. };
  27115. /**
  27116. * Creates the VertexData of the Plane.
  27117. */
  27118. VertexData.CreatePlane = function (options) {
  27119. var indices = [];
  27120. var positions = [];
  27121. var normals = [];
  27122. var uvs = [];
  27123. var width = options.width || options.size || 1;
  27124. var height = options.height || options.size || 1;
  27125. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27126. // Vertices
  27127. var halfWidth = width / 2.0;
  27128. var halfHeight = height / 2.0;
  27129. positions.push(-halfWidth, -halfHeight, 0);
  27130. normals.push(0, 0, -1.0);
  27131. uvs.push(0.0, 0.0);
  27132. positions.push(halfWidth, -halfHeight, 0);
  27133. normals.push(0, 0, -1.0);
  27134. uvs.push(1.0, 0.0);
  27135. positions.push(halfWidth, halfHeight, 0);
  27136. normals.push(0, 0, -1.0);
  27137. uvs.push(1.0, 1.0);
  27138. positions.push(-halfWidth, halfHeight, 0);
  27139. normals.push(0, 0, -1.0);
  27140. uvs.push(0.0, 1.0);
  27141. // Indices
  27142. indices.push(0);
  27143. indices.push(1);
  27144. indices.push(2);
  27145. indices.push(0);
  27146. indices.push(2);
  27147. indices.push(3);
  27148. // Sides
  27149. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27150. // Result
  27151. var vertexData = new VertexData();
  27152. vertexData.indices = indices;
  27153. vertexData.positions = positions;
  27154. vertexData.normals = normals;
  27155. vertexData.uvs = uvs;
  27156. return vertexData;
  27157. };
  27158. /**
  27159. * Creates the VertexData of the Disc or regular Polygon.
  27160. */
  27161. VertexData.CreateDisc = function (options) {
  27162. var positions = [];
  27163. var indices = [];
  27164. var normals = [];
  27165. var uvs = [];
  27166. var radius = options.radius || 0.5;
  27167. var tessellation = options.tessellation || 64;
  27168. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27169. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27170. // positions and uvs
  27171. positions.push(0, 0, 0); // disc center first
  27172. uvs.push(0.5, 0.5);
  27173. var theta = Math.PI * 2 * arc;
  27174. var step = theta / tessellation;
  27175. for (var a = 0; a < theta; a += step) {
  27176. var x = Math.cos(a);
  27177. var y = Math.sin(a);
  27178. var u = (x + 1) / 2;
  27179. var v = (1 - y) / 2;
  27180. positions.push(radius * x, radius * y, 0);
  27181. uvs.push(u, v);
  27182. }
  27183. if (arc === 1) {
  27184. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27185. uvs.push(uvs[2], uvs[3]);
  27186. }
  27187. //indices
  27188. var vertexNb = positions.length / 3;
  27189. for (var i = 1; i < vertexNb - 1; i++) {
  27190. indices.push(i + 1, 0, i);
  27191. }
  27192. // result
  27193. VertexData.ComputeNormals(positions, indices, normals);
  27194. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27195. var vertexData = new VertexData();
  27196. vertexData.indices = indices;
  27197. vertexData.positions = positions;
  27198. vertexData.normals = normals;
  27199. vertexData.uvs = uvs;
  27200. return vertexData;
  27201. };
  27202. /**
  27203. * Re-creates the VertexData of the Polygon for sideOrientation.
  27204. */
  27205. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27206. var faceUV = fUV || new Array(3);
  27207. var faceColors = fColors;
  27208. var colors = [];
  27209. // default face colors and UV if undefined
  27210. for (var f = 0; f < 3; f++) {
  27211. if (faceUV[f] === undefined) {
  27212. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27213. }
  27214. if (faceColors && faceColors[f] === undefined) {
  27215. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27216. }
  27217. }
  27218. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27219. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27220. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27221. var indices = polygon.getIndices();
  27222. // set face colours and textures
  27223. var idx = 0;
  27224. var face = 0;
  27225. for (var index = 0; index < normals.length; index += 3) {
  27226. //Edge Face no. 1
  27227. if (Math.abs(normals[index + 1]) < 0.001) {
  27228. face = 1;
  27229. }
  27230. //Top Face no. 0
  27231. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27232. face = 0;
  27233. }
  27234. //Bottom Face no. 2
  27235. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27236. face = 2;
  27237. }
  27238. idx = index / 3;
  27239. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27240. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27241. if (faceColors) {
  27242. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27243. }
  27244. }
  27245. // sides
  27246. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27247. // Result
  27248. var vertexData = new VertexData();
  27249. vertexData.indices = indices;
  27250. vertexData.positions = positions;
  27251. vertexData.normals = normals;
  27252. vertexData.uvs = uvs;
  27253. if (faceColors) {
  27254. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27255. vertexData.colors = totalColors;
  27256. }
  27257. return vertexData;
  27258. };
  27259. /**
  27260. * Creates the VertexData of the IcoSphere.
  27261. */
  27262. VertexData.CreateIcoSphere = function (options) {
  27263. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27264. var radius = options.radius || 1;
  27265. var flat = (options.flat === undefined) ? true : options.flat;
  27266. var subdivisions = options.subdivisions || 4;
  27267. var radiusX = options.radiusX || radius;
  27268. var radiusY = options.radiusY || radius;
  27269. var radiusZ = options.radiusZ || radius;
  27270. var t = (1 + Math.sqrt(5)) / 2;
  27271. // 12 vertex x,y,z
  27272. var ico_vertices = [
  27273. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27274. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27275. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27276. ];
  27277. // index of 3 vertex makes a face of icopshere
  27278. var ico_indices = [
  27279. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27280. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27281. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27282. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27283. ];
  27284. // vertex for uv have aliased position, not for UV
  27285. var vertices_unalias_id = [
  27286. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27287. // vertex alias
  27288. 0,
  27289. 2,
  27290. 3,
  27291. 3,
  27292. 3,
  27293. 4,
  27294. 7,
  27295. 8,
  27296. 9,
  27297. 9,
  27298. 10,
  27299. 11 // 23: B + 12
  27300. ];
  27301. // uv as integer step (not pixels !)
  27302. var ico_vertexuv = [
  27303. 5, 1, 3, 1, 6, 4, 0, 0,
  27304. 5, 3, 4, 2, 2, 2, 4, 0,
  27305. 2, 0, 1, 1, 6, 0, 6, 2,
  27306. // vertex alias (for same vertex on different faces)
  27307. 0, 4,
  27308. 3, 3,
  27309. 4, 4,
  27310. 3, 1,
  27311. 4, 2,
  27312. 4, 4,
  27313. 0, 2,
  27314. 1, 1,
  27315. 2, 2,
  27316. 3, 3,
  27317. 1, 3,
  27318. 2, 4 // 23: B + 12
  27319. ];
  27320. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27321. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27322. // First island of uv mapping
  27323. // v = 4h 3+ 2
  27324. // v = 3h 9+ 4
  27325. // v = 2h 9+ 5 B
  27326. // v = 1h 9 1 0
  27327. // v = 0h 3 8 7 A
  27328. // u = 0 1 2 3 4 5 6 *a
  27329. // Second island of uv mapping
  27330. // v = 4h 0+ B+ 4+
  27331. // v = 3h A+ 2+
  27332. // v = 2h 7+ 6 3+
  27333. // v = 1h 8+ 3+
  27334. // v = 0h
  27335. // u = 0 1 2 3 4 5 6 *a
  27336. // Face layout on texture UV mapping
  27337. // ============
  27338. // \ 4 /\ 16 / ======
  27339. // \ / \ / /\ 11 /
  27340. // \/ 7 \/ / \ /
  27341. // ======= / 10 \/
  27342. // /\ 17 /\ =======
  27343. // / \ / \ \ 15 /\
  27344. // / 8 \/ 12 \ \ / \
  27345. // ============ \/ 6 \
  27346. // \ 18 /\ ============
  27347. // \ / \ \ 5 /\ 0 /
  27348. // \/ 13 \ \ / \ /
  27349. // ======= \/ 1 \/
  27350. // =============
  27351. // /\ 19 /\ 2 /\
  27352. // / \ / \ / \
  27353. // / 14 \/ 9 \/ 3 \
  27354. // ===================
  27355. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27356. var ustep = 138 / 1024;
  27357. var vstep = 239 / 1024;
  27358. var uoffset = 60 / 1024;
  27359. var voffset = 26 / 1024;
  27360. // Second island should have margin, not to touch the first island
  27361. // avoid any borderline artefact in pixel rounding
  27362. var island_u_offset = -40 / 1024;
  27363. var island_v_offset = +20 / 1024;
  27364. // face is either island 0 or 1 :
  27365. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27366. var island = [
  27367. 0, 0, 0, 0, 1,
  27368. 0, 0, 1, 1, 0,
  27369. 0, 0, 1, 1, 0,
  27370. 0, 1, 1, 1, 0 // 15 - 19
  27371. ];
  27372. var indices = [];
  27373. var positions = [];
  27374. var normals = [];
  27375. var uvs = [];
  27376. var current_indice = 0;
  27377. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27378. var face_vertex_pos = new Array(3);
  27379. var face_vertex_uv = new Array(3);
  27380. var v012;
  27381. for (v012 = 0; v012 < 3; v012++) {
  27382. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27383. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27384. }
  27385. // create all with normals
  27386. for (var face = 0; face < 20; face++) {
  27387. // 3 vertex per face
  27388. for (v012 = 0; v012 < 3; v012++) {
  27389. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27390. var v_id = ico_indices[3 * face + v012];
  27391. // vertex have 3D position (x,y,z)
  27392. 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]);
  27393. // Normalize to get normal, then scale to radius
  27394. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27395. // uv Coordinates from vertex ID
  27396. 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);
  27397. }
  27398. // Subdivide the face (interpolate pos, norm, uv)
  27399. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27400. // - norm is linear interpolation of vertex corner normal
  27401. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27402. // - uv is linear interpolation
  27403. //
  27404. // Topology is as below for sub-divide by 2
  27405. // vertex shown as v0,v1,v2
  27406. // interp index is i1 to progress in range [v0,v1[
  27407. // interp index is i2 to progress in range [v0,v2[
  27408. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27409. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27410. //
  27411. //
  27412. // i2 v2
  27413. // ^ ^
  27414. // / / \
  27415. // / / \
  27416. // / / \
  27417. // / / (0,1) \
  27418. // / #---------\
  27419. // / / \ (0,0)'/ \
  27420. // / / \ / \
  27421. // / / \ / \
  27422. // / / (0,0) \ / (1,0) \
  27423. // / #---------#---------\
  27424. // v0 v1
  27425. //
  27426. // --------------------> i1
  27427. //
  27428. // interp of (i1,i2):
  27429. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27430. // along i1 : lerp(x0,x1, i1/(S-i2))
  27431. //
  27432. // centroid of triangle is needed to get help normal computation
  27433. // (c1,c2) are used for centroid location
  27434. var interp_vertex = function (i1, i2, c1, c2) {
  27435. // vertex is interpolated from
  27436. // - face_vertex_pos[0..2]
  27437. // - face_vertex_uv[0..2]
  27438. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27439. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27440. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27441. pos_interp.normalize();
  27442. var vertex_normal;
  27443. if (flat) {
  27444. // in flat mode, recalculate normal as face centroid normal
  27445. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27446. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27447. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27448. }
  27449. else {
  27450. // in smooth mode, recalculate normal from each single vertex position
  27451. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27452. }
  27453. // Vertex normal need correction due to X,Y,Z radius scaling
  27454. vertex_normal.x /= radiusX;
  27455. vertex_normal.y /= radiusY;
  27456. vertex_normal.z /= radiusZ;
  27457. vertex_normal.normalize();
  27458. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27459. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27460. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27461. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27462. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27463. uvs.push(uv_interp.x, uv_interp.y);
  27464. // push each vertex has member of a face
  27465. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27466. indices.push(current_indice);
  27467. current_indice++;
  27468. };
  27469. for (var i2 = 0; i2 < subdivisions; i2++) {
  27470. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27471. // face : (i1,i2) for /\ :
  27472. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27473. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27474. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27475. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27476. if (i1 + i2 + 1 < subdivisions) {
  27477. // face : (i1,i2)' for \/ :
  27478. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27479. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27480. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27481. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27482. }
  27483. }
  27484. }
  27485. }
  27486. // Sides
  27487. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27488. // Result
  27489. var vertexData = new VertexData();
  27490. vertexData.indices = indices;
  27491. vertexData.positions = positions;
  27492. vertexData.normals = normals;
  27493. vertexData.uvs = uvs;
  27494. return vertexData;
  27495. };
  27496. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27497. /**
  27498. * Creates the VertexData of the Polyhedron.
  27499. */
  27500. VertexData.CreatePolyhedron = function (options) {
  27501. // provided polyhedron types :
  27502. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27503. // 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)
  27504. var polyhedra = [];
  27505. 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]] };
  27506. 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]] };
  27507. polyhedra[2] = {
  27508. 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]],
  27509. 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]]
  27510. };
  27511. polyhedra[3] = {
  27512. 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]],
  27513. 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]]
  27514. };
  27515. polyhedra[4] = {
  27516. 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]],
  27517. 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]]
  27518. };
  27519. 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]] };
  27520. 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]] };
  27521. 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]] };
  27522. 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]] };
  27523. 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]] };
  27524. 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]] };
  27525. 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]] };
  27526. 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]] };
  27527. 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]] };
  27528. polyhedra[14] = {
  27529. 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]],
  27530. 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]]
  27531. };
  27532. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27533. var size = options.size;
  27534. var sizeX = options.sizeX || size || 1;
  27535. var sizeY = options.sizeY || size || 1;
  27536. var sizeZ = options.sizeZ || size || 1;
  27537. var data = options.custom || polyhedra[type];
  27538. var nbfaces = data.face.length;
  27539. var faceUV = options.faceUV || new Array(nbfaces);
  27540. var faceColors = options.faceColors;
  27541. var flat = (options.flat === undefined) ? true : options.flat;
  27542. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27543. var positions = [];
  27544. var indices = [];
  27545. var normals = [];
  27546. var uvs = [];
  27547. var colors = [];
  27548. var index = 0;
  27549. var faceIdx = 0; // face cursor in the array "indexes"
  27550. var indexes = [];
  27551. var i = 0;
  27552. var f = 0;
  27553. var u, v, ang, x, y, tmp;
  27554. // default face colors and UV if undefined
  27555. if (flat) {
  27556. for (f = 0; f < nbfaces; f++) {
  27557. if (faceColors && faceColors[f] === undefined) {
  27558. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27559. }
  27560. if (faceUV && faceUV[f] === undefined) {
  27561. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27562. }
  27563. }
  27564. }
  27565. if (!flat) {
  27566. for (i = 0; i < data.vertex.length; i++) {
  27567. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27568. uvs.push(0, 0);
  27569. }
  27570. for (f = 0; f < nbfaces; f++) {
  27571. for (i = 0; i < data.face[f].length - 2; i++) {
  27572. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27573. }
  27574. }
  27575. }
  27576. else {
  27577. for (f = 0; f < nbfaces; f++) {
  27578. var fl = data.face[f].length; // number of vertices of the current face
  27579. ang = 2 * Math.PI / fl;
  27580. x = 0.5 * Math.tan(ang / 2);
  27581. y = 0.5;
  27582. // positions, uvs, colors
  27583. for (i = 0; i < fl; i++) {
  27584. // positions
  27585. 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);
  27586. indexes.push(index);
  27587. index++;
  27588. // uvs
  27589. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27590. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27591. uvs.push(u, v);
  27592. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27593. y = x * Math.sin(ang) + y * Math.cos(ang);
  27594. x = tmp;
  27595. // colors
  27596. if (faceColors) {
  27597. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27598. }
  27599. }
  27600. // indices from indexes
  27601. for (i = 0; i < fl - 2; i++) {
  27602. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27603. }
  27604. faceIdx += fl;
  27605. }
  27606. }
  27607. VertexData.ComputeNormals(positions, indices, normals);
  27608. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27609. var vertexData = new VertexData();
  27610. vertexData.positions = positions;
  27611. vertexData.indices = indices;
  27612. vertexData.normals = normals;
  27613. vertexData.uvs = uvs;
  27614. if (faceColors && flat) {
  27615. vertexData.colors = colors;
  27616. }
  27617. return vertexData;
  27618. };
  27619. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27620. /**
  27621. * Creates the VertexData of the Torus Knot.
  27622. */
  27623. VertexData.CreateTorusKnot = function (options) {
  27624. var indices = [];
  27625. var positions = [];
  27626. var normals = [];
  27627. var uvs = [];
  27628. var radius = options.radius || 2;
  27629. var tube = options.tube || 0.5;
  27630. var radialSegments = options.radialSegments || 32;
  27631. var tubularSegments = options.tubularSegments || 32;
  27632. var p = options.p || 2;
  27633. var q = options.q || 3;
  27634. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27635. // Helper
  27636. var getPos = function (angle) {
  27637. var cu = Math.cos(angle);
  27638. var su = Math.sin(angle);
  27639. var quOverP = q / p * angle;
  27640. var cs = Math.cos(quOverP);
  27641. var tx = radius * (2 + cs) * 0.5 * cu;
  27642. var ty = radius * (2 + cs) * su * 0.5;
  27643. var tz = radius * Math.sin(quOverP) * 0.5;
  27644. return new BABYLON.Vector3(tx, ty, tz);
  27645. };
  27646. // Vertices
  27647. var i;
  27648. var j;
  27649. for (i = 0; i <= radialSegments; i++) {
  27650. var modI = i % radialSegments;
  27651. var u = modI / radialSegments * 2 * p * Math.PI;
  27652. var p1 = getPos(u);
  27653. var p2 = getPos(u + 0.01);
  27654. var tang = p2.subtract(p1);
  27655. var n = p2.add(p1);
  27656. var bitan = BABYLON.Vector3.Cross(tang, n);
  27657. n = BABYLON.Vector3.Cross(bitan, tang);
  27658. bitan.normalize();
  27659. n.normalize();
  27660. for (j = 0; j < tubularSegments; j++) {
  27661. var modJ = j % tubularSegments;
  27662. var v = modJ / tubularSegments * 2 * Math.PI;
  27663. var cx = -tube * Math.cos(v);
  27664. var cy = tube * Math.sin(v);
  27665. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27666. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27667. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27668. uvs.push(i / radialSegments);
  27669. uvs.push(j / tubularSegments);
  27670. }
  27671. }
  27672. for (i = 0; i < radialSegments; i++) {
  27673. for (j = 0; j < tubularSegments; j++) {
  27674. var jNext = (j + 1) % tubularSegments;
  27675. var a = i * tubularSegments + j;
  27676. var b = (i + 1) * tubularSegments + j;
  27677. var c = (i + 1) * tubularSegments + jNext;
  27678. var d = i * tubularSegments + jNext;
  27679. indices.push(d);
  27680. indices.push(b);
  27681. indices.push(a);
  27682. indices.push(d);
  27683. indices.push(c);
  27684. indices.push(b);
  27685. }
  27686. }
  27687. // Normals
  27688. VertexData.ComputeNormals(positions, indices, normals);
  27689. // Sides
  27690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27691. // Result
  27692. var vertexData = new VertexData();
  27693. vertexData.indices = indices;
  27694. vertexData.positions = positions;
  27695. vertexData.normals = normals;
  27696. vertexData.uvs = uvs;
  27697. return vertexData;
  27698. };
  27699. // Tools
  27700. /**
  27701. * @param {any} - positions (number[] or Float32Array)
  27702. * @param {any} - indices (number[] or Uint16Array)
  27703. * @param {any} - normals (number[] or Float32Array)
  27704. * options (optional) :
  27705. * facetPositions : optional array of facet positions (vector3)
  27706. * facetNormals : optional array of facet normals (vector3)
  27707. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  27708. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  27709. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  27710. * bbSize : optional bounding box size data, required for facetPartitioning computation
  27711. * bInfo : optional bounding info, required for facetPartitioning computation
  27712. */
  27713. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  27714. // temporary scalar variables
  27715. var index = 0; // facet index
  27716. var p1p2x = 0.0; // p1p2 vector x coordinate
  27717. var p1p2y = 0.0; // p1p2 vector y coordinate
  27718. var p1p2z = 0.0; // p1p2 vector z coordinate
  27719. var p3p2x = 0.0; // p3p2 vector x coordinate
  27720. var p3p2y = 0.0; // p3p2 vector y coordinate
  27721. var p3p2z = 0.0; // p3p2 vector z coordinate
  27722. var faceNormalx = 0.0; // facet normal x coordinate
  27723. var faceNormaly = 0.0; // facet normal y coordinate
  27724. var faceNormalz = 0.0; // facet normal z coordinate
  27725. var length = 0.0; // facet normal length before normalization
  27726. var v1x = 0; // vector1 x index in the positions array
  27727. var v1y = 0; // vector1 y index in the positions array
  27728. var v1z = 0; // vector1 z index in the positions array
  27729. var v2x = 0; // vector2 x index in the positions array
  27730. var v2y = 0; // vector2 y index in the positions array
  27731. var v2z = 0; // vector2 z index in the positions array
  27732. var v3x = 0; // vector3 x index in the positions array
  27733. var v3y = 0; // vector3 y index in the positions array
  27734. var v3z = 0; // vector3 z index in the positions array
  27735. var computeFacetNormals = false;
  27736. var computeFacetPositions = false;
  27737. var computeFacetPartitioning = false;
  27738. var faceNormalSign = 1;
  27739. if (options) {
  27740. computeFacetNormals = (options.facetNormals) ? true : false;
  27741. computeFacetPositions = (options.facetPositions) ? true : false;
  27742. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  27743. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  27744. }
  27745. // facetPartitioning reinit if needed
  27746. if (computeFacetPartitioning) {
  27747. var ox = 0; // X partitioning index for facet position
  27748. var oy = 0; // Y partinioning index for facet position
  27749. var oz = 0; // Z partinioning index for facet position
  27750. var b1x = 0; // X partitioning index for facet v1 vertex
  27751. var b1y = 0; // Y partitioning index for facet v1 vertex
  27752. var b1z = 0; // z partitioning index for facet v1 vertex
  27753. var b2x = 0; // X partitioning index for facet v2 vertex
  27754. var b2y = 0; // Y partitioning index for facet v2 vertex
  27755. var b2z = 0; // Z partitioning index for facet v2 vertex
  27756. var b3x = 0; // X partitioning index for facet v3 vertex
  27757. var b3y = 0; // Y partitioning index for facet v3 vertex
  27758. var b3z = 0; // Z partitioning index for facet v3 vertex
  27759. var block_idx_o = 0; // facet barycenter block index
  27760. var block_idx_v1 = 0; // v1 vertex block index
  27761. var block_idx_v2 = 0; // v2 vertex block index
  27762. var block_idx_v3 = 0; // v3 vertex block index
  27763. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  27764. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  27765. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  27766. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  27767. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  27768. var subSq = options.subDiv.max * options.subDiv.max;
  27769. options.facetPartitioning.length = 0;
  27770. }
  27771. // reset the normals
  27772. for (index = 0; index < positions.length; index++) {
  27773. normals[index] = 0.0;
  27774. }
  27775. // Loop : 1 indice triplet = 1 facet
  27776. var nbFaces = indices.length / 3;
  27777. for (index = 0; index < nbFaces; index++) {
  27778. // get the indexes of the coordinates of each vertex of the facet
  27779. v1x = indices[index * 3] * 3;
  27780. v1y = v1x + 1;
  27781. v1z = v1x + 2;
  27782. v2x = indices[index * 3 + 1] * 3;
  27783. v2y = v2x + 1;
  27784. v2z = v2x + 2;
  27785. v3x = indices[index * 3 + 2] * 3;
  27786. v3y = v3x + 1;
  27787. v3z = v3x + 2;
  27788. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  27789. p1p2y = positions[v1y] - positions[v2y];
  27790. p1p2z = positions[v1z] - positions[v2z];
  27791. p3p2x = positions[v3x] - positions[v2x];
  27792. p3p2y = positions[v3y] - positions[v2y];
  27793. p3p2z = positions[v3z] - positions[v2z];
  27794. // compute the face normal with the cross product
  27795. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  27796. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  27797. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  27798. // normalize this normal and store it in the array facetData
  27799. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27800. length = (length === 0) ? 1.0 : length;
  27801. faceNormalx /= length;
  27802. faceNormaly /= length;
  27803. faceNormalz /= length;
  27804. if (computeFacetNormals) {
  27805. options.facetNormals[index].x = faceNormalx;
  27806. options.facetNormals[index].y = faceNormaly;
  27807. options.facetNormals[index].z = faceNormalz;
  27808. }
  27809. if (computeFacetPositions) {
  27810. // compute and the facet barycenter coordinates in the array facetPositions
  27811. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  27812. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  27813. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  27814. }
  27815. if (computeFacetPartitioning) {
  27816. // store the facet indexes in arrays in the main facetPartitioning array :
  27817. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  27818. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27819. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27820. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27821. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27822. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27823. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27824. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27825. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27826. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27827. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27828. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27829. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27830. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  27831. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  27832. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  27833. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  27834. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  27835. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  27836. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  27837. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  27838. // push each facet index in each block containing the vertex
  27839. options.facetPartitioning[block_idx_v1].push(index);
  27840. if (block_idx_v2 != block_idx_v1) {
  27841. options.facetPartitioning[block_idx_v2].push(index);
  27842. }
  27843. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  27844. options.facetPartitioning[block_idx_v3].push(index);
  27845. }
  27846. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  27847. options.facetPartitioning[block_idx_o].push(index);
  27848. }
  27849. }
  27850. // compute the normals anyway
  27851. normals[v1x] += faceNormalx; // accumulate all the normals per face
  27852. normals[v1y] += faceNormaly;
  27853. normals[v1z] += faceNormalz;
  27854. normals[v2x] += faceNormalx;
  27855. normals[v2y] += faceNormaly;
  27856. normals[v2z] += faceNormalz;
  27857. normals[v3x] += faceNormalx;
  27858. normals[v3y] += faceNormaly;
  27859. normals[v3z] += faceNormalz;
  27860. }
  27861. // last normalization of each normal
  27862. for (index = 0; index < normals.length / 3; index++) {
  27863. faceNormalx = normals[index * 3];
  27864. faceNormaly = normals[index * 3 + 1];
  27865. faceNormalz = normals[index * 3 + 2];
  27866. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27867. length = (length === 0) ? 1.0 : length;
  27868. faceNormalx /= length;
  27869. faceNormaly /= length;
  27870. faceNormalz /= length;
  27871. normals[index * 3] = faceNormalx;
  27872. normals[index * 3 + 1] = faceNormaly;
  27873. normals[index * 3 + 2] = faceNormalz;
  27874. }
  27875. };
  27876. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  27877. var li = indices.length;
  27878. var ln = normals.length;
  27879. var i;
  27880. var n;
  27881. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27882. switch (sideOrientation) {
  27883. case BABYLON.Mesh.FRONTSIDE:
  27884. // nothing changed
  27885. break;
  27886. case BABYLON.Mesh.BACKSIDE:
  27887. var tmp;
  27888. // indices
  27889. for (i = 0; i < li; i += 3) {
  27890. tmp = indices[i];
  27891. indices[i] = indices[i + 2];
  27892. indices[i + 2] = tmp;
  27893. }
  27894. // normals
  27895. for (n = 0; n < ln; n++) {
  27896. normals[n] = -normals[n];
  27897. }
  27898. break;
  27899. case BABYLON.Mesh.DOUBLESIDE:
  27900. // positions
  27901. var lp = positions.length;
  27902. var l = lp / 3;
  27903. for (var p = 0; p < lp; p++) {
  27904. positions[lp + p] = positions[p];
  27905. }
  27906. // indices
  27907. for (i = 0; i < li; i += 3) {
  27908. indices[i + li] = indices[i + 2] + l;
  27909. indices[i + 1 + li] = indices[i + 1] + l;
  27910. indices[i + 2 + li] = indices[i] + l;
  27911. }
  27912. // normals
  27913. for (n = 0; n < ln; n++) {
  27914. normals[ln + n] = -normals[n];
  27915. }
  27916. // uvs
  27917. var lu = uvs.length;
  27918. var u = 0;
  27919. for (u = 0; u < lu; u++) {
  27920. uvs[u + lu] = uvs[u];
  27921. }
  27922. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27923. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27924. u = 0;
  27925. for (i = 0; i < lu / 2; i++) {
  27926. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27927. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27928. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27929. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27930. u += 2;
  27931. }
  27932. break;
  27933. }
  27934. };
  27935. /**
  27936. * Creates a new VertexData from the imported parameters.
  27937. */
  27938. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27939. var vertexData = new VertexData();
  27940. // positions
  27941. var positions = parsedVertexData.positions;
  27942. if (positions) {
  27943. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27944. }
  27945. // normals
  27946. var normals = parsedVertexData.normals;
  27947. if (normals) {
  27948. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27949. }
  27950. // tangents
  27951. var tangents = parsedVertexData.tangents;
  27952. if (tangents) {
  27953. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27954. }
  27955. // uvs
  27956. var uvs = parsedVertexData.uvs;
  27957. if (uvs) {
  27958. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27959. }
  27960. // uv2s
  27961. var uv2s = parsedVertexData.uv2s;
  27962. if (uv2s) {
  27963. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27964. }
  27965. // uv3s
  27966. var uv3s = parsedVertexData.uv3s;
  27967. if (uv3s) {
  27968. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27969. }
  27970. // uv4s
  27971. var uv4s = parsedVertexData.uv4s;
  27972. if (uv4s) {
  27973. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27974. }
  27975. // uv5s
  27976. var uv5s = parsedVertexData.uv5s;
  27977. if (uv5s) {
  27978. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27979. }
  27980. // uv6s
  27981. var uv6s = parsedVertexData.uv6s;
  27982. if (uv6s) {
  27983. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27984. }
  27985. // colors
  27986. var colors = parsedVertexData.colors;
  27987. if (colors) {
  27988. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27989. }
  27990. // matricesIndices
  27991. var matricesIndices = parsedVertexData.matricesIndices;
  27992. if (matricesIndices) {
  27993. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27994. }
  27995. // matricesWeights
  27996. var matricesWeights = parsedVertexData.matricesWeights;
  27997. if (matricesWeights) {
  27998. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27999. }
  28000. // indices
  28001. var indices = parsedVertexData.indices;
  28002. if (indices) {
  28003. vertexData.indices = indices;
  28004. }
  28005. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28006. };
  28007. return VertexData;
  28008. }());
  28009. BABYLON.VertexData = VertexData;
  28010. })(BABYLON || (BABYLON = {}));
  28011. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28012. var BABYLON;
  28013. (function (BABYLON) {
  28014. var Geometry = (function () {
  28015. function Geometry(id, scene, vertexData, updatable, mesh) {
  28016. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28017. this._totalVertices = 0;
  28018. this._isDisposed = false;
  28019. this.id = id;
  28020. this._engine = scene.getEngine();
  28021. this._meshes = [];
  28022. this._scene = scene;
  28023. //Init vertex buffer cache
  28024. this._vertexBuffers = {};
  28025. this._indices = [];
  28026. this._updatable = updatable;
  28027. // vertexData
  28028. if (vertexData) {
  28029. this.setAllVerticesData(vertexData, updatable);
  28030. }
  28031. else {
  28032. this._totalVertices = 0;
  28033. this._indices = [];
  28034. }
  28035. if (this._engine.getCaps().vertexArrayObject) {
  28036. this._vertexArrayObjects = {};
  28037. }
  28038. // applyToMesh
  28039. if (mesh) {
  28040. if (mesh.getClassName() === "LinesMesh") {
  28041. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28042. this.updateExtend();
  28043. }
  28044. this.applyToMesh(mesh);
  28045. mesh.computeWorldMatrix(true);
  28046. }
  28047. }
  28048. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28049. /**
  28050. * 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
  28051. * @returns The Bias Vector
  28052. */
  28053. get: function () {
  28054. return this._boundingBias;
  28055. },
  28056. set: function (value) {
  28057. if (this._boundingBias && this._boundingBias.equals(value)) {
  28058. return;
  28059. }
  28060. this._boundingBias = value.clone();
  28061. this.updateBoundingInfo(true, null);
  28062. },
  28063. enumerable: true,
  28064. configurable: true
  28065. });
  28066. Object.defineProperty(Geometry.prototype, "extend", {
  28067. get: function () {
  28068. return this._extend;
  28069. },
  28070. enumerable: true,
  28071. configurable: true
  28072. });
  28073. Geometry.prototype.getScene = function () {
  28074. return this._scene;
  28075. };
  28076. Geometry.prototype.getEngine = function () {
  28077. return this._engine;
  28078. };
  28079. Geometry.prototype.isReady = function () {
  28080. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28081. };
  28082. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28083. get: function () {
  28084. for (var index = 0; index < this._meshes.length; index++) {
  28085. if (!this._meshes[index].doNotSerialize) {
  28086. return false;
  28087. }
  28088. }
  28089. return true;
  28090. },
  28091. enumerable: true,
  28092. configurable: true
  28093. });
  28094. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28095. vertexData.applyToGeometry(this, updatable);
  28096. this.notifyUpdate();
  28097. };
  28098. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28099. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28100. this.setVerticesBuffer(buffer);
  28101. };
  28102. Geometry.prototype.removeVerticesData = function (kind) {
  28103. if (this._vertexBuffers[kind]) {
  28104. this._vertexBuffers[kind].dispose();
  28105. delete this._vertexBuffers[kind];
  28106. }
  28107. };
  28108. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28109. var kind = buffer.getKind();
  28110. if (this._vertexBuffers[kind]) {
  28111. this._vertexBuffers[kind].dispose();
  28112. }
  28113. this._vertexBuffers[kind] = buffer;
  28114. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28115. var data = buffer.getData();
  28116. var stride = buffer.getStrideSize();
  28117. this._totalVertices = data.length / stride;
  28118. this.updateExtend(data, stride);
  28119. this._resetPointsArrayCache();
  28120. var meshes = this._meshes;
  28121. var numOfMeshes = meshes.length;
  28122. for (var index = 0; index < numOfMeshes; index++) {
  28123. var mesh = meshes[index];
  28124. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28125. mesh._createGlobalSubMesh(false);
  28126. mesh.computeWorldMatrix(true);
  28127. }
  28128. }
  28129. this.notifyUpdate(kind);
  28130. if (this._vertexArrayObjects) {
  28131. this._disposeVertexArrayObjects();
  28132. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28133. }
  28134. };
  28135. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28136. var vertexBuffer = this.getVertexBuffer(kind);
  28137. if (!vertexBuffer) {
  28138. return;
  28139. }
  28140. vertexBuffer.updateDirectly(data, offset);
  28141. this.notifyUpdate(kind);
  28142. };
  28143. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28144. var vertexBuffer = this.getVertexBuffer(kind);
  28145. if (!vertexBuffer) {
  28146. return;
  28147. }
  28148. vertexBuffer.update(data);
  28149. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28150. var stride = vertexBuffer.getStrideSize();
  28151. this._totalVertices = data.length / stride;
  28152. this.updateBoundingInfo(updateExtends, data);
  28153. }
  28154. this.notifyUpdate(kind);
  28155. };
  28156. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28157. if (updateExtends) {
  28158. this.updateExtend(data);
  28159. }
  28160. var meshes = this._meshes;
  28161. var numOfMeshes = meshes.length;
  28162. this._resetPointsArrayCache();
  28163. for (var index = 0; index < numOfMeshes; index++) {
  28164. var mesh = meshes[index];
  28165. if (updateExtends) {
  28166. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28167. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28168. var subMesh = mesh.subMeshes[subIndex];
  28169. subMesh.refreshBoundingInfo();
  28170. }
  28171. }
  28172. }
  28173. };
  28174. Geometry.prototype._bind = function (effect, indexToBind) {
  28175. if (indexToBind === void 0) { indexToBind = undefined; }
  28176. if (indexToBind === undefined) {
  28177. indexToBind = this._indexBuffer;
  28178. }
  28179. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28180. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28181. return;
  28182. }
  28183. // Using VAO
  28184. if (!this._vertexArrayObjects[effect.key]) {
  28185. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28186. }
  28187. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28188. };
  28189. Geometry.prototype.getTotalVertices = function () {
  28190. if (!this.isReady()) {
  28191. return 0;
  28192. }
  28193. return this._totalVertices;
  28194. };
  28195. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28196. var vertexBuffer = this.getVertexBuffer(kind);
  28197. if (!vertexBuffer) {
  28198. return null;
  28199. }
  28200. var orig = vertexBuffer.getData();
  28201. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28202. return orig;
  28203. }
  28204. else {
  28205. var len = orig.length;
  28206. var copy = [];
  28207. for (var i = 0; i < len; i++) {
  28208. copy.push(orig[i]);
  28209. }
  28210. return copy;
  28211. }
  28212. };
  28213. Geometry.prototype.getVertexBuffer = function (kind) {
  28214. if (!this.isReady()) {
  28215. return null;
  28216. }
  28217. return this._vertexBuffers[kind];
  28218. };
  28219. Geometry.prototype.getVertexBuffers = function () {
  28220. if (!this.isReady()) {
  28221. return null;
  28222. }
  28223. return this._vertexBuffers;
  28224. };
  28225. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28226. if (!this._vertexBuffers) {
  28227. if (this._delayInfo) {
  28228. return this._delayInfo.indexOf(kind) !== -1;
  28229. }
  28230. return false;
  28231. }
  28232. return this._vertexBuffers[kind] !== undefined;
  28233. };
  28234. Geometry.prototype.getVerticesDataKinds = function () {
  28235. var result = [];
  28236. var kind;
  28237. if (!this._vertexBuffers && this._delayInfo) {
  28238. for (kind in this._delayInfo) {
  28239. result.push(kind);
  28240. }
  28241. }
  28242. else {
  28243. for (kind in this._vertexBuffers) {
  28244. result.push(kind);
  28245. }
  28246. }
  28247. return result;
  28248. };
  28249. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28250. if (this._indexBuffer) {
  28251. this._engine._releaseBuffer(this._indexBuffer);
  28252. }
  28253. this._disposeVertexArrayObjects();
  28254. this._indices = indices;
  28255. if (this._meshes.length !== 0 && this._indices) {
  28256. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28257. }
  28258. if (totalVertices !== undefined) {
  28259. this._totalVertices = totalVertices;
  28260. }
  28261. var meshes = this._meshes;
  28262. var numOfMeshes = meshes.length;
  28263. for (var index = 0; index < numOfMeshes; index++) {
  28264. meshes[index]._createGlobalSubMesh(true);
  28265. }
  28266. this.notifyUpdate();
  28267. };
  28268. Geometry.prototype.getTotalIndices = function () {
  28269. if (!this.isReady()) {
  28270. return 0;
  28271. }
  28272. return this._indices.length;
  28273. };
  28274. Geometry.prototype.getIndices = function (copyWhenShared) {
  28275. if (!this.isReady()) {
  28276. return null;
  28277. }
  28278. var orig = this._indices;
  28279. if (!copyWhenShared || this._meshes.length === 1) {
  28280. return orig;
  28281. }
  28282. else {
  28283. var len = orig.length;
  28284. var copy = [];
  28285. for (var i = 0; i < len; i++) {
  28286. copy.push(orig[i]);
  28287. }
  28288. return copy;
  28289. }
  28290. };
  28291. Geometry.prototype.getIndexBuffer = function () {
  28292. if (!this.isReady()) {
  28293. return null;
  28294. }
  28295. return this._indexBuffer;
  28296. };
  28297. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28298. if (!effect || !this._vertexArrayObjects) {
  28299. return;
  28300. }
  28301. if (this._vertexArrayObjects[effect.key]) {
  28302. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28303. delete this._vertexArrayObjects[effect.key];
  28304. }
  28305. };
  28306. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28307. var meshes = this._meshes;
  28308. var index = meshes.indexOf(mesh);
  28309. if (index === -1) {
  28310. return;
  28311. }
  28312. meshes.splice(index, 1);
  28313. mesh._geometry = null;
  28314. if (meshes.length === 0 && shouldDispose) {
  28315. this.dispose();
  28316. }
  28317. };
  28318. Geometry.prototype.applyToMesh = function (mesh) {
  28319. if (mesh._geometry === this) {
  28320. return;
  28321. }
  28322. var previousGeometry = mesh._geometry;
  28323. if (previousGeometry) {
  28324. previousGeometry.releaseForMesh(mesh);
  28325. }
  28326. var meshes = this._meshes;
  28327. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28328. mesh._geometry = this;
  28329. this._scene.pushGeometry(this);
  28330. meshes.push(mesh);
  28331. if (this.isReady()) {
  28332. this._applyToMesh(mesh);
  28333. }
  28334. else {
  28335. mesh._boundingInfo = this._boundingInfo;
  28336. }
  28337. };
  28338. Geometry.prototype.updateExtend = function (data, stride) {
  28339. if (data === void 0) { data = null; }
  28340. if (!data) {
  28341. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28342. }
  28343. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28344. };
  28345. Geometry.prototype._applyToMesh = function (mesh) {
  28346. var numOfMeshes = this._meshes.length;
  28347. // vertexBuffers
  28348. for (var kind in this._vertexBuffers) {
  28349. if (numOfMeshes === 1) {
  28350. this._vertexBuffers[kind].create();
  28351. }
  28352. var buffer = this._vertexBuffers[kind].getBuffer();
  28353. if (buffer)
  28354. buffer.references = numOfMeshes;
  28355. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28356. if (!this._extend) {
  28357. this.updateExtend(this._vertexBuffers[kind].getData());
  28358. }
  28359. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28360. mesh._createGlobalSubMesh(false);
  28361. //bounding info was just created again, world matrix should be applied again.
  28362. mesh._updateBoundingInfo();
  28363. }
  28364. }
  28365. // indexBuffer
  28366. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28367. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28368. }
  28369. if (this._indexBuffer) {
  28370. this._indexBuffer.references = numOfMeshes;
  28371. }
  28372. };
  28373. Geometry.prototype.notifyUpdate = function (kind) {
  28374. if (this.onGeometryUpdated) {
  28375. this.onGeometryUpdated(this, kind);
  28376. }
  28377. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28378. var mesh = _a[_i];
  28379. mesh._markSubMeshesAsAttributesDirty();
  28380. }
  28381. };
  28382. Geometry.prototype.load = function (scene, onLoaded) {
  28383. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28384. return;
  28385. }
  28386. if (this.isReady()) {
  28387. if (onLoaded) {
  28388. onLoaded();
  28389. }
  28390. return;
  28391. }
  28392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28393. this._queueLoad(scene, onLoaded);
  28394. };
  28395. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28396. var _this = this;
  28397. scene._addPendingData(this);
  28398. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28399. _this._delayLoadingFunction(JSON.parse(data), _this);
  28400. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28401. _this._delayInfo = [];
  28402. scene._removePendingData(_this);
  28403. var meshes = _this._meshes;
  28404. var numOfMeshes = meshes.length;
  28405. for (var index = 0; index < numOfMeshes; index++) {
  28406. _this._applyToMesh(meshes[index]);
  28407. }
  28408. if (onLoaded) {
  28409. onLoaded();
  28410. }
  28411. }, function () { }, scene.database);
  28412. };
  28413. /**
  28414. * Invert the geometry to move from a right handed system to a left handed one.
  28415. */
  28416. Geometry.prototype.toLeftHanded = function () {
  28417. // Flip faces
  28418. var tIndices = this.getIndices(false);
  28419. if (tIndices != null && tIndices.length > 0) {
  28420. for (var i = 0; i < tIndices.length; i += 3) {
  28421. var tTemp = tIndices[i + 0];
  28422. tIndices[i + 0] = tIndices[i + 2];
  28423. tIndices[i + 2] = tTemp;
  28424. }
  28425. this.setIndices(tIndices);
  28426. }
  28427. // Negate position.z
  28428. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28429. if (tPositions != null && tPositions.length > 0) {
  28430. for (var i = 0; i < tPositions.length; i += 3) {
  28431. tPositions[i + 2] = -tPositions[i + 2];
  28432. }
  28433. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28434. }
  28435. // Negate normal.z
  28436. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28437. if (tNormals != null && tNormals.length > 0) {
  28438. for (var i = 0; i < tNormals.length; i += 3) {
  28439. tNormals[i + 2] = -tNormals[i + 2];
  28440. }
  28441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28442. }
  28443. };
  28444. // Cache
  28445. Geometry.prototype._resetPointsArrayCache = function () {
  28446. this._positions = null;
  28447. };
  28448. Geometry.prototype._generatePointsArray = function () {
  28449. if (this._positions)
  28450. return true;
  28451. this._positions = [];
  28452. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28453. if (!data) {
  28454. return false;
  28455. }
  28456. for (var index = 0; index < data.length; index += 3) {
  28457. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28458. }
  28459. return true;
  28460. };
  28461. Geometry.prototype.isDisposed = function () {
  28462. return this._isDisposed;
  28463. };
  28464. Geometry.prototype._disposeVertexArrayObjects = function () {
  28465. if (this._vertexArrayObjects) {
  28466. for (var kind in this._vertexArrayObjects) {
  28467. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28468. }
  28469. this._vertexArrayObjects = {};
  28470. }
  28471. };
  28472. Geometry.prototype.dispose = function () {
  28473. var meshes = this._meshes;
  28474. var numOfMeshes = meshes.length;
  28475. var index;
  28476. for (index = 0; index < numOfMeshes; index++) {
  28477. this.releaseForMesh(meshes[index]);
  28478. }
  28479. this._meshes = [];
  28480. this._disposeVertexArrayObjects();
  28481. for (var kind in this._vertexBuffers) {
  28482. this._vertexBuffers[kind].dispose();
  28483. }
  28484. this._vertexBuffers = {};
  28485. this._totalVertices = 0;
  28486. if (this._indexBuffer) {
  28487. this._engine._releaseBuffer(this._indexBuffer);
  28488. }
  28489. this._indexBuffer = null;
  28490. this._indices = [];
  28491. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28492. this.delayLoadingFile = null;
  28493. this._delayLoadingFunction = null;
  28494. this._delayInfo = [];
  28495. this._boundingInfo = null;
  28496. this._scene.removeGeometry(this);
  28497. this._isDisposed = true;
  28498. };
  28499. Geometry.prototype.copy = function (id) {
  28500. var vertexData = new BABYLON.VertexData();
  28501. vertexData.indices = [];
  28502. var indices = this.getIndices();
  28503. for (var index = 0; index < indices.length; index++) {
  28504. vertexData.indices.push(indices[index]);
  28505. }
  28506. var updatable = false;
  28507. var stopChecking = false;
  28508. var kind;
  28509. for (kind in this._vertexBuffers) {
  28510. // using slice() to make a copy of the array and not just reference it
  28511. var data = this.getVerticesData(kind);
  28512. if (data instanceof Float32Array) {
  28513. vertexData.set(new Float32Array(data), kind);
  28514. }
  28515. else {
  28516. vertexData.set(data.slice(0), kind);
  28517. }
  28518. if (!stopChecking) {
  28519. updatable = this.getVertexBuffer(kind).isUpdatable();
  28520. stopChecking = !updatable;
  28521. }
  28522. }
  28523. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28524. geometry.delayLoadState = this.delayLoadState;
  28525. geometry.delayLoadingFile = this.delayLoadingFile;
  28526. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28527. for (kind in this._delayInfo) {
  28528. geometry._delayInfo = geometry._delayInfo || [];
  28529. geometry._delayInfo.push(kind);
  28530. }
  28531. // Bounding info
  28532. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28533. return geometry;
  28534. };
  28535. Geometry.prototype.serialize = function () {
  28536. var serializationObject = {};
  28537. serializationObject.id = this.id;
  28538. serializationObject.updatable = this._updatable;
  28539. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28540. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28541. }
  28542. return serializationObject;
  28543. };
  28544. Geometry.prototype.toNumberArray = function (origin) {
  28545. if (Array.isArray(origin)) {
  28546. return origin;
  28547. }
  28548. else {
  28549. return Array.prototype.slice.call(origin);
  28550. }
  28551. };
  28552. Geometry.prototype.serializeVerticeData = function () {
  28553. var serializationObject = this.serialize();
  28554. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28555. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28556. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28557. serializationObject.positions._updatable = true;
  28558. }
  28559. }
  28560. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28561. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28562. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28563. serializationObject.normals._updatable = true;
  28564. }
  28565. }
  28566. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28567. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28568. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28569. serializationObject.uvs._updatable = true;
  28570. }
  28571. }
  28572. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28573. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28574. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28575. serializationObject.uv2s._updatable = true;
  28576. }
  28577. }
  28578. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28579. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28580. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28581. serializationObject.uv3s._updatable = true;
  28582. }
  28583. }
  28584. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28585. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28586. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28587. serializationObject.uv4s._updatable = true;
  28588. }
  28589. }
  28590. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28591. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28592. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28593. serializationObject.uv5s._updatable = true;
  28594. }
  28595. }
  28596. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28597. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  28598. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  28599. serializationObject.uv6s._updatable = true;
  28600. }
  28601. }
  28602. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28603. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  28604. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  28605. serializationObject.colors._updatable = true;
  28606. }
  28607. }
  28608. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28609. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  28610. serializationObject.matricesIndices._isExpanded = true;
  28611. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  28612. serializationObject.matricesIndices._updatable = true;
  28613. }
  28614. }
  28615. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28616. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  28617. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  28618. serializationObject.matricesWeights._updatable = true;
  28619. }
  28620. }
  28621. serializationObject.indices = this.toNumberArray(this.getIndices());
  28622. return serializationObject;
  28623. };
  28624. // Statics
  28625. Geometry.ExtractFromMesh = function (mesh, id) {
  28626. var geometry = mesh._geometry;
  28627. if (!geometry) {
  28628. return null;
  28629. }
  28630. return geometry.copy(id);
  28631. };
  28632. /**
  28633. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  28634. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28635. * Be aware Math.random() could cause collisions, but:
  28636. * "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"
  28637. */
  28638. Geometry.RandomId = function () {
  28639. return BABYLON.Tools.RandomId();
  28640. };
  28641. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28642. var scene = mesh.getScene();
  28643. // Geometry
  28644. var geometryId = parsedGeometry.geometryId;
  28645. if (geometryId) {
  28646. var geometry = scene.getGeometryByID(geometryId);
  28647. if (geometry) {
  28648. geometry.applyToMesh(mesh);
  28649. }
  28650. }
  28651. else if (parsedGeometry instanceof ArrayBuffer) {
  28652. var binaryInfo = mesh._binaryInfo;
  28653. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28654. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28655. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28656. }
  28657. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28658. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28659. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28660. }
  28661. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28662. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28663. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28664. }
  28665. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28666. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28667. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28668. }
  28669. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28670. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28671. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28672. }
  28673. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28674. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28675. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28676. }
  28677. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28678. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28679. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28680. }
  28681. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28682. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28683. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28684. }
  28685. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28686. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28687. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28688. }
  28689. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28690. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28691. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28692. }
  28693. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28694. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28695. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28696. }
  28697. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28698. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28699. mesh.setIndices(indicesData);
  28700. }
  28701. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28702. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28703. mesh.subMeshes = [];
  28704. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28705. var materialIndex = subMeshesData[(i * 5) + 0];
  28706. var verticesStart = subMeshesData[(i * 5) + 1];
  28707. var verticesCount = subMeshesData[(i * 5) + 2];
  28708. var indexStart = subMeshesData[(i * 5) + 3];
  28709. var indexCount = subMeshesData[(i * 5) + 4];
  28710. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28711. }
  28712. }
  28713. }
  28714. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28715. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  28716. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  28717. if (parsedGeometry.uvs) {
  28718. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  28719. }
  28720. if (parsedGeometry.uvs2) {
  28721. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  28722. }
  28723. if (parsedGeometry.uvs3) {
  28724. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  28725. }
  28726. if (parsedGeometry.uvs4) {
  28727. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  28728. }
  28729. if (parsedGeometry.uvs5) {
  28730. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  28731. }
  28732. if (parsedGeometry.uvs6) {
  28733. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  28734. }
  28735. if (parsedGeometry.colors) {
  28736. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  28737. }
  28738. if (parsedGeometry.matricesIndices) {
  28739. if (!parsedGeometry.matricesIndices._isExpanded) {
  28740. var floatIndices = [];
  28741. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28742. var matricesIndex = parsedGeometry.matricesIndices[i];
  28743. floatIndices.push(matricesIndex & 0x000000FF);
  28744. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28745. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28746. floatIndices.push(matricesIndex >> 24);
  28747. }
  28748. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  28749. }
  28750. else {
  28751. delete parsedGeometry.matricesIndices._isExpanded;
  28752. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  28753. }
  28754. }
  28755. if (parsedGeometry.matricesIndicesExtra) {
  28756. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28757. var floatIndices = [];
  28758. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28759. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28760. floatIndices.push(matricesIndex & 0x000000FF);
  28761. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28762. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28763. floatIndices.push(matricesIndex >> 24);
  28764. }
  28765. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  28766. }
  28767. else {
  28768. delete parsedGeometry.matricesIndices._isExpanded;
  28769. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  28770. }
  28771. }
  28772. if (parsedGeometry.matricesWeights) {
  28773. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  28774. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  28775. }
  28776. if (parsedGeometry.matricesWeightsExtra) {
  28777. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  28778. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  28779. }
  28780. mesh.setIndices(parsedGeometry.indices);
  28781. }
  28782. // SubMeshes
  28783. if (parsedGeometry.subMeshes) {
  28784. mesh.subMeshes = [];
  28785. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28786. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28787. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28788. }
  28789. }
  28790. // Flat shading
  28791. if (mesh._shouldGenerateFlatShading) {
  28792. mesh.convertToFlatShadedMesh();
  28793. delete mesh._shouldGenerateFlatShading;
  28794. }
  28795. // Update
  28796. mesh.computeWorldMatrix(true);
  28797. // Octree
  28798. if (scene['_selectionOctree']) {
  28799. scene['_selectionOctree'].addMesh(mesh);
  28800. }
  28801. };
  28802. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  28803. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  28804. return;
  28805. }
  28806. var size = matricesWeights.length;
  28807. for (var i = 0; i < size; i += influencers) {
  28808. var weight = 0;
  28809. var biggerIndex = i;
  28810. var biggerWeight = 0;
  28811. for (var j = 0; j < influencers - 1; j++) {
  28812. weight += matricesWeights[i + j];
  28813. if (matricesWeights[i + j] > biggerWeight) {
  28814. biggerWeight = matricesWeights[i + j];
  28815. biggerIndex = i + j;
  28816. }
  28817. }
  28818. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  28819. }
  28820. };
  28821. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28822. if (scene.getGeometryByID(parsedVertexData.id)) {
  28823. return null; // null since geometry could be something else than a box...
  28824. }
  28825. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  28826. if (BABYLON.Tags) {
  28827. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28828. }
  28829. if (parsedVertexData.delayLoadingFile) {
  28830. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28831. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28832. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28833. geometry._delayInfo = [];
  28834. if (parsedVertexData.hasUVs) {
  28835. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28836. }
  28837. if (parsedVertexData.hasUVs2) {
  28838. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28839. }
  28840. if (parsedVertexData.hasUVs3) {
  28841. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28842. }
  28843. if (parsedVertexData.hasUVs4) {
  28844. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28845. }
  28846. if (parsedVertexData.hasUVs5) {
  28847. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28848. }
  28849. if (parsedVertexData.hasUVs6) {
  28850. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28851. }
  28852. if (parsedVertexData.hasColors) {
  28853. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28854. }
  28855. if (parsedVertexData.hasMatricesIndices) {
  28856. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28857. }
  28858. if (parsedVertexData.hasMatricesWeights) {
  28859. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28860. }
  28861. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28862. }
  28863. else {
  28864. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28865. }
  28866. scene.pushGeometry(geometry, true);
  28867. return geometry;
  28868. };
  28869. return Geometry;
  28870. }());
  28871. BABYLON.Geometry = Geometry;
  28872. /////// Primitives //////////////////////////////////////////////
  28873. (function (Geometry) {
  28874. var Primitives;
  28875. (function (Primitives) {
  28876. /// Abstract class
  28877. var _Primitive = (function (_super) {
  28878. __extends(_Primitive, _super);
  28879. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28880. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  28881. _this._canBeRegenerated = _canBeRegenerated;
  28882. _this._beingRegenerated = true;
  28883. _this.regenerate();
  28884. _this._beingRegenerated = false;
  28885. return _this;
  28886. }
  28887. _Primitive.prototype.canBeRegenerated = function () {
  28888. return this._canBeRegenerated;
  28889. };
  28890. _Primitive.prototype.regenerate = function () {
  28891. if (!this._canBeRegenerated) {
  28892. return;
  28893. }
  28894. this._beingRegenerated = true;
  28895. this.setAllVerticesData(this._regenerateVertexData(), false);
  28896. this._beingRegenerated = false;
  28897. };
  28898. _Primitive.prototype.asNewGeometry = function (id) {
  28899. return _super.prototype.copy.call(this, id);
  28900. };
  28901. // overrides
  28902. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28903. if (!this._beingRegenerated) {
  28904. return;
  28905. }
  28906. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28907. };
  28908. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28909. if (!this._beingRegenerated) {
  28910. return;
  28911. }
  28912. _super.prototype.setVerticesData.call(this, kind, data, false);
  28913. };
  28914. // to override
  28915. // protected
  28916. _Primitive.prototype._regenerateVertexData = function () {
  28917. throw new Error("Abstract method");
  28918. };
  28919. _Primitive.prototype.copy = function (id) {
  28920. throw new Error("Must be overriden in sub-classes.");
  28921. };
  28922. _Primitive.prototype.serialize = function () {
  28923. var serializationObject = _super.prototype.serialize.call(this);
  28924. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28925. return serializationObject;
  28926. };
  28927. return _Primitive;
  28928. }(Geometry));
  28929. Primitives._Primitive = _Primitive;
  28930. var Ribbon = (function (_super) {
  28931. __extends(Ribbon, _super);
  28932. // Members
  28933. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28934. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28935. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28936. _this.pathArray = pathArray;
  28937. _this.closeArray = closeArray;
  28938. _this.closePath = closePath;
  28939. _this.offset = offset;
  28940. _this.side = side;
  28941. return _this;
  28942. }
  28943. Ribbon.prototype._regenerateVertexData = function () {
  28944. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28945. };
  28946. Ribbon.prototype.copy = function (id) {
  28947. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28948. };
  28949. return Ribbon;
  28950. }(_Primitive));
  28951. Primitives.Ribbon = Ribbon;
  28952. var Box = (function (_super) {
  28953. __extends(Box, _super);
  28954. // Members
  28955. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28956. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28957. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28958. _this.size = size;
  28959. _this.side = side;
  28960. return _this;
  28961. }
  28962. Box.prototype._regenerateVertexData = function () {
  28963. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28964. };
  28965. Box.prototype.copy = function (id) {
  28966. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28967. };
  28968. Box.prototype.serialize = function () {
  28969. var serializationObject = _super.prototype.serialize.call(this);
  28970. serializationObject.size = this.size;
  28971. return serializationObject;
  28972. };
  28973. Box.Parse = function (parsedBox, scene) {
  28974. if (scene.getGeometryByID(parsedBox.id)) {
  28975. return null; // null since geometry could be something else than a box...
  28976. }
  28977. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28978. if (BABYLON.Tags) {
  28979. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28980. }
  28981. scene.pushGeometry(box, true);
  28982. return box;
  28983. };
  28984. return Box;
  28985. }(_Primitive));
  28986. Primitives.Box = Box;
  28987. var Sphere = (function (_super) {
  28988. __extends(Sphere, _super);
  28989. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28991. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28992. _this.segments = segments;
  28993. _this.diameter = diameter;
  28994. _this.side = side;
  28995. return _this;
  28996. }
  28997. Sphere.prototype._regenerateVertexData = function () {
  28998. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28999. };
  29000. Sphere.prototype.copy = function (id) {
  29001. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29002. };
  29003. Sphere.prototype.serialize = function () {
  29004. var serializationObject = _super.prototype.serialize.call(this);
  29005. serializationObject.segments = this.segments;
  29006. serializationObject.diameter = this.diameter;
  29007. return serializationObject;
  29008. };
  29009. Sphere.Parse = function (parsedSphere, scene) {
  29010. if (scene.getGeometryByID(parsedSphere.id)) {
  29011. return null; // null since geometry could be something else than a sphere...
  29012. }
  29013. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29014. if (BABYLON.Tags) {
  29015. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29016. }
  29017. scene.pushGeometry(sphere, true);
  29018. return sphere;
  29019. };
  29020. return Sphere;
  29021. }(_Primitive));
  29022. Primitives.Sphere = Sphere;
  29023. var Disc = (function (_super) {
  29024. __extends(Disc, _super);
  29025. // Members
  29026. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29027. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29028. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29029. _this.radius = radius;
  29030. _this.tessellation = tessellation;
  29031. _this.side = side;
  29032. return _this;
  29033. }
  29034. Disc.prototype._regenerateVertexData = function () {
  29035. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29036. };
  29037. Disc.prototype.copy = function (id) {
  29038. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29039. };
  29040. return Disc;
  29041. }(_Primitive));
  29042. Primitives.Disc = Disc;
  29043. var Cylinder = (function (_super) {
  29044. __extends(Cylinder, _super);
  29045. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29046. if (subdivisions === void 0) { subdivisions = 1; }
  29047. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29048. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29049. _this.height = height;
  29050. _this.diameterTop = diameterTop;
  29051. _this.diameterBottom = diameterBottom;
  29052. _this.tessellation = tessellation;
  29053. _this.subdivisions = subdivisions;
  29054. _this.side = side;
  29055. return _this;
  29056. }
  29057. Cylinder.prototype._regenerateVertexData = function () {
  29058. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29059. };
  29060. Cylinder.prototype.copy = function (id) {
  29061. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29062. };
  29063. Cylinder.prototype.serialize = function () {
  29064. var serializationObject = _super.prototype.serialize.call(this);
  29065. serializationObject.height = this.height;
  29066. serializationObject.diameterTop = this.diameterTop;
  29067. serializationObject.diameterBottom = this.diameterBottom;
  29068. serializationObject.tessellation = this.tessellation;
  29069. return serializationObject;
  29070. };
  29071. Cylinder.Parse = function (parsedCylinder, scene) {
  29072. if (scene.getGeometryByID(parsedCylinder.id)) {
  29073. return null; // null since geometry could be something else than a cylinder...
  29074. }
  29075. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29076. if (BABYLON.Tags) {
  29077. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29078. }
  29079. scene.pushGeometry(cylinder, true);
  29080. return cylinder;
  29081. };
  29082. return Cylinder;
  29083. }(_Primitive));
  29084. Primitives.Cylinder = Cylinder;
  29085. var Torus = (function (_super) {
  29086. __extends(Torus, _super);
  29087. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29088. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29089. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29090. _this.diameter = diameter;
  29091. _this.thickness = thickness;
  29092. _this.tessellation = tessellation;
  29093. _this.side = side;
  29094. return _this;
  29095. }
  29096. Torus.prototype._regenerateVertexData = function () {
  29097. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29098. };
  29099. Torus.prototype.copy = function (id) {
  29100. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29101. };
  29102. Torus.prototype.serialize = function () {
  29103. var serializationObject = _super.prototype.serialize.call(this);
  29104. serializationObject.diameter = this.diameter;
  29105. serializationObject.thickness = this.thickness;
  29106. serializationObject.tessellation = this.tessellation;
  29107. return serializationObject;
  29108. };
  29109. Torus.Parse = function (parsedTorus, scene) {
  29110. if (scene.getGeometryByID(parsedTorus.id)) {
  29111. return null; // null since geometry could be something else than a torus...
  29112. }
  29113. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29114. if (BABYLON.Tags) {
  29115. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29116. }
  29117. scene.pushGeometry(torus, true);
  29118. return torus;
  29119. };
  29120. return Torus;
  29121. }(_Primitive));
  29122. Primitives.Torus = Torus;
  29123. var Ground = (function (_super) {
  29124. __extends(Ground, _super);
  29125. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29126. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29127. _this.width = width;
  29128. _this.height = height;
  29129. _this.subdivisions = subdivisions;
  29130. return _this;
  29131. }
  29132. Ground.prototype._regenerateVertexData = function () {
  29133. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29134. };
  29135. Ground.prototype.copy = function (id) {
  29136. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29137. };
  29138. Ground.prototype.serialize = function () {
  29139. var serializationObject = _super.prototype.serialize.call(this);
  29140. serializationObject.width = this.width;
  29141. serializationObject.height = this.height;
  29142. serializationObject.subdivisions = this.subdivisions;
  29143. return serializationObject;
  29144. };
  29145. Ground.Parse = function (parsedGround, scene) {
  29146. if (scene.getGeometryByID(parsedGround.id)) {
  29147. return null; // null since geometry could be something else than a ground...
  29148. }
  29149. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29150. if (BABYLON.Tags) {
  29151. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29152. }
  29153. scene.pushGeometry(ground, true);
  29154. return ground;
  29155. };
  29156. return Ground;
  29157. }(_Primitive));
  29158. Primitives.Ground = Ground;
  29159. var TiledGround = (function (_super) {
  29160. __extends(TiledGround, _super);
  29161. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29162. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29163. _this.xmin = xmin;
  29164. _this.zmin = zmin;
  29165. _this.xmax = xmax;
  29166. _this.zmax = zmax;
  29167. _this.subdivisions = subdivisions;
  29168. _this.precision = precision;
  29169. return _this;
  29170. }
  29171. TiledGround.prototype._regenerateVertexData = function () {
  29172. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29173. };
  29174. TiledGround.prototype.copy = function (id) {
  29175. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29176. };
  29177. return TiledGround;
  29178. }(_Primitive));
  29179. Primitives.TiledGround = TiledGround;
  29180. var Plane = (function (_super) {
  29181. __extends(Plane, _super);
  29182. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29183. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29184. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29185. _this.size = size;
  29186. _this.side = side;
  29187. return _this;
  29188. }
  29189. Plane.prototype._regenerateVertexData = function () {
  29190. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29191. };
  29192. Plane.prototype.copy = function (id) {
  29193. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29194. };
  29195. Plane.prototype.serialize = function () {
  29196. var serializationObject = _super.prototype.serialize.call(this);
  29197. serializationObject.size = this.size;
  29198. return serializationObject;
  29199. };
  29200. Plane.Parse = function (parsedPlane, scene) {
  29201. if (scene.getGeometryByID(parsedPlane.id)) {
  29202. return null; // null since geometry could be something else than a ground...
  29203. }
  29204. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29205. if (BABYLON.Tags) {
  29206. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29207. }
  29208. scene.pushGeometry(plane, true);
  29209. return plane;
  29210. };
  29211. return Plane;
  29212. }(_Primitive));
  29213. Primitives.Plane = Plane;
  29214. var TorusKnot = (function (_super) {
  29215. __extends(TorusKnot, _super);
  29216. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29217. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29218. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29219. _this.radius = radius;
  29220. _this.tube = tube;
  29221. _this.radialSegments = radialSegments;
  29222. _this.tubularSegments = tubularSegments;
  29223. _this.p = p;
  29224. _this.q = q;
  29225. _this.side = side;
  29226. return _this;
  29227. }
  29228. TorusKnot.prototype._regenerateVertexData = function () {
  29229. 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 });
  29230. };
  29231. TorusKnot.prototype.copy = function (id) {
  29232. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29233. };
  29234. TorusKnot.prototype.serialize = function () {
  29235. var serializationObject = _super.prototype.serialize.call(this);
  29236. serializationObject.radius = this.radius;
  29237. serializationObject.tube = this.tube;
  29238. serializationObject.radialSegments = this.radialSegments;
  29239. serializationObject.tubularSegments = this.tubularSegments;
  29240. serializationObject.p = this.p;
  29241. serializationObject.q = this.q;
  29242. return serializationObject;
  29243. };
  29244. ;
  29245. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29246. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29247. return null; // null since geometry could be something else than a ground...
  29248. }
  29249. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29250. if (BABYLON.Tags) {
  29251. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29252. }
  29253. scene.pushGeometry(torusKnot, true);
  29254. return torusKnot;
  29255. };
  29256. return TorusKnot;
  29257. }(_Primitive));
  29258. Primitives.TorusKnot = TorusKnot;
  29259. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29260. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29261. })(BABYLON || (BABYLON = {}));
  29262. //# sourceMappingURL=babylon.geometry.js.map
  29263. var BABYLON;
  29264. (function (BABYLON) {
  29265. var PostProcessManager = (function () {
  29266. function PostProcessManager(scene) {
  29267. this._vertexBuffers = {};
  29268. this._scene = scene;
  29269. }
  29270. PostProcessManager.prototype._prepareBuffers = function () {
  29271. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29272. return;
  29273. }
  29274. // VBO
  29275. var vertices = [];
  29276. vertices.push(1, 1);
  29277. vertices.push(-1, 1);
  29278. vertices.push(-1, -1);
  29279. vertices.push(1, -1);
  29280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29281. // Indices
  29282. var indices = [];
  29283. indices.push(0);
  29284. indices.push(1);
  29285. indices.push(2);
  29286. indices.push(0);
  29287. indices.push(2);
  29288. indices.push(3);
  29289. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29290. };
  29291. // Methods
  29292. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29293. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29294. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29295. return false;
  29296. }
  29297. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29298. return true;
  29299. };
  29300. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29301. var engine = this._scene.getEngine();
  29302. for (var index = 0; index < postProcesses.length; index++) {
  29303. if (index < postProcesses.length - 1) {
  29304. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29305. }
  29306. else {
  29307. if (targetTexture) {
  29308. engine.bindFramebuffer(targetTexture);
  29309. }
  29310. else {
  29311. engine.restoreDefaultFramebuffer();
  29312. }
  29313. }
  29314. var pp = postProcesses[index];
  29315. var effect = pp.apply();
  29316. if (effect) {
  29317. pp.onBeforeRenderObservable.notifyObservers(effect);
  29318. // VBOs
  29319. this._prepareBuffers();
  29320. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29321. // Draw order
  29322. engine.draw(true, 0, 6);
  29323. pp.onAfterRenderObservable.notifyObservers(effect);
  29324. }
  29325. }
  29326. // Restore depth buffer
  29327. engine.setDepthBuffer(true);
  29328. engine.setDepthWrite(true);
  29329. };
  29330. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29331. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29332. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29333. return;
  29334. }
  29335. var engine = this._scene.getEngine();
  29336. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29337. if (index < len - 1) {
  29338. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29339. }
  29340. else {
  29341. if (targetTexture) {
  29342. engine.bindFramebuffer(targetTexture, faceIndex);
  29343. }
  29344. else {
  29345. engine.restoreDefaultFramebuffer();
  29346. }
  29347. }
  29348. if (doNotPresent) {
  29349. break;
  29350. }
  29351. var pp = postProcesses[index];
  29352. var effect = pp.apply();
  29353. if (effect) {
  29354. pp.onBeforeRenderObservable.notifyObservers(effect);
  29355. // VBOs
  29356. this._prepareBuffers();
  29357. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29358. // Draw order
  29359. engine.draw(true, 0, 6);
  29360. pp.onAfterRenderObservable.notifyObservers(effect);
  29361. }
  29362. }
  29363. // Restore states
  29364. engine.setDepthBuffer(true);
  29365. engine.setDepthWrite(true);
  29366. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29367. };
  29368. PostProcessManager.prototype.dispose = function () {
  29369. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29370. if (buffer) {
  29371. buffer.dispose();
  29372. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29373. }
  29374. if (this._indexBuffer) {
  29375. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29376. this._indexBuffer = null;
  29377. }
  29378. };
  29379. return PostProcessManager;
  29380. }());
  29381. BABYLON.PostProcessManager = PostProcessManager;
  29382. })(BABYLON || (BABYLON = {}));
  29383. //# sourceMappingURL=babylon.postProcessManager.js.map
  29384. var BABYLON;
  29385. (function (BABYLON) {
  29386. /**
  29387. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29388. */
  29389. var PerformanceMonitor = (function () {
  29390. /**
  29391. * constructor
  29392. * @param frameSampleSize The number of samples required to saturate the sliding window
  29393. */
  29394. function PerformanceMonitor(frameSampleSize) {
  29395. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29396. this._enabled = true;
  29397. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29398. }
  29399. /**
  29400. * Samples current frame
  29401. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29402. */
  29403. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29404. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29405. if (!this._enabled)
  29406. return;
  29407. if (this._lastFrameTimeMs != null) {
  29408. var dt = timeMs - this._lastFrameTimeMs;
  29409. this._rollingFrameTime.add(dt);
  29410. }
  29411. this._lastFrameTimeMs = timeMs;
  29412. };
  29413. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29414. /**
  29415. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29416. * @return Average frame time in milliseconds
  29417. */
  29418. get: function () {
  29419. return this._rollingFrameTime.average;
  29420. },
  29421. enumerable: true,
  29422. configurable: true
  29423. });
  29424. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29425. /**
  29426. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29427. * @return Frame time variance in milliseconds squared
  29428. */
  29429. get: function () {
  29430. return this._rollingFrameTime.variance;
  29431. },
  29432. enumerable: true,
  29433. configurable: true
  29434. });
  29435. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29436. /**
  29437. * Returns the frame time of the most recent frame
  29438. * @return Frame time in milliseconds
  29439. */
  29440. get: function () {
  29441. return this._rollingFrameTime.history(0);
  29442. },
  29443. enumerable: true,
  29444. configurable: true
  29445. });
  29446. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29447. /**
  29448. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29449. * @return Framerate in frames per second
  29450. */
  29451. get: function () {
  29452. return 1000.0 / this._rollingFrameTime.average;
  29453. },
  29454. enumerable: true,
  29455. configurable: true
  29456. });
  29457. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29458. /**
  29459. * Returns the average framerate in frames per second using the most recent frame time
  29460. * @return Framerate in frames per second
  29461. */
  29462. get: function () {
  29463. return 1000.0 / this._rollingFrameTime.history(0);
  29464. },
  29465. enumerable: true,
  29466. configurable: true
  29467. });
  29468. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29469. /**
  29470. * Returns true if enough samples have been taken to completely fill the sliding window
  29471. * @return true if saturated
  29472. */
  29473. get: function () {
  29474. return this._rollingFrameTime.isSaturated();
  29475. },
  29476. enumerable: true,
  29477. configurable: true
  29478. });
  29479. /**
  29480. * Enables contributions to the sliding window sample set
  29481. */
  29482. PerformanceMonitor.prototype.enable = function () {
  29483. this._enabled = true;
  29484. };
  29485. /**
  29486. * Disables contributions to the sliding window sample set
  29487. * Samples will not be interpolated over the disabled period
  29488. */
  29489. PerformanceMonitor.prototype.disable = function () {
  29490. this._enabled = false;
  29491. //clear last sample to avoid interpolating over the disabled period when next enabled
  29492. this._lastFrameTimeMs = null;
  29493. this._lastChangeTimeMs = null;
  29494. };
  29495. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29496. /**
  29497. * Returns true if sampling is enabled
  29498. * @return true if enabled
  29499. */
  29500. get: function () {
  29501. return this._enabled;
  29502. },
  29503. enumerable: true,
  29504. configurable: true
  29505. });
  29506. /**
  29507. * Resets performance monitor
  29508. */
  29509. PerformanceMonitor.prototype.reset = function () {
  29510. //clear last sample to avoid interpolating over the disabled period when next enabled
  29511. this._lastFrameTimeMs = null;
  29512. this._lastChangeTimeMs = null;
  29513. //wipe record
  29514. this._rollingFrameTime.reset();
  29515. };
  29516. return PerformanceMonitor;
  29517. }());
  29518. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29519. /**
  29520. * RollingAverage
  29521. *
  29522. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29523. */
  29524. var RollingAverage = (function () {
  29525. /**
  29526. * constructor
  29527. * @param length The number of samples required to saturate the sliding window
  29528. */
  29529. function RollingAverage(length) {
  29530. this._samples = new Array(length);
  29531. this.reset();
  29532. }
  29533. /**
  29534. * Adds a sample to the sample set
  29535. * @param v The sample value
  29536. */
  29537. RollingAverage.prototype.add = function (v) {
  29538. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29539. var delta;
  29540. //we need to check if we've already wrapped round
  29541. if (this.isSaturated()) {
  29542. //remove bottom of stack from mean
  29543. var bottomValue = this._samples[this._pos];
  29544. delta = bottomValue - this.average;
  29545. this.average -= delta / (this._sampleCount - 1);
  29546. this._m2 -= delta * (bottomValue - this.average);
  29547. }
  29548. else {
  29549. this._sampleCount++;
  29550. }
  29551. //add new value to mean
  29552. delta = v - this.average;
  29553. this.average += delta / (this._sampleCount);
  29554. this._m2 += delta * (v - this.average);
  29555. //set the new variance
  29556. this.variance = this._m2 / (this._sampleCount - 1);
  29557. this._samples[this._pos] = v;
  29558. this._pos++;
  29559. this._pos %= this._samples.length; //positive wrap around
  29560. };
  29561. /**
  29562. * Returns previously added values or null if outside of history or outside the sliding window domain
  29563. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  29564. * @return Value previously recorded with add() or null if outside of range
  29565. */
  29566. RollingAverage.prototype.history = function (i) {
  29567. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  29568. return null;
  29569. }
  29570. var i0 = this._wrapPosition(this._pos - 1.0);
  29571. return this._samples[this._wrapPosition(i0 - i)];
  29572. };
  29573. /**
  29574. * Returns true if enough samples have been taken to completely fill the sliding window
  29575. * @return true if sample-set saturated
  29576. */
  29577. RollingAverage.prototype.isSaturated = function () {
  29578. return this._sampleCount >= this._samples.length;
  29579. };
  29580. /**
  29581. * Resets the rolling average (equivalent to 0 samples taken so far)
  29582. */
  29583. RollingAverage.prototype.reset = function () {
  29584. this.average = 0;
  29585. this.variance = 0;
  29586. this._sampleCount = 0;
  29587. this._pos = 0;
  29588. this._m2 = 0;
  29589. };
  29590. /**
  29591. * Wraps a value around the sample range boundaries
  29592. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  29593. * @return Wrapped position in sample range
  29594. */
  29595. RollingAverage.prototype._wrapPosition = function (i) {
  29596. var max = this._samples.length;
  29597. return ((i % max) + max) % max;
  29598. };
  29599. return RollingAverage;
  29600. }());
  29601. BABYLON.RollingAverage = RollingAverage;
  29602. })(BABYLON || (BABYLON = {}));
  29603. //# sourceMappingURL=babylon.performanceMonitor.js.map
  29604. var BABYLON;
  29605. (function (BABYLON) {
  29606. var StandardMaterialDefines = (function (_super) {
  29607. __extends(StandardMaterialDefines, _super);
  29608. function StandardMaterialDefines() {
  29609. var _this = _super.call(this) || this;
  29610. _this.MAINUV1 = false;
  29611. _this.MAINUV2 = false;
  29612. _this.DIFFUSE = false;
  29613. _this.DIFFUSEDIRECTUV = 0;
  29614. _this.AMBIENT = false;
  29615. _this.AMBIENTDIRECTUV = 0;
  29616. _this.OPACITY = false;
  29617. _this.OPACITYDIRECTUV = 0;
  29618. _this.OPACITYRGB = false;
  29619. _this.REFLECTION = false;
  29620. _this.EMISSIVE = false;
  29621. _this.EMISSIVEDIRECTUV = 0;
  29622. _this.SPECULAR = false;
  29623. _this.SPECULARDIRECTUV = 0;
  29624. _this.BUMP = false;
  29625. _this.BUMPDIRECTUV = 0;
  29626. _this.PARALLAX = false;
  29627. _this.PARALLAXOCCLUSION = false;
  29628. _this.SPECULAROVERALPHA = false;
  29629. _this.CLIPPLANE = false;
  29630. _this.ALPHATEST = false;
  29631. _this.ALPHAFROMDIFFUSE = false;
  29632. _this.POINTSIZE = false;
  29633. _this.FOG = false;
  29634. _this.SPECULARTERM = false;
  29635. _this.DIFFUSEFRESNEL = false;
  29636. _this.OPACITYFRESNEL = false;
  29637. _this.REFLECTIONFRESNEL = false;
  29638. _this.REFRACTIONFRESNEL = false;
  29639. _this.EMISSIVEFRESNEL = false;
  29640. _this.FRESNEL = false;
  29641. _this.NORMAL = false;
  29642. _this.UV1 = false;
  29643. _this.UV2 = false;
  29644. _this.VERTEXCOLOR = false;
  29645. _this.VERTEXALPHA = false;
  29646. _this.NUM_BONE_INFLUENCERS = 0;
  29647. _this.BonesPerMesh = 0;
  29648. _this.INSTANCES = false;
  29649. _this.GLOSSINESS = false;
  29650. _this.ROUGHNESS = false;
  29651. _this.EMISSIVEASILLUMINATION = false;
  29652. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29653. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29654. _this.LIGHTMAP = false;
  29655. _this.LIGHTMAPDIRECTUV = 0;
  29656. _this.USELIGHTMAPASSHADOWMAP = false;
  29657. _this.REFLECTIONMAP_3D = false;
  29658. _this.REFLECTIONMAP_SPHERICAL = false;
  29659. _this.REFLECTIONMAP_PLANAR = false;
  29660. _this.REFLECTIONMAP_CUBIC = false;
  29661. _this.REFLECTIONMAP_PROJECTION = false;
  29662. _this.REFLECTIONMAP_SKYBOX = false;
  29663. _this.REFLECTIONMAP_EXPLICIT = false;
  29664. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29665. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29666. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29667. _this.INVERTCUBICMAP = false;
  29668. _this.LOGARITHMICDEPTH = false;
  29669. _this.REFRACTION = false;
  29670. _this.REFRACTIONMAP_3D = false;
  29671. _this.REFLECTIONOVERALPHA = false;
  29672. _this.TWOSIDEDLIGHTING = false;
  29673. _this.SHADOWFLOAT = false;
  29674. _this.MORPHTARGETS = false;
  29675. _this.MORPHTARGETS_NORMAL = false;
  29676. _this.MORPHTARGETS_TANGENT = false;
  29677. _this.NUM_MORPH_INFLUENCERS = 0;
  29678. _this.USERIGHTHANDEDSYSTEM = false;
  29679. _this.IMAGEPROCESSING = false;
  29680. _this.VIGNETTE = false;
  29681. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  29682. _this.VIGNETTEBLENDMODEOPAQUE = false;
  29683. _this.TONEMAPPING = false;
  29684. _this.CONTRAST = false;
  29685. _this.COLORCURVES = false;
  29686. _this.COLORGRADING = false;
  29687. _this.SAMPLER3DGREENDEPTH = false;
  29688. _this.SAMPLER3DBGRMAP = false;
  29689. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  29690. _this.EXPOSURE = false;
  29691. _this.rebuild();
  29692. return _this;
  29693. }
  29694. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  29695. var modes = [
  29696. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  29697. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  29698. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  29699. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  29700. ];
  29701. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  29702. var mode = modes_1[_i];
  29703. this[mode] = (mode === modeToEnable);
  29704. }
  29705. };
  29706. return StandardMaterialDefines;
  29707. }(BABYLON.MaterialDefines));
  29708. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  29709. var StandardMaterial = (function (_super) {
  29710. __extends(StandardMaterial, _super);
  29711. function StandardMaterial(name, scene) {
  29712. var _this = _super.call(this, name, scene) || this;
  29713. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29714. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29715. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29716. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29717. _this.specularPower = 64;
  29718. _this._useAlphaFromDiffuseTexture = false;
  29719. _this._useEmissiveAsIllumination = false;
  29720. _this._linkEmissiveWithDiffuse = false;
  29721. _this._useSpecularOverAlpha = false;
  29722. _this._useReflectionOverAlpha = false;
  29723. _this._disableLighting = false;
  29724. _this._useParallax = false;
  29725. _this._useParallaxOcclusion = false;
  29726. _this.parallaxScaleBias = 0.05;
  29727. _this._roughness = 0;
  29728. _this.indexOfRefraction = 0.98;
  29729. _this.invertRefractionY = true;
  29730. _this._useLightmapAsShadowmap = false;
  29731. _this._useReflectionFresnelFromSpecular = false;
  29732. _this._useGlossinessFromSpecularMapAlpha = false;
  29733. _this._maxSimultaneousLights = 4;
  29734. /**
  29735. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29736. */
  29737. _this._invertNormalMapX = false;
  29738. /**
  29739. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29740. */
  29741. _this._invertNormalMapY = false;
  29742. /**
  29743. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  29744. */
  29745. _this._twoSidedLighting = false;
  29746. _this._renderTargets = new BABYLON.SmartArray(16);
  29747. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29748. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29749. // Setup the default processing configuration to the scene.
  29750. _this._attachImageProcessingConfiguration(null);
  29751. _this.getRenderTargetTextures = function () {
  29752. _this._renderTargets.reset();
  29753. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  29754. _this._renderTargets.push(_this._reflectionTexture);
  29755. }
  29756. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  29757. _this._renderTargets.push(_this._refractionTexture);
  29758. }
  29759. return _this._renderTargets;
  29760. };
  29761. return _this;
  29762. }
  29763. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  29764. /**
  29765. * Gets the image processing configuration used either in this material.
  29766. */
  29767. get: function () {
  29768. return this._imageProcessingConfiguration;
  29769. },
  29770. /**
  29771. * Sets the Default image processing configuration used either in the this material.
  29772. *
  29773. * If sets to null, the scene one is in use.
  29774. */
  29775. set: function (value) {
  29776. this._attachImageProcessingConfiguration(value);
  29777. // Ensure the effect will be rebuilt.
  29778. this._markAllSubMeshesAsTexturesDirty();
  29779. },
  29780. enumerable: true,
  29781. configurable: true
  29782. });
  29783. /**
  29784. * Attaches a new image processing configuration to the Standard Material.
  29785. * @param configuration
  29786. */
  29787. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  29788. var _this = this;
  29789. if (configuration === this._imageProcessingConfiguration) {
  29790. return;
  29791. }
  29792. // Detaches observer.
  29793. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  29794. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  29795. }
  29796. // Pick the scene configuration if needed.
  29797. if (!configuration) {
  29798. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  29799. }
  29800. else {
  29801. this._imageProcessingConfiguration = configuration;
  29802. }
  29803. // Attaches observer.
  29804. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  29805. _this._markAllSubMeshesAsImageProcessingDirty();
  29806. });
  29807. };
  29808. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  29809. /**
  29810. * Gets wether the color curves effect is enabled.
  29811. */
  29812. get: function () {
  29813. return this.imageProcessingConfiguration.colorCurvesEnabled;
  29814. },
  29815. /**
  29816. * Sets wether the color curves effect is enabled.
  29817. */
  29818. set: function (value) {
  29819. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  29820. },
  29821. enumerable: true,
  29822. configurable: true
  29823. });
  29824. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  29825. /**
  29826. * Gets wether the color grading effect is enabled.
  29827. */
  29828. get: function () {
  29829. return this.imageProcessingConfiguration.colorGradingEnabled;
  29830. },
  29831. /**
  29832. * Gets wether the color grading effect is enabled.
  29833. */
  29834. set: function (value) {
  29835. this.imageProcessingConfiguration.colorGradingEnabled = value;
  29836. },
  29837. enumerable: true,
  29838. configurable: true
  29839. });
  29840. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  29841. /**
  29842. * Gets wether tonemapping is enabled or not.
  29843. */
  29844. get: function () {
  29845. return this._imageProcessingConfiguration.toneMappingEnabled;
  29846. },
  29847. /**
  29848. * Sets wether tonemapping is enabled or not
  29849. */
  29850. set: function (value) {
  29851. this._imageProcessingConfiguration.toneMappingEnabled = value;
  29852. },
  29853. enumerable: true,
  29854. configurable: true
  29855. });
  29856. ;
  29857. ;
  29858. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  29859. /**
  29860. * The camera exposure used on this material.
  29861. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29862. * This corresponds to a photographic exposure.
  29863. */
  29864. get: function () {
  29865. return this._imageProcessingConfiguration.exposure;
  29866. },
  29867. /**
  29868. * The camera exposure used on this material.
  29869. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29870. * This corresponds to a photographic exposure.
  29871. */
  29872. set: function (value) {
  29873. this._imageProcessingConfiguration.exposure = value;
  29874. },
  29875. enumerable: true,
  29876. configurable: true
  29877. });
  29878. ;
  29879. ;
  29880. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  29881. /**
  29882. * Gets The camera contrast used on this material.
  29883. */
  29884. get: function () {
  29885. return this._imageProcessingConfiguration.contrast;
  29886. },
  29887. /**
  29888. * Sets The camera contrast used on this material.
  29889. */
  29890. set: function (value) {
  29891. this._imageProcessingConfiguration.contrast = value;
  29892. },
  29893. enumerable: true,
  29894. configurable: true
  29895. });
  29896. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  29897. /**
  29898. * Gets the Color Grading 2D Lookup Texture.
  29899. */
  29900. get: function () {
  29901. return this._imageProcessingConfiguration.colorGradingTexture;
  29902. },
  29903. /**
  29904. * Sets the Color Grading 2D Lookup Texture.
  29905. */
  29906. set: function (value) {
  29907. this._imageProcessingConfiguration.colorGradingTexture = value;
  29908. },
  29909. enumerable: true,
  29910. configurable: true
  29911. });
  29912. StandardMaterial.prototype.getClassName = function () {
  29913. return "StandardMaterial";
  29914. };
  29915. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  29916. get: function () {
  29917. return this._useLogarithmicDepth;
  29918. },
  29919. set: function (value) {
  29920. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29921. this._markAllSubMeshesAsMiscDirty();
  29922. },
  29923. enumerable: true,
  29924. configurable: true
  29925. });
  29926. StandardMaterial.prototype.needAlphaBlending = function () {
  29927. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  29928. };
  29929. StandardMaterial.prototype.needAlphaTesting = function () {
  29930. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  29931. };
  29932. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  29933. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  29934. };
  29935. StandardMaterial.prototype.getAlphaTestTexture = function () {
  29936. return this._diffuseTexture;
  29937. };
  29938. /**
  29939. * Child classes can use it to update shaders
  29940. */
  29941. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29942. if (this.isFrozen) {
  29943. if (this._wasPreviouslyReady && subMesh.effect) {
  29944. return true;
  29945. }
  29946. }
  29947. if (!subMesh._materialDefines) {
  29948. subMesh._materialDefines = new StandardMaterialDefines();
  29949. }
  29950. var scene = this.getScene();
  29951. var defines = subMesh._materialDefines;
  29952. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  29953. if (defines._renderId === scene.getRenderId()) {
  29954. return true;
  29955. }
  29956. }
  29957. var engine = scene.getEngine();
  29958. // Lights
  29959. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  29960. // Textures
  29961. if (defines._areTexturesDirty) {
  29962. defines._needUVs = false;
  29963. defines.MAINUV1 = false;
  29964. defines.MAINUV2 = false;
  29965. if (scene.texturesEnabled) {
  29966. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29967. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  29968. return false;
  29969. }
  29970. else {
  29971. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  29972. }
  29973. }
  29974. else {
  29975. defines.DIFFUSE = false;
  29976. }
  29977. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29978. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  29979. return false;
  29980. }
  29981. else {
  29982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  29983. }
  29984. }
  29985. else {
  29986. defines.AMBIENT = false;
  29987. }
  29988. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29989. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  29990. return false;
  29991. }
  29992. else {
  29993. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  29994. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  29995. }
  29996. }
  29997. else {
  29998. defines.OPACITY = false;
  29999. }
  30000. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30001. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30002. return false;
  30003. }
  30004. else {
  30005. defines._needNormals = true;
  30006. defines.REFLECTION = true;
  30007. defines.ROUGHNESS = (this._roughness > 0);
  30008. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30009. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30010. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30011. switch (this._reflectionTexture.coordinatesMode) {
  30012. case BABYLON.Texture.CUBIC_MODE:
  30013. case BABYLON.Texture.INVCUBIC_MODE:
  30014. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30015. break;
  30016. case BABYLON.Texture.EXPLICIT_MODE:
  30017. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30018. break;
  30019. case BABYLON.Texture.PLANAR_MODE:
  30020. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30021. break;
  30022. case BABYLON.Texture.PROJECTION_MODE:
  30023. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30024. break;
  30025. case BABYLON.Texture.SKYBOX_MODE:
  30026. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30027. break;
  30028. case BABYLON.Texture.SPHERICAL_MODE:
  30029. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30030. break;
  30031. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30032. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30033. break;
  30034. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30035. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30036. break;
  30037. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30038. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30039. break;
  30040. }
  30041. }
  30042. }
  30043. else {
  30044. defines.REFLECTION = false;
  30045. }
  30046. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30047. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30048. return false;
  30049. }
  30050. else {
  30051. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30052. }
  30053. }
  30054. else {
  30055. defines.EMISSIVE = false;
  30056. }
  30057. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30058. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30059. return false;
  30060. }
  30061. else {
  30062. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30063. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30064. }
  30065. }
  30066. else {
  30067. defines.LIGHTMAP = false;
  30068. }
  30069. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30070. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30071. return false;
  30072. }
  30073. else {
  30074. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30075. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30076. }
  30077. }
  30078. else {
  30079. defines.SPECULAR = false;
  30080. }
  30081. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30082. // Bump texure can not be not blocking.
  30083. if (!this._bumpTexture.isReady()) {
  30084. return false;
  30085. }
  30086. else {
  30087. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30088. defines.PARALLAX = this._useParallax;
  30089. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30090. }
  30091. }
  30092. else {
  30093. defines.BUMP = false;
  30094. }
  30095. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30096. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30097. return false;
  30098. }
  30099. else {
  30100. defines._needUVs = true;
  30101. defines.REFRACTION = true;
  30102. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30103. }
  30104. }
  30105. else {
  30106. defines.REFRACTION = false;
  30107. }
  30108. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30109. }
  30110. else {
  30111. defines.DIFFUSE = false;
  30112. defines.AMBIENT = false;
  30113. defines.OPACITY = false;
  30114. defines.REFLECTION = false;
  30115. defines.EMISSIVE = false;
  30116. defines.LIGHTMAP = false;
  30117. defines.BUMP = false;
  30118. defines.REFRACTION = false;
  30119. }
  30120. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30121. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30122. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30123. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30124. }
  30125. if (defines._areImageProcessingDirty) {
  30126. if (!this._imageProcessingConfiguration.isReady()) {
  30127. return false;
  30128. }
  30129. this._imageProcessingConfiguration.prepareDefines(defines);
  30130. }
  30131. if (defines._areFresnelDirty) {
  30132. if (StandardMaterial.FresnelEnabled) {
  30133. // Fresnel
  30134. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  30135. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  30136. this._reflectionFresnelParameters) {
  30137. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  30138. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  30139. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  30140. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  30141. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  30142. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  30143. defines._needNormals = true;
  30144. defines.FRESNEL = true;
  30145. }
  30146. }
  30147. else {
  30148. defines.FRESNEL = false;
  30149. }
  30150. }
  30151. // Misc.
  30152. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30153. // Attribs
  30154. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  30155. // Values that need to be evaluated on every frame
  30156. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  30157. // Get correct effect
  30158. if (defines.isDirty) {
  30159. defines.markAsProcessed();
  30160. scene.resetCachedMaterial();
  30161. // Fallbacks
  30162. var fallbacks = new BABYLON.EffectFallbacks();
  30163. if (defines.REFLECTION) {
  30164. fallbacks.addFallback(0, "REFLECTION");
  30165. }
  30166. if (defines.SPECULAR) {
  30167. fallbacks.addFallback(0, "SPECULAR");
  30168. }
  30169. if (defines.BUMP) {
  30170. fallbacks.addFallback(0, "BUMP");
  30171. }
  30172. if (defines.PARALLAX) {
  30173. fallbacks.addFallback(1, "PARALLAX");
  30174. }
  30175. if (defines.PARALLAXOCCLUSION) {
  30176. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30177. }
  30178. if (defines.SPECULAROVERALPHA) {
  30179. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30180. }
  30181. if (defines.FOG) {
  30182. fallbacks.addFallback(1, "FOG");
  30183. }
  30184. if (defines.POINTSIZE) {
  30185. fallbacks.addFallback(0, "POINTSIZE");
  30186. }
  30187. if (defines.LOGARITHMICDEPTH) {
  30188. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30189. }
  30190. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30191. if (defines.SPECULARTERM) {
  30192. fallbacks.addFallback(0, "SPECULARTERM");
  30193. }
  30194. if (defines.DIFFUSEFRESNEL) {
  30195. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30196. }
  30197. if (defines.OPACITYFRESNEL) {
  30198. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30199. }
  30200. if (defines.REFLECTIONFRESNEL) {
  30201. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30202. }
  30203. if (defines.EMISSIVEFRESNEL) {
  30204. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30205. }
  30206. if (defines.FRESNEL) {
  30207. fallbacks.addFallback(4, "FRESNEL");
  30208. }
  30209. //Attributes
  30210. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30211. if (defines.NORMAL) {
  30212. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30213. }
  30214. if (defines.UV1) {
  30215. attribs.push(BABYLON.VertexBuffer.UVKind);
  30216. }
  30217. if (defines.UV2) {
  30218. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30219. }
  30220. if (defines.VERTEXCOLOR) {
  30221. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30222. }
  30223. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30224. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30225. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30226. var shaderName = "default";
  30227. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30228. "vFogInfos", "vFogColor", "pointSize",
  30229. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30230. "mBones",
  30231. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30232. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30233. "logarithmicDepthConstant", "vNormalReoderParams"
  30234. ];
  30235. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30236. var uniformBuffers = ["Material", "Scene"];
  30237. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30238. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30239. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30240. uniformsNames: uniforms,
  30241. uniformBuffersNames: uniformBuffers,
  30242. samplers: samplers,
  30243. defines: defines,
  30244. maxSimultaneousLights: this._maxSimultaneousLights
  30245. });
  30246. if (this.customShaderNameResolve) {
  30247. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  30248. }
  30249. var join = defines.toString();
  30250. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  30251. attributes: attribs,
  30252. uniformsNames: uniforms,
  30253. uniformBuffersNames: uniformBuffers,
  30254. samplers: samplers,
  30255. defines: join,
  30256. fallbacks: fallbacks,
  30257. onCompiled: this.onCompiled,
  30258. onError: this.onError,
  30259. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  30260. }, engine), defines);
  30261. this.buildUniformLayout();
  30262. }
  30263. if (!subMesh.effect.isReady()) {
  30264. return false;
  30265. }
  30266. defines._renderId = scene.getRenderId();
  30267. this._wasPreviouslyReady = true;
  30268. return true;
  30269. };
  30270. StandardMaterial.prototype.buildUniformLayout = function () {
  30271. // Order is important !
  30272. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  30273. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  30274. this._uniformBuffer.addUniform("opacityParts", 4);
  30275. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  30276. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  30277. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  30278. this._uniformBuffer.addUniform("refractionRightColor", 4);
  30279. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30280. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30281. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  30282. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  30283. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30284. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30285. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30286. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30287. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  30288. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30289. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  30290. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30291. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30292. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30293. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30294. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30295. this._uniformBuffer.addUniform("specularMatrix", 16);
  30296. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30297. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  30298. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30299. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30300. this._uniformBuffer.addUniform("vSpecularColor", 4);
  30301. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30302. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  30303. this._uniformBuffer.addUniform("pointSize", 1);
  30304. this._uniformBuffer.create();
  30305. };
  30306. StandardMaterial.prototype.unbind = function () {
  30307. if (this._activeEffect) {
  30308. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30309. this._activeEffect.setTexture("reflection2DSampler", null);
  30310. }
  30311. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30312. this._activeEffect.setTexture("refraction2DSampler", null);
  30313. }
  30314. }
  30315. _super.prototype.unbind.call(this);
  30316. };
  30317. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30318. var scene = this.getScene();
  30319. var defines = subMesh._materialDefines;
  30320. if (!defines) {
  30321. return;
  30322. }
  30323. var effect = subMesh.effect;
  30324. this._activeEffect = effect;
  30325. // Matrices
  30326. this.bindOnlyWorldMatrix(world);
  30327. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  30328. // Bones
  30329. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  30330. if (mustRebind) {
  30331. this._uniformBuffer.bindToEffect(effect, "Material");
  30332. this.bindViewProjection(effect);
  30333. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30334. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  30335. // Fresnel
  30336. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30337. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30338. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30339. }
  30340. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30341. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30342. }
  30343. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30344. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30345. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30346. }
  30347. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30348. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30349. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30350. }
  30351. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30352. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30353. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30354. }
  30355. }
  30356. // Textures
  30357. if (scene.texturesEnabled) {
  30358. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30359. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  30360. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  30361. }
  30362. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30363. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  30364. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  30365. }
  30366. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30367. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30368. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  30369. }
  30370. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30371. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  30372. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  30373. }
  30374. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30375. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30376. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  30377. }
  30378. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30379. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30380. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  30381. }
  30382. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30383. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  30384. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  30385. }
  30386. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30387. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  30388. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  30389. if (scene._mirroredCameraPosition) {
  30390. 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);
  30391. }
  30392. else {
  30393. 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);
  30394. }
  30395. }
  30396. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30397. var depth = 1.0;
  30398. if (!this._refractionTexture.isCube) {
  30399. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30400. if (this._refractionTexture.depth) {
  30401. depth = this._refractionTexture.depth;
  30402. }
  30403. }
  30404. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30405. }
  30406. }
  30407. // Point size
  30408. if (this.pointsCloud) {
  30409. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30410. }
  30411. if (defines.SPECULARTERM) {
  30412. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  30413. }
  30414. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  30415. // Diffuse
  30416. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30417. }
  30418. // Textures
  30419. if (scene.texturesEnabled) {
  30420. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30421. effect.setTexture("diffuseSampler", this._diffuseTexture);
  30422. }
  30423. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30424. effect.setTexture("ambientSampler", this._ambientTexture);
  30425. }
  30426. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30427. effect.setTexture("opacitySampler", this._opacityTexture);
  30428. }
  30429. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30430. if (this._reflectionTexture.isCube) {
  30431. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  30432. }
  30433. else {
  30434. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  30435. }
  30436. }
  30437. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30438. effect.setTexture("emissiveSampler", this._emissiveTexture);
  30439. }
  30440. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30441. effect.setTexture("lightmapSampler", this._lightmapTexture);
  30442. }
  30443. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30444. effect.setTexture("specularSampler", this._specularTexture);
  30445. }
  30446. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30447. effect.setTexture("bumpSampler", this._bumpTexture);
  30448. }
  30449. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30450. var depth = 1.0;
  30451. if (this._refractionTexture.isCube) {
  30452. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  30453. }
  30454. else {
  30455. effect.setTexture("refraction2DSampler", this._refractionTexture);
  30456. }
  30457. }
  30458. }
  30459. // Clip plane
  30460. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  30461. // Colors
  30462. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30463. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  30464. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30465. }
  30466. if (mustRebind || !this.isFrozen) {
  30467. // Lights
  30468. if (scene.lightsEnabled && !this._disableLighting) {
  30469. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  30470. }
  30471. // View
  30472. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  30473. this.bindView(effect);
  30474. }
  30475. // Fog
  30476. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  30477. // Morph targets
  30478. if (defines.NUM_MORPH_INFLUENCERS) {
  30479. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  30480. }
  30481. // Log. depth
  30482. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  30483. // image processing
  30484. this._imageProcessingConfiguration.bind(this._activeEffect);
  30485. }
  30486. this._uniformBuffer.update();
  30487. this._afterBind(mesh, this._activeEffect);
  30488. };
  30489. StandardMaterial.prototype.getAnimatables = function () {
  30490. var results = [];
  30491. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  30492. results.push(this._diffuseTexture);
  30493. }
  30494. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30495. results.push(this._ambientTexture);
  30496. }
  30497. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30498. results.push(this._opacityTexture);
  30499. }
  30500. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30501. results.push(this._reflectionTexture);
  30502. }
  30503. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30504. results.push(this._emissiveTexture);
  30505. }
  30506. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  30507. results.push(this._specularTexture);
  30508. }
  30509. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30510. results.push(this._bumpTexture);
  30511. }
  30512. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30513. results.push(this._lightmapTexture);
  30514. }
  30515. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30516. results.push(this._refractionTexture);
  30517. }
  30518. return results;
  30519. };
  30520. StandardMaterial.prototype.getActiveTextures = function () {
  30521. var activeTextures = _super.prototype.getActiveTextures.call(this);
  30522. if (this._diffuseTexture) {
  30523. activeTextures.push(this._diffuseTexture);
  30524. }
  30525. if (this._ambientTexture) {
  30526. activeTextures.push(this._ambientTexture);
  30527. }
  30528. if (this._opacityTexture) {
  30529. activeTextures.push(this._opacityTexture);
  30530. }
  30531. if (this._reflectionTexture) {
  30532. activeTextures.push(this._reflectionTexture);
  30533. }
  30534. if (this._emissiveTexture) {
  30535. activeTextures.push(this._emissiveTexture);
  30536. }
  30537. if (this._specularTexture) {
  30538. activeTextures.push(this._specularTexture);
  30539. }
  30540. if (this._bumpTexture) {
  30541. activeTextures.push(this._bumpTexture);
  30542. }
  30543. if (this._lightmapTexture) {
  30544. activeTextures.push(this._lightmapTexture);
  30545. }
  30546. if (this._refractionTexture) {
  30547. activeTextures.push(this._refractionTexture);
  30548. }
  30549. return activeTextures;
  30550. };
  30551. StandardMaterial.prototype.hasTexture = function (texture) {
  30552. if (_super.prototype.hasTexture.call(this, texture)) {
  30553. return true;
  30554. }
  30555. if (this._diffuseTexture === texture) {
  30556. return true;
  30557. }
  30558. if (this._ambientTexture === texture) {
  30559. return true;
  30560. }
  30561. if (this._opacityTexture === texture) {
  30562. return true;
  30563. }
  30564. if (this._reflectionTexture === texture) {
  30565. return true;
  30566. }
  30567. if (this._emissiveTexture === texture) {
  30568. return true;
  30569. }
  30570. if (this._specularTexture === texture) {
  30571. return true;
  30572. }
  30573. if (this._bumpTexture === texture) {
  30574. return true;
  30575. }
  30576. if (this._lightmapTexture === texture) {
  30577. return true;
  30578. }
  30579. if (this._refractionTexture === texture) {
  30580. return true;
  30581. }
  30582. return false;
  30583. };
  30584. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30585. if (forceDisposeTextures) {
  30586. if (this._diffuseTexture) {
  30587. this._diffuseTexture.dispose();
  30588. }
  30589. if (this._ambientTexture) {
  30590. this._ambientTexture.dispose();
  30591. }
  30592. if (this._opacityTexture) {
  30593. this._opacityTexture.dispose();
  30594. }
  30595. if (this._reflectionTexture) {
  30596. this._reflectionTexture.dispose();
  30597. }
  30598. if (this._emissiveTexture) {
  30599. this._emissiveTexture.dispose();
  30600. }
  30601. if (this._specularTexture) {
  30602. this._specularTexture.dispose();
  30603. }
  30604. if (this._bumpTexture) {
  30605. this._bumpTexture.dispose();
  30606. }
  30607. if (this._lightmapTexture) {
  30608. this._lightmapTexture.dispose();
  30609. }
  30610. if (this._refractionTexture) {
  30611. this._refractionTexture.dispose();
  30612. }
  30613. }
  30614. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30615. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30616. }
  30617. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30618. };
  30619. StandardMaterial.prototype.clone = function (name) {
  30620. var _this = this;
  30621. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30622. result.name = name;
  30623. result.id = name;
  30624. return result;
  30625. };
  30626. StandardMaterial.prototype.serialize = function () {
  30627. return BABYLON.SerializationHelper.Serialize(this);
  30628. };
  30629. // Statics
  30630. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30631. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30632. };
  30633. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  30634. get: function () {
  30635. return StandardMaterial._DiffuseTextureEnabled;
  30636. },
  30637. set: function (value) {
  30638. if (StandardMaterial._DiffuseTextureEnabled === value) {
  30639. return;
  30640. }
  30641. StandardMaterial._DiffuseTextureEnabled = value;
  30642. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30643. },
  30644. enumerable: true,
  30645. configurable: true
  30646. });
  30647. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  30648. get: function () {
  30649. return StandardMaterial._AmbientTextureEnabled;
  30650. },
  30651. set: function (value) {
  30652. if (StandardMaterial._AmbientTextureEnabled === value) {
  30653. return;
  30654. }
  30655. StandardMaterial._AmbientTextureEnabled = value;
  30656. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30657. },
  30658. enumerable: true,
  30659. configurable: true
  30660. });
  30661. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  30662. get: function () {
  30663. return StandardMaterial._OpacityTextureEnabled;
  30664. },
  30665. set: function (value) {
  30666. if (StandardMaterial._OpacityTextureEnabled === value) {
  30667. return;
  30668. }
  30669. StandardMaterial._OpacityTextureEnabled = value;
  30670. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30671. },
  30672. enumerable: true,
  30673. configurable: true
  30674. });
  30675. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  30676. get: function () {
  30677. return StandardMaterial._ReflectionTextureEnabled;
  30678. },
  30679. set: function (value) {
  30680. if (StandardMaterial._ReflectionTextureEnabled === value) {
  30681. return;
  30682. }
  30683. StandardMaterial._ReflectionTextureEnabled = value;
  30684. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30685. },
  30686. enumerable: true,
  30687. configurable: true
  30688. });
  30689. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  30690. get: function () {
  30691. return StandardMaterial._EmissiveTextureEnabled;
  30692. },
  30693. set: function (value) {
  30694. if (StandardMaterial._EmissiveTextureEnabled === value) {
  30695. return;
  30696. }
  30697. StandardMaterial._EmissiveTextureEnabled = value;
  30698. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30699. },
  30700. enumerable: true,
  30701. configurable: true
  30702. });
  30703. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  30704. get: function () {
  30705. return StandardMaterial._SpecularTextureEnabled;
  30706. },
  30707. set: function (value) {
  30708. if (StandardMaterial._SpecularTextureEnabled === value) {
  30709. return;
  30710. }
  30711. StandardMaterial._SpecularTextureEnabled = value;
  30712. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30713. },
  30714. enumerable: true,
  30715. configurable: true
  30716. });
  30717. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  30718. get: function () {
  30719. return StandardMaterial._BumpTextureEnabled;
  30720. },
  30721. set: function (value) {
  30722. if (StandardMaterial._BumpTextureEnabled === value) {
  30723. return;
  30724. }
  30725. StandardMaterial._BumpTextureEnabled = value;
  30726. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30727. },
  30728. enumerable: true,
  30729. configurable: true
  30730. });
  30731. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  30732. get: function () {
  30733. return StandardMaterial._LightmapTextureEnabled;
  30734. },
  30735. set: function (value) {
  30736. if (StandardMaterial._LightmapTextureEnabled === value) {
  30737. return;
  30738. }
  30739. StandardMaterial._LightmapTextureEnabled = value;
  30740. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30741. },
  30742. enumerable: true,
  30743. configurable: true
  30744. });
  30745. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  30746. get: function () {
  30747. return StandardMaterial._RefractionTextureEnabled;
  30748. },
  30749. set: function (value) {
  30750. if (StandardMaterial._RefractionTextureEnabled === value) {
  30751. return;
  30752. }
  30753. StandardMaterial._RefractionTextureEnabled = value;
  30754. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30755. },
  30756. enumerable: true,
  30757. configurable: true
  30758. });
  30759. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  30760. get: function () {
  30761. return StandardMaterial._ColorGradingTextureEnabled;
  30762. },
  30763. set: function (value) {
  30764. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  30765. return;
  30766. }
  30767. StandardMaterial._ColorGradingTextureEnabled = value;
  30768. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30769. },
  30770. enumerable: true,
  30771. configurable: true
  30772. });
  30773. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  30774. get: function () {
  30775. return StandardMaterial._FresnelEnabled;
  30776. },
  30777. set: function (value) {
  30778. if (StandardMaterial._FresnelEnabled === value) {
  30779. return;
  30780. }
  30781. StandardMaterial._FresnelEnabled = value;
  30782. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  30783. },
  30784. enumerable: true,
  30785. configurable: true
  30786. });
  30787. // Flags used to enable or disable a type of texture for all Standard Materials
  30788. StandardMaterial._DiffuseTextureEnabled = true;
  30789. StandardMaterial._AmbientTextureEnabled = true;
  30790. StandardMaterial._OpacityTextureEnabled = true;
  30791. StandardMaterial._ReflectionTextureEnabled = true;
  30792. StandardMaterial._EmissiveTextureEnabled = true;
  30793. StandardMaterial._SpecularTextureEnabled = true;
  30794. StandardMaterial._BumpTextureEnabled = true;
  30795. StandardMaterial._LightmapTextureEnabled = true;
  30796. StandardMaterial._RefractionTextureEnabled = true;
  30797. StandardMaterial._ColorGradingTextureEnabled = true;
  30798. StandardMaterial._FresnelEnabled = true;
  30799. __decorate([
  30800. BABYLON.serializeAsTexture("diffuseTexture")
  30801. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  30802. __decorate([
  30803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30804. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30805. __decorate([
  30806. BABYLON.serializeAsTexture("ambientTexture")
  30807. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  30808. __decorate([
  30809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30810. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30811. __decorate([
  30812. BABYLON.serializeAsTexture("opacityTexture")
  30813. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  30814. __decorate([
  30815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30816. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30817. __decorate([
  30818. BABYLON.serializeAsTexture("reflectionTexture")
  30819. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  30820. __decorate([
  30821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30822. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30823. __decorate([
  30824. BABYLON.serializeAsTexture("emissiveTexture")
  30825. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  30826. __decorate([
  30827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30828. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30829. __decorate([
  30830. BABYLON.serializeAsTexture("specularTexture")
  30831. ], StandardMaterial.prototype, "_specularTexture", void 0);
  30832. __decorate([
  30833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30834. ], StandardMaterial.prototype, "specularTexture", void 0);
  30835. __decorate([
  30836. BABYLON.serializeAsTexture("bumpTexture")
  30837. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  30838. __decorate([
  30839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30840. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30841. __decorate([
  30842. BABYLON.serializeAsTexture("lightmapTexture")
  30843. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  30844. __decorate([
  30845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30846. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30847. __decorate([
  30848. BABYLON.serializeAsTexture("refractionTexture")
  30849. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  30850. __decorate([
  30851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30852. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30853. __decorate([
  30854. BABYLON.serializeAsColor3("ambient")
  30855. ], StandardMaterial.prototype, "ambientColor", void 0);
  30856. __decorate([
  30857. BABYLON.serializeAsColor3("diffuse")
  30858. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30859. __decorate([
  30860. BABYLON.serializeAsColor3("specular")
  30861. ], StandardMaterial.prototype, "specularColor", void 0);
  30862. __decorate([
  30863. BABYLON.serializeAsColor3("emissive")
  30864. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30865. __decorate([
  30866. BABYLON.serialize()
  30867. ], StandardMaterial.prototype, "specularPower", void 0);
  30868. __decorate([
  30869. BABYLON.serialize("useAlphaFromDiffuseTexture")
  30870. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  30871. __decorate([
  30872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30873. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30874. __decorate([
  30875. BABYLON.serialize("useEmissiveAsIllumination")
  30876. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  30877. __decorate([
  30878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30879. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30880. __decorate([
  30881. BABYLON.serialize("linkEmissiveWithDiffuse")
  30882. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  30883. __decorate([
  30884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30885. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30886. __decorate([
  30887. BABYLON.serialize("useSpecularOverAlpha")
  30888. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  30889. __decorate([
  30890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30891. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30892. __decorate([
  30893. BABYLON.serialize("useReflectionOverAlpha")
  30894. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  30895. __decorate([
  30896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30897. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30898. __decorate([
  30899. BABYLON.serialize("disableLighting")
  30900. ], StandardMaterial.prototype, "_disableLighting", void 0);
  30901. __decorate([
  30902. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30903. ], StandardMaterial.prototype, "disableLighting", void 0);
  30904. __decorate([
  30905. BABYLON.serialize("useParallax")
  30906. ], StandardMaterial.prototype, "_useParallax", void 0);
  30907. __decorate([
  30908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30909. ], StandardMaterial.prototype, "useParallax", void 0);
  30910. __decorate([
  30911. BABYLON.serialize("useParallaxOcclusion")
  30912. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  30913. __decorate([
  30914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30915. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30916. __decorate([
  30917. BABYLON.serialize()
  30918. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30919. __decorate([
  30920. BABYLON.serialize("roughness")
  30921. ], StandardMaterial.prototype, "_roughness", void 0);
  30922. __decorate([
  30923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30924. ], StandardMaterial.prototype, "roughness", void 0);
  30925. __decorate([
  30926. BABYLON.serialize()
  30927. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30928. __decorate([
  30929. BABYLON.serialize()
  30930. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30931. __decorate([
  30932. BABYLON.serialize("useLightmapAsShadowmap")
  30933. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  30934. __decorate([
  30935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30936. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30937. __decorate([
  30938. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  30939. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  30940. __decorate([
  30941. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30942. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30943. __decorate([
  30944. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  30945. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  30946. __decorate([
  30947. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30948. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30949. __decorate([
  30950. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  30951. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  30952. __decorate([
  30953. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30954. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30955. __decorate([
  30956. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  30957. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  30958. __decorate([
  30959. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30960. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30961. __decorate([
  30962. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  30963. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  30964. __decorate([
  30965. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30966. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30967. __decorate([
  30968. BABYLON.serialize("useReflectionFresnelFromSpecular")
  30969. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  30970. __decorate([
  30971. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  30972. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30973. __decorate([
  30974. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  30975. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  30976. __decorate([
  30977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30978. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30979. __decorate([
  30980. BABYLON.serialize("maxSimultaneousLights")
  30981. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  30982. __decorate([
  30983. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  30984. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30985. __decorate([
  30986. BABYLON.serialize("invertNormalMapX")
  30987. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  30988. __decorate([
  30989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30990. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30991. __decorate([
  30992. BABYLON.serialize("invertNormalMapY")
  30993. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  30994. __decorate([
  30995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  30996. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30997. __decorate([
  30998. BABYLON.serialize("twoSidedLighting")
  30999. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31000. __decorate([
  31001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31002. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31003. __decorate([
  31004. BABYLON.serialize()
  31005. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31006. return StandardMaterial;
  31007. }(BABYLON.PushMaterial));
  31008. BABYLON.StandardMaterial = StandardMaterial;
  31009. })(BABYLON || (BABYLON = {}));
  31010. //# sourceMappingURL=babylon.standardMaterial.js.map
  31011. var BABYLON;
  31012. (function (BABYLON) {
  31013. var PBRMaterialDefines = (function (_super) {
  31014. __extends(PBRMaterialDefines, _super);
  31015. function PBRMaterialDefines() {
  31016. var _this = _super.call(this) || this;
  31017. _this.PBR = true;
  31018. _this.MAINUV1 = false;
  31019. _this.MAINUV2 = false;
  31020. _this.UV1 = false;
  31021. _this.UV2 = false;
  31022. _this.ALBEDO = false;
  31023. _this.ALBEDODIRECTUV = 0;
  31024. _this.VERTEXCOLOR = false;
  31025. _this.AMBIENT = false;
  31026. _this.AMBIENTDIRECTUV = 0;
  31027. _this.AMBIENTINGRAYSCALE = false;
  31028. _this.OPACITY = false;
  31029. _this.VERTEXALPHA = false;
  31030. _this.OPACITYDIRECTUV = 0;
  31031. _this.OPACITYRGB = false;
  31032. _this.ALPHATEST = false;
  31033. _this.ALPHABLEND = false;
  31034. _this.ALPHAFROMALBEDO = false;
  31035. _this.ALPHATESTVALUE = 0.5;
  31036. _this.SPECULAROVERALPHA = false;
  31037. _this.RADIANCEOVERALPHA = false;
  31038. _this.ALPHAFRESNEL = false;
  31039. _this.PREMULTIPLYALPHA = false;
  31040. _this.EMISSIVE = false;
  31041. _this.EMISSIVEDIRECTUV = 0;
  31042. _this.REFLECTIVITY = false;
  31043. _this.REFLECTIVITYDIRECTUV = 0;
  31044. _this.SPECULARTERM = false;
  31045. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31046. _this.MICROSURFACEAUTOMATIC = false;
  31047. _this.LODBASEDMICROSFURACE = false;
  31048. _this.MICROSURFACEMAP = false;
  31049. _this.MICROSURFACEMAPDIRECTUV = 0;
  31050. _this.METALLICWORKFLOW = false;
  31051. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31052. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31053. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31054. _this.AOSTOREINMETALMAPRED = false;
  31055. _this.ENVIRONMENTBRDF = false;
  31056. _this.NORMAL = false;
  31057. _this.TANGENT = false;
  31058. _this.BUMP = false;
  31059. _this.BUMPDIRECTUV = 0;
  31060. _this.PARALLAX = false;
  31061. _this.PARALLAXOCCLUSION = false;
  31062. _this.NORMALXYSCALE = true;
  31063. _this.LIGHTMAP = false;
  31064. _this.LIGHTMAPDIRECTUV = 0;
  31065. _this.USELIGHTMAPASSHADOWMAP = false;
  31066. _this.REFLECTION = false;
  31067. _this.REFLECTIONMAP_3D = false;
  31068. _this.REFLECTIONMAP_SPHERICAL = false;
  31069. _this.REFLECTIONMAP_PLANAR = false;
  31070. _this.REFLECTIONMAP_CUBIC = false;
  31071. _this.REFLECTIONMAP_PROJECTION = false;
  31072. _this.REFLECTIONMAP_SKYBOX = false;
  31073. _this.REFLECTIONMAP_EXPLICIT = false;
  31074. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31075. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31076. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31077. _this.INVERTCUBICMAP = false;
  31078. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31079. _this.USESPHERICALINFRAGMENT = false;
  31080. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31081. _this.LODINREFLECTIONALPHA = false;
  31082. _this.GAMMAREFLECTION = false;
  31083. _this.REFRACTION = false;
  31084. _this.REFRACTIONMAP_3D = false;
  31085. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31086. _this.LODINREFRACTIONALPHA = false;
  31087. _this.GAMMAREFRACTION = false;
  31088. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31089. _this.INSTANCES = false;
  31090. _this.NUM_BONE_INFLUENCERS = 0;
  31091. _this.BonesPerMesh = 0;
  31092. _this.MORPHTARGETS = false;
  31093. _this.MORPHTARGETS_NORMAL = false;
  31094. _this.MORPHTARGETS_TANGENT = false;
  31095. _this.NUM_MORPH_INFLUENCERS = 0;
  31096. _this.IMAGEPROCESSING = false;
  31097. _this.VIGNETTE = false;
  31098. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  31099. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31100. _this.TONEMAPPING = false;
  31101. _this.CONTRAST = false;
  31102. _this.COLORCURVES = false;
  31103. _this.COLORGRADING = false;
  31104. _this.SAMPLER3DGREENDEPTH = false;
  31105. _this.SAMPLER3DBGRMAP = false;
  31106. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31107. _this.EXPOSURE = false;
  31108. _this.USEPHYSICALLIGHTFALLOFF = false;
  31109. _this.TWOSIDEDLIGHTING = false;
  31110. _this.SHADOWFLOAT = false;
  31111. _this.USERIGHTHANDEDSYSTEM = false;
  31112. _this.CLIPPLANE = false;
  31113. _this.POINTSIZE = false;
  31114. _this.FOG = false;
  31115. _this.LOGARITHMICDEPTH = false;
  31116. _this.FORCENORMALFORWARD = false;
  31117. _this.rebuild();
  31118. return _this;
  31119. }
  31120. PBRMaterialDefines.prototype.reset = function () {
  31121. _super.prototype.reset.call(this);
  31122. this.ALPHATESTVALUE = 0.5;
  31123. this.PBR = true;
  31124. };
  31125. return PBRMaterialDefines;
  31126. }(BABYLON.MaterialDefines));
  31127. /**
  31128. * The Physically based material base class of BJS.
  31129. *
  31130. * This offers the main features of a standard PBR material.
  31131. * For more information, please refer to the documentation :
  31132. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31133. */
  31134. var PBRBaseMaterial = (function (_super) {
  31135. __extends(PBRBaseMaterial, _super);
  31136. /**
  31137. * Instantiates a new PBRMaterial instance.
  31138. *
  31139. * @param name The material name
  31140. * @param scene The scene the material will be use in.
  31141. */
  31142. function PBRBaseMaterial(name, scene) {
  31143. var _this = _super.call(this, name, scene) || this;
  31144. /**
  31145. * Intensity of the direct lights e.g. the four lights available in your scene.
  31146. * This impacts both the direct diffuse and specular highlights.
  31147. */
  31148. _this._directIntensity = 1.0;
  31149. /**
  31150. * Intensity of the emissive part of the material.
  31151. * This helps controlling the emissive effect without modifying the emissive color.
  31152. */
  31153. _this._emissiveIntensity = 1.0;
  31154. /**
  31155. * Intensity of the environment e.g. how much the environment will light the object
  31156. * either through harmonics for rough material or through the refelction for shiny ones.
  31157. */
  31158. _this._environmentIntensity = 1.0;
  31159. /**
  31160. * This is a special control allowing the reduction of the specular highlights coming from the
  31161. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31162. */
  31163. _this._specularIntensity = 1.0;
  31164. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  31165. /**
  31166. * Debug Control allowing disabling the bump map on this material.
  31167. */
  31168. _this._disableBumpMap = false;
  31169. /**
  31170. * AKA Occlusion Texture Intensity in other nomenclature.
  31171. */
  31172. _this._ambientTextureStrength = 1.0;
  31173. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  31174. /**
  31175. * AKA Diffuse Color in other nomenclature.
  31176. */
  31177. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  31178. /**
  31179. * AKA Specular Color in other nomenclature.
  31180. */
  31181. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31182. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  31183. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  31184. /**
  31185. * AKA Glossiness in other nomenclature.
  31186. */
  31187. _this._microSurface = 0.9;
  31188. /**
  31189. * source material index of refraction (IOR)' / 'destination material IOR.
  31190. */
  31191. _this._indexOfRefraction = 0.66;
  31192. /**
  31193. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31194. */
  31195. _this._invertRefractionY = false;
  31196. /**
  31197. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31198. * Materials half opaque for instance using refraction could benefit from this control.
  31199. */
  31200. _this._linkRefractionWithTransparency = false;
  31201. _this._useLightmapAsShadowmap = false;
  31202. /**
  31203. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31204. */
  31205. _this._useAlphaFromAlbedoTexture = false;
  31206. /**
  31207. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31208. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31209. */
  31210. _this._useSpecularOverAlpha = true;
  31211. /**
  31212. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31213. */
  31214. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  31215. /**
  31216. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31217. */
  31218. _this._useRoughnessFromMetallicTextureAlpha = true;
  31219. /**
  31220. * Specifies if the metallic texture contains the roughness information in its green channel.
  31221. */
  31222. _this._useRoughnessFromMetallicTextureGreen = false;
  31223. /**
  31224. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31225. */
  31226. _this._useMetallnessFromMetallicTextureBlue = false;
  31227. /**
  31228. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31229. */
  31230. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  31231. /**
  31232. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31233. */
  31234. _this._useAmbientInGrayScale = false;
  31235. /**
  31236. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31237. * The material will try to infer what glossiness each pixel should be.
  31238. */
  31239. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  31240. /**
  31241. * BJS is using an harcoded light falloff based on a manually sets up range.
  31242. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31243. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31244. */
  31245. _this._usePhysicalLightFalloff = true;
  31246. /**
  31247. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31248. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31249. */
  31250. _this._useRadianceOverAlpha = true;
  31251. /**
  31252. * Allows using the bump map in parallax mode.
  31253. */
  31254. _this._useParallax = false;
  31255. /**
  31256. * Allows using the bump map in parallax occlusion mode.
  31257. */
  31258. _this._useParallaxOcclusion = false;
  31259. /**
  31260. * Controls the scale bias of the parallax mode.
  31261. */
  31262. _this._parallaxScaleBias = 0.05;
  31263. /**
  31264. * If sets to true, disables all the lights affecting the material.
  31265. */
  31266. _this._disableLighting = false;
  31267. /**
  31268. * Number of Simultaneous lights allowed on the material.
  31269. */
  31270. _this._maxSimultaneousLights = 4;
  31271. /**
  31272. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  31273. */
  31274. _this._invertNormalMapX = false;
  31275. /**
  31276. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  31277. */
  31278. _this._invertNormalMapY = false;
  31279. /**
  31280. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31281. */
  31282. _this._twoSidedLighting = false;
  31283. /**
  31284. * Defines the alpha limits in alpha test mode.
  31285. */
  31286. _this._alphaCutOff = 0.4;
  31287. /**
  31288. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  31289. */
  31290. _this._forceAlphaTest = false;
  31291. /**
  31292. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31293. * in your scene composition.
  31294. */
  31295. _this._preMultiplyAlpha = false;
  31296. /**
  31297. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31298. * And/Or occlude the blended part.
  31299. */
  31300. _this._useAlphaFresnel = false;
  31301. /**
  31302. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  31303. * from cos thetav and roughness:
  31304. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  31305. */
  31306. _this._environmentBRDFTexture = null;
  31307. /**
  31308. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  31309. */
  31310. _this._forceIrradianceInFragment = false;
  31311. /**
  31312. * Force normal to face away from face.
  31313. * (Temporary internal fix to remove before 3.1)
  31314. */
  31315. _this._forceNormalForward = false;
  31316. _this._renderTargets = new BABYLON.SmartArray(16);
  31317. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  31318. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  31319. _this._tempColor = new BABYLON.Color3();
  31320. // Setup the default processing configuration to the scene.
  31321. _this._attachImageProcessingConfiguration(null);
  31322. _this.getRenderTargetTextures = function () {
  31323. _this._renderTargets.reset();
  31324. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  31325. _this._renderTargets.push(_this._reflectionTexture);
  31326. }
  31327. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  31328. _this._renderTargets.push(_this._refractionTexture);
  31329. }
  31330. return _this._renderTargets;
  31331. };
  31332. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  31333. return _this;
  31334. }
  31335. /**
  31336. * Attaches a new image processing configuration to the PBR Material.
  31337. * @param configuration
  31338. */
  31339. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  31340. var _this = this;
  31341. if (configuration === this._imageProcessingConfiguration) {
  31342. return;
  31343. }
  31344. // Detaches observer.
  31345. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31346. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31347. }
  31348. // Pick the scene configuration if needed.
  31349. if (!configuration) {
  31350. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  31351. }
  31352. else {
  31353. this._imageProcessingConfiguration = configuration;
  31354. }
  31355. // Attaches observer.
  31356. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  31357. _this._markAllSubMeshesAsImageProcessingDirty();
  31358. });
  31359. };
  31360. PBRBaseMaterial.prototype.getClassName = function () {
  31361. return "PBRBaseMaterial";
  31362. };
  31363. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  31364. get: function () {
  31365. return this._useLogarithmicDepth;
  31366. },
  31367. set: function (value) {
  31368. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  31369. },
  31370. enumerable: true,
  31371. configurable: true
  31372. });
  31373. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  31374. if (this._linkRefractionWithTransparency) {
  31375. return false;
  31376. }
  31377. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  31378. };
  31379. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  31380. if (this._forceAlphaTest) {
  31381. return true;
  31382. }
  31383. if (this._linkRefractionWithTransparency) {
  31384. return false;
  31385. }
  31386. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  31387. };
  31388. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  31389. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  31390. };
  31391. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  31392. return this._albedoTexture;
  31393. };
  31394. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31395. if (this.isFrozen) {
  31396. if (this._wasPreviouslyReady) {
  31397. return true;
  31398. }
  31399. }
  31400. if (!subMesh._materialDefines) {
  31401. subMesh._materialDefines = new PBRMaterialDefines();
  31402. }
  31403. var scene = this.getScene();
  31404. var defines = subMesh._materialDefines;
  31405. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31406. if (defines._renderId === scene.getRenderId()) {
  31407. return true;
  31408. }
  31409. }
  31410. var engine = scene.getEngine();
  31411. // Lights
  31412. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  31413. defines._needNormals = true;
  31414. // Textures
  31415. if (defines._areTexturesDirty) {
  31416. defines._needUVs = false;
  31417. if (scene.texturesEnabled) {
  31418. if (scene.getEngine().getCaps().textureLOD) {
  31419. defines.LODBASEDMICROSFURACE = true;
  31420. }
  31421. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31422. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  31423. return false;
  31424. }
  31425. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  31426. }
  31427. else {
  31428. defines.ALBEDO = false;
  31429. }
  31430. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31431. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  31432. return false;
  31433. }
  31434. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  31435. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  31436. }
  31437. else {
  31438. defines.AMBIENT = false;
  31439. }
  31440. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31441. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  31442. return false;
  31443. }
  31444. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  31445. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31446. }
  31447. else {
  31448. defines.OPACITY = false;
  31449. }
  31450. var reflectionTexture = this._getReflectionTexture();
  31451. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31452. if (!reflectionTexture.isReadyOrNotBlocking()) {
  31453. return false;
  31454. }
  31455. defines.REFLECTION = true;
  31456. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  31457. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  31458. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31459. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  31460. defines.INVERTCUBICMAP = true;
  31461. }
  31462. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  31463. switch (reflectionTexture.coordinatesMode) {
  31464. case BABYLON.Texture.CUBIC_MODE:
  31465. case BABYLON.Texture.INVCUBIC_MODE:
  31466. defines.REFLECTIONMAP_CUBIC = true;
  31467. break;
  31468. case BABYLON.Texture.EXPLICIT_MODE:
  31469. defines.REFLECTIONMAP_EXPLICIT = true;
  31470. break;
  31471. case BABYLON.Texture.PLANAR_MODE:
  31472. defines.REFLECTIONMAP_PLANAR = true;
  31473. break;
  31474. case BABYLON.Texture.PROJECTION_MODE:
  31475. defines.REFLECTIONMAP_PROJECTION = true;
  31476. break;
  31477. case BABYLON.Texture.SKYBOX_MODE:
  31478. defines.REFLECTIONMAP_SKYBOX = true;
  31479. break;
  31480. case BABYLON.Texture.SPHERICAL_MODE:
  31481. defines.REFLECTIONMAP_SPHERICAL = true;
  31482. break;
  31483. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31484. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  31485. break;
  31486. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31487. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  31488. break;
  31489. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31490. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  31491. break;
  31492. }
  31493. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  31494. if (reflectionTexture.sphericalPolynomial) {
  31495. defines.USESPHERICALFROMREFLECTIONMAP = true;
  31496. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  31497. defines.USESPHERICALINFRAGMENT = true;
  31498. }
  31499. }
  31500. }
  31501. }
  31502. else {
  31503. defines.REFLECTION = false;
  31504. defines.REFLECTIONMAP_3D = false;
  31505. defines.REFLECTIONMAP_SPHERICAL = false;
  31506. defines.REFLECTIONMAP_PLANAR = false;
  31507. defines.REFLECTIONMAP_CUBIC = false;
  31508. defines.REFLECTIONMAP_PROJECTION = false;
  31509. defines.REFLECTIONMAP_SKYBOX = false;
  31510. defines.REFLECTIONMAP_EXPLICIT = false;
  31511. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31512. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31513. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31514. defines.INVERTCUBICMAP = false;
  31515. defines.USESPHERICALFROMREFLECTIONMAP = false;
  31516. defines.USESPHERICALINFRAGMENT = false;
  31517. defines.REFLECTIONMAP_OPPOSITEZ = false;
  31518. defines.LODINREFLECTIONALPHA = false;
  31519. defines.GAMMAREFLECTION = false;
  31520. }
  31521. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31522. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  31523. return false;
  31524. }
  31525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  31526. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31527. }
  31528. else {
  31529. defines.LIGHTMAP = false;
  31530. }
  31531. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31532. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  31533. return false;
  31534. }
  31535. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  31536. }
  31537. else {
  31538. defines.EMISSIVE = false;
  31539. }
  31540. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31541. if (this._metallicTexture) {
  31542. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  31543. return false;
  31544. }
  31545. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  31546. defines.METALLICWORKFLOW = true;
  31547. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  31548. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  31549. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  31550. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  31551. }
  31552. else if (this._reflectivityTexture) {
  31553. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  31554. return false;
  31555. }
  31556. defines.METALLICWORKFLOW = false;
  31557. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  31558. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  31559. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  31560. }
  31561. else {
  31562. defines.METALLICWORKFLOW = false;
  31563. defines.REFLECTIVITY = false;
  31564. }
  31565. if (this._microSurfaceTexture) {
  31566. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  31567. return false;
  31568. }
  31569. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  31570. }
  31571. else {
  31572. defines.MICROSURFACEMAP = false;
  31573. }
  31574. }
  31575. else {
  31576. defines.REFLECTIVITY = false;
  31577. defines.MICROSURFACEMAP = false;
  31578. }
  31579. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31580. // Bump texure can not be none blocking.
  31581. if (!this._bumpTexture.isReady()) {
  31582. return false;
  31583. }
  31584. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  31585. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31586. defines.PARALLAX = true;
  31587. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  31588. }
  31589. else {
  31590. defines.PARALLAX = false;
  31591. }
  31592. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  31593. }
  31594. else {
  31595. defines.BUMP = false;
  31596. }
  31597. var refractionTexture = this._getRefractionTexture();
  31598. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31599. if (!refractionTexture.isReadyOrNotBlocking()) {
  31600. return false;
  31601. }
  31602. defines.REFRACTION = true;
  31603. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  31604. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  31605. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  31606. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31607. if (this._linkRefractionWithTransparency) {
  31608. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  31609. }
  31610. }
  31611. else {
  31612. defines.REFRACTION = false;
  31613. }
  31614. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31615. // This is blocking.
  31616. if (!this._environmentBRDFTexture.isReady()) {
  31617. return false;
  31618. }
  31619. defines.ENVIRONMENTBRDF = true;
  31620. }
  31621. if (this._shouldUseAlphaFromAlbedoTexture()) {
  31622. defines.ALPHAFROMALBEDO = true;
  31623. }
  31624. }
  31625. if (this._useSpecularOverAlpha) {
  31626. defines.SPECULAROVERALPHA = true;
  31627. }
  31628. if (this._usePhysicalLightFalloff) {
  31629. defines.USEPHYSICALLIGHTFALLOFF = true;
  31630. }
  31631. if (this._useRadianceOverAlpha) {
  31632. defines.RADIANCEOVERALPHA = true;
  31633. }
  31634. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  31635. defines.METALLICWORKFLOW = true;
  31636. }
  31637. if (!this.backFaceCulling && this._twoSidedLighting) {
  31638. defines.TWOSIDEDLIGHTING = true;
  31639. }
  31640. defines.ALPHATESTVALUE = this._alphaCutOff;
  31641. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  31642. defines.ALPHABLEND = this.needAlphaBlending();
  31643. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  31644. }
  31645. if (defines._areImageProcessingDirty) {
  31646. if (!this._imageProcessingConfiguration.isReady()) {
  31647. return false;
  31648. }
  31649. this._imageProcessingConfiguration.prepareDefines(defines);
  31650. }
  31651. defines.FORCENORMALFORWARD = this._forceNormalForward;
  31652. // Misc.
  31653. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31654. // Values that need to be evaluated on every frame
  31655. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  31656. // Attribs
  31657. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  31658. if (mesh) {
  31659. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31660. mesh.createNormals(true);
  31661. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  31662. }
  31663. }
  31664. }
  31665. // Get correct effect
  31666. if (defines.isDirty) {
  31667. defines.markAsProcessed();
  31668. scene.resetCachedMaterial();
  31669. // Fallbacks
  31670. var fallbacks = new BABYLON.EffectFallbacks();
  31671. if (defines.ENVIRONMENTBRDF) {
  31672. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  31673. }
  31674. if (defines.REFLECTION) {
  31675. fallbacks.addFallback(0, "REFLECTION");
  31676. }
  31677. if (defines.REFRACTION) {
  31678. fallbacks.addFallback(0, "REFRACTION");
  31679. }
  31680. if (defines.REFLECTIVITY) {
  31681. fallbacks.addFallback(0, "REFLECTIVITY");
  31682. }
  31683. if (defines.BUMP) {
  31684. fallbacks.addFallback(0, "BUMP");
  31685. }
  31686. if (defines.PARALLAX) {
  31687. fallbacks.addFallback(1, "PARALLAX");
  31688. }
  31689. if (defines.PARALLAXOCCLUSION) {
  31690. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31691. }
  31692. if (defines.SPECULAROVERALPHA) {
  31693. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31694. }
  31695. if (defines.FOG) {
  31696. fallbacks.addFallback(1, "FOG");
  31697. }
  31698. if (defines.POINTSIZE) {
  31699. fallbacks.addFallback(0, "POINTSIZE");
  31700. }
  31701. if (defines.LOGARITHMICDEPTH) {
  31702. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31703. }
  31704. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31705. if (defines.SPECULARTERM) {
  31706. fallbacks.addFallback(0, "SPECULARTERM");
  31707. }
  31708. if (defines.NUM_BONE_INFLUENCERS > 0) {
  31709. fallbacks.addCPUSkinningFallback(0, mesh);
  31710. }
  31711. //Attributes
  31712. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31713. if (defines.NORMAL) {
  31714. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31715. }
  31716. if (defines.TANGENT) {
  31717. attribs.push(BABYLON.VertexBuffer.TangentKind);
  31718. }
  31719. if (defines.UV1) {
  31720. attribs.push(BABYLON.VertexBuffer.UVKind);
  31721. }
  31722. if (defines.UV2) {
  31723. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31724. }
  31725. if (defines.VERTEXCOLOR) {
  31726. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31727. }
  31728. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31729. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31730. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31731. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  31732. "vFogInfos", "vFogColor", "pointSize",
  31733. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31734. "mBones",
  31735. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31736. "vLightingIntensity",
  31737. "logarithmicDepthConstant",
  31738. "vSphericalX", "vSphericalY", "vSphericalZ",
  31739. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  31740. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  31741. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  31742. "vNormalReoderParams"
  31743. ];
  31744. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  31745. "bumpSampler", "lightmapSampler", "opacitySampler",
  31746. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  31747. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  31748. "microSurfaceSampler", "environmentBrdfSampler"];
  31749. var uniformBuffers = ["Material", "Scene"];
  31750. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31751. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31752. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31753. uniformsNames: uniforms,
  31754. uniformBuffersNames: uniformBuffers,
  31755. samplers: samplers,
  31756. defines: defines,
  31757. maxSimultaneousLights: this._maxSimultaneousLights
  31758. });
  31759. var onCompiled = function (effect) {
  31760. if (this.onCompiled) {
  31761. this.onCompiled(effect);
  31762. }
  31763. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  31764. }.bind(this);
  31765. var join = defines.toString();
  31766. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  31767. attributes: attribs,
  31768. uniformsNames: uniforms,
  31769. uniformBuffersNames: uniformBuffers,
  31770. samplers: samplers,
  31771. defines: join,
  31772. fallbacks: fallbacks,
  31773. onCompiled: onCompiled,
  31774. onError: this.onError,
  31775. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31776. }, engine), defines);
  31777. this.buildUniformLayout();
  31778. }
  31779. if (!subMesh.effect.isReady()) {
  31780. return false;
  31781. }
  31782. defines._renderId = scene.getRenderId();
  31783. this._wasPreviouslyReady = true;
  31784. return true;
  31785. };
  31786. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  31787. // Order is important !
  31788. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  31789. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  31790. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31791. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31792. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31793. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  31794. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  31795. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31796. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31797. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31798. this._uniformBuffer.addUniform("albedoMatrix", 16);
  31799. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31800. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31801. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31802. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31803. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  31804. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  31805. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31806. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  31807. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31808. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31809. this._uniformBuffer.addUniform("vReflectionColor", 3);
  31810. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  31811. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  31812. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  31813. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  31814. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  31815. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31816. this._uniformBuffer.addUniform("pointSize", 1);
  31817. this._uniformBuffer.create();
  31818. };
  31819. PBRBaseMaterial.prototype.unbind = function () {
  31820. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31821. this._uniformBuffer.setTexture("reflectionSampler", null);
  31822. }
  31823. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31824. this._uniformBuffer.setTexture("refractionSampler", null);
  31825. }
  31826. _super.prototype.unbind.call(this);
  31827. };
  31828. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  31829. this._activeEffect.setMatrix("world", world);
  31830. };
  31831. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31832. var scene = this.getScene();
  31833. var defines = subMesh._materialDefines;
  31834. if (!defines) {
  31835. return;
  31836. }
  31837. var effect = subMesh.effect;
  31838. this._activeEffect = effect;
  31839. // Matrices
  31840. this.bindOnlyWorldMatrix(world);
  31841. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  31842. // Bones
  31843. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  31844. if (mustRebind) {
  31845. this._uniformBuffer.bindToEffect(effect, "Material");
  31846. this.bindViewProjection(effect);
  31847. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31848. // Texture uniforms
  31849. if (scene.texturesEnabled) {
  31850. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31851. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  31852. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  31853. }
  31854. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31855. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  31856. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31857. }
  31858. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31859. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31860. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31861. }
  31862. var reflectionTexture = this._getReflectionTexture();
  31863. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31864. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  31865. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  31866. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  31867. var polynomials = reflectionTexture.sphericalPolynomial;
  31868. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  31869. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  31870. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  31871. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  31872. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  31873. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  31874. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  31875. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  31876. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  31877. }
  31878. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  31879. }
  31880. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31881. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31882. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31883. }
  31884. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31885. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31886. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31887. }
  31888. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31889. if (this._metallicTexture) {
  31890. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  31891. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  31892. }
  31893. else if (this._reflectivityTexture) {
  31894. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  31895. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  31896. }
  31897. if (this._microSurfaceTexture) {
  31898. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  31899. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  31900. }
  31901. }
  31902. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31903. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  31904. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31905. if (scene._mirroredCameraPosition) {
  31906. 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);
  31907. }
  31908. else {
  31909. 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);
  31910. }
  31911. }
  31912. var refractionTexture = this._getRefractionTexture();
  31913. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31914. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  31915. var depth = 1.0;
  31916. if (!refractionTexture.isCube) {
  31917. if (refractionTexture.depth) {
  31918. depth = refractionTexture.depth;
  31919. }
  31920. }
  31921. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  31922. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  31923. }
  31924. }
  31925. // Point size
  31926. if (this.pointsCloud) {
  31927. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31928. }
  31929. // Colors
  31930. if (defines.METALLICWORKFLOW) {
  31931. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  31932. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  31933. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  31934. }
  31935. else {
  31936. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  31937. }
  31938. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  31939. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  31940. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  31941. // Misc
  31942. this._lightingInfos.x = this._directIntensity;
  31943. this._lightingInfos.y = this._emissiveIntensity;
  31944. this._lightingInfos.z = this._environmentIntensity;
  31945. this._lightingInfos.w = this._specularIntensity;
  31946. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  31947. }
  31948. // Textures
  31949. if (scene.texturesEnabled) {
  31950. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31951. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  31952. }
  31953. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31954. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  31955. }
  31956. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31957. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  31958. }
  31959. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31960. if (defines.LODBASEDMICROSFURACE) {
  31961. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  31962. }
  31963. else {
  31964. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  31965. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  31966. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  31967. }
  31968. }
  31969. if (defines.ENVIRONMENTBRDF) {
  31970. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  31971. }
  31972. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31973. if (defines.LODBASEDMICROSFURACE) {
  31974. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  31975. }
  31976. else {
  31977. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  31978. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  31979. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  31980. }
  31981. }
  31982. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31983. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  31984. }
  31985. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31986. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  31987. }
  31988. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31989. if (this._metallicTexture) {
  31990. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  31991. }
  31992. else if (this._reflectivityTexture) {
  31993. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  31994. }
  31995. if (this._microSurfaceTexture) {
  31996. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  31997. }
  31998. }
  31999. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32000. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32001. }
  32002. }
  32003. // Clip plane
  32004. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32005. // Colors
  32006. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32007. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32008. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32009. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32010. }
  32011. if (mustRebind || !this.isFrozen) {
  32012. // Lights
  32013. if (scene.lightsEnabled && !this._disableLighting) {
  32014. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32015. }
  32016. // View
  32017. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32018. this.bindView(effect);
  32019. }
  32020. // Fog
  32021. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32022. // Morph targets
  32023. if (defines.NUM_MORPH_INFLUENCERS) {
  32024. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32025. }
  32026. // image processing
  32027. this._imageProcessingConfiguration.bind(this._activeEffect);
  32028. // Log. depth
  32029. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32030. }
  32031. this._uniformBuffer.update();
  32032. this._afterBind(mesh);
  32033. scene = null;
  32034. };
  32035. PBRBaseMaterial.prototype.getAnimatables = function () {
  32036. var results = [];
  32037. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32038. results.push(this._albedoTexture);
  32039. }
  32040. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32041. results.push(this._ambientTexture);
  32042. }
  32043. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32044. results.push(this._opacityTexture);
  32045. }
  32046. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32047. results.push(this._reflectionTexture);
  32048. }
  32049. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32050. results.push(this._emissiveTexture);
  32051. }
  32052. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32053. results.push(this._metallicTexture);
  32054. }
  32055. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32056. results.push(this._reflectivityTexture);
  32057. }
  32058. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32059. results.push(this._bumpTexture);
  32060. }
  32061. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32062. results.push(this._lightmapTexture);
  32063. }
  32064. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32065. results.push(this._refractionTexture);
  32066. }
  32067. return results;
  32068. };
  32069. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32070. if (this._reflectionTexture) {
  32071. return this._reflectionTexture;
  32072. }
  32073. return this.getScene().environmentTexture;
  32074. };
  32075. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32076. if (this._refractionTexture) {
  32077. return this._refractionTexture;
  32078. }
  32079. if (this._linkRefractionWithTransparency) {
  32080. return this.getScene().environmentTexture;
  32081. }
  32082. return null;
  32083. };
  32084. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32085. if (forceDisposeTextures) {
  32086. if (this._albedoTexture) {
  32087. this._albedoTexture.dispose();
  32088. }
  32089. if (this._ambientTexture) {
  32090. this._ambientTexture.dispose();
  32091. }
  32092. if (this._opacityTexture) {
  32093. this._opacityTexture.dispose();
  32094. }
  32095. if (this._reflectionTexture) {
  32096. this._reflectionTexture.dispose();
  32097. }
  32098. if (this._environmentBRDFTexture) {
  32099. this._environmentBRDFTexture.dispose();
  32100. }
  32101. if (this._emissiveTexture) {
  32102. this._emissiveTexture.dispose();
  32103. }
  32104. if (this._metallicTexture) {
  32105. this._metallicTexture.dispose();
  32106. }
  32107. if (this._reflectivityTexture) {
  32108. this._reflectivityTexture.dispose();
  32109. }
  32110. if (this._bumpTexture) {
  32111. this._bumpTexture.dispose();
  32112. }
  32113. if (this._lightmapTexture) {
  32114. this._lightmapTexture.dispose();
  32115. }
  32116. if (this._refractionTexture) {
  32117. this._refractionTexture.dispose();
  32118. }
  32119. }
  32120. this._renderTargets.dispose();
  32121. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32122. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32123. }
  32124. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32125. };
  32126. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32127. __decorate([
  32128. BABYLON.serializeAsImageProcessingConfiguration()
  32129. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32130. __decorate([
  32131. BABYLON.serialize()
  32132. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32133. return PBRBaseMaterial;
  32134. }(BABYLON.PushMaterial));
  32135. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  32136. })(BABYLON || (BABYLON = {}));
  32137. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  32138. var BABYLON;
  32139. (function (BABYLON) {
  32140. var Internals;
  32141. (function (Internals) {
  32142. /**
  32143. * The Physically based simple base material of BJS.
  32144. *
  32145. * This enables better naming and convention enforcements on top of the pbrMaterial.
  32146. * It is used as the base class for both the specGloss and metalRough conventions.
  32147. */
  32148. var PBRBaseSimpleMaterial = (function (_super) {
  32149. __extends(PBRBaseSimpleMaterial, _super);
  32150. /**
  32151. * Instantiates a new PBRMaterial instance.
  32152. *
  32153. * @param name The material name
  32154. * @param scene The scene the material will be use in.
  32155. */
  32156. function PBRBaseSimpleMaterial(name, scene) {
  32157. var _this = _super.call(this, name, scene) || this;
  32158. /**
  32159. * Number of Simultaneous lights allowed on the material.
  32160. */
  32161. _this.maxSimultaneousLights = 4;
  32162. /**
  32163. * If sets to true, disables all the lights affecting the material.
  32164. */
  32165. _this.disableLighting = false;
  32166. /**
  32167. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32168. */
  32169. _this.invertNormalMapX = false;
  32170. /**
  32171. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32172. */
  32173. _this.invertNormalMapY = false;
  32174. /**
  32175. * Emissivie color used to self-illuminate the model.
  32176. */
  32177. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32178. /**
  32179. * Occlusion Channel Strenght.
  32180. */
  32181. _this.occlusionStrength = 1.0;
  32182. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32183. _this._useAmbientInGrayScale = true;
  32184. return _this;
  32185. }
  32186. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  32187. /**
  32188. * Gets the current transparency mode.
  32189. */
  32190. get: function () {
  32191. return this._transparencyMode;
  32192. },
  32193. /**
  32194. * Sets the transparency mode of the material.
  32195. */
  32196. set: function (value) {
  32197. if (this._transparencyMode === value) {
  32198. return;
  32199. }
  32200. this._transparencyMode = value;
  32201. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  32202. this._forceAlphaTest = true;
  32203. }
  32204. else {
  32205. this._forceAlphaTest = false;
  32206. }
  32207. this._markAllSubMeshesAsTexturesDirty();
  32208. },
  32209. enumerable: true,
  32210. configurable: true
  32211. });
  32212. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  32213. /**
  32214. * Gets the current double sided mode.
  32215. */
  32216. get: function () {
  32217. return this._twoSidedLighting;
  32218. },
  32219. /**
  32220. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32221. */
  32222. set: function (value) {
  32223. if (this._twoSidedLighting === value) {
  32224. return;
  32225. }
  32226. this._twoSidedLighting = value;
  32227. this.backFaceCulling = !value;
  32228. this._markAllSubMeshesAsTexturesDirty();
  32229. },
  32230. enumerable: true,
  32231. configurable: true
  32232. });
  32233. /**
  32234. * Specifies wether or not the alpha value of the albedo texture should be used.
  32235. */
  32236. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32237. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32238. };
  32239. /**
  32240. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  32241. */
  32242. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  32243. if (this._linkRefractionWithTransparency) {
  32244. return false;
  32245. }
  32246. return (this.alpha < 1.0) ||
  32247. (this._shouldUseAlphaFromAlbedoTexture() &&
  32248. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  32249. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  32250. };
  32251. /**
  32252. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  32253. */
  32254. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  32255. if (this._linkRefractionWithTransparency) {
  32256. return false;
  32257. }
  32258. return this._shouldUseAlphaFromAlbedoTexture() &&
  32259. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  32260. };
  32261. /**
  32262. * Return the active textures of the material.
  32263. */
  32264. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  32265. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32266. if (this.environmentTexture) {
  32267. activeTextures.push(this.environmentTexture);
  32268. }
  32269. if (this.normalTexture) {
  32270. activeTextures.push(this.normalTexture);
  32271. }
  32272. if (this.emissiveTexture) {
  32273. activeTextures.push(this.emissiveTexture);
  32274. }
  32275. if (this.occlusionTexture) {
  32276. activeTextures.push(this.occlusionTexture);
  32277. }
  32278. return activeTextures;
  32279. };
  32280. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  32281. return "PBRBaseSimpleMaterial";
  32282. };
  32283. __decorate([
  32284. BABYLON.serialize(),
  32285. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32286. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  32287. __decorate([
  32288. BABYLON.serialize(),
  32289. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32290. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  32291. __decorate([
  32292. BABYLON.serializeAsTexture(),
  32293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  32294. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  32295. __decorate([
  32296. BABYLON.serialize(),
  32297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32298. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  32299. __decorate([
  32300. BABYLON.serialize(),
  32301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32302. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  32303. __decorate([
  32304. BABYLON.serializeAsTexture(),
  32305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  32306. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  32307. __decorate([
  32308. BABYLON.serializeAsColor3("emissive"),
  32309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32310. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  32311. __decorate([
  32312. BABYLON.serializeAsTexture(),
  32313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32314. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  32315. __decorate([
  32316. BABYLON.serialize(),
  32317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  32318. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  32319. __decorate([
  32320. BABYLON.serializeAsTexture(),
  32321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  32322. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  32323. __decorate([
  32324. BABYLON.serialize(),
  32325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  32326. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  32327. __decorate([
  32328. BABYLON.serialize()
  32329. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  32330. __decorate([
  32331. BABYLON.serialize()
  32332. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  32333. return PBRBaseSimpleMaterial;
  32334. }(BABYLON.PBRBaseMaterial));
  32335. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  32336. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32337. })(BABYLON || (BABYLON = {}));
  32338. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  32339. var BABYLON;
  32340. (function (BABYLON) {
  32341. /**
  32342. * The Physically based material of BJS.
  32343. *
  32344. * This offers the main features of a standard PBR material.
  32345. * For more information, please refer to the documentation :
  32346. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32347. */
  32348. var PBRMaterial = (function (_super) {
  32349. __extends(PBRMaterial, _super);
  32350. /**
  32351. * Instantiates a new PBRMaterial instance.
  32352. *
  32353. * @param name The material name
  32354. * @param scene The scene the material will be use in.
  32355. */
  32356. function PBRMaterial(name, scene) {
  32357. var _this = _super.call(this, name, scene) || this;
  32358. /**
  32359. * Intensity of the direct lights e.g. the four lights available in your scene.
  32360. * This impacts both the direct diffuse and specular highlights.
  32361. */
  32362. _this.directIntensity = 1.0;
  32363. /**
  32364. * Intensity of the emissive part of the material.
  32365. * This helps controlling the emissive effect without modifying the emissive color.
  32366. */
  32367. _this.emissiveIntensity = 1.0;
  32368. /**
  32369. * Intensity of the environment e.g. how much the environment will light the object
  32370. * either through harmonics for rough material or through the refelction for shiny ones.
  32371. */
  32372. _this.environmentIntensity = 1.0;
  32373. /**
  32374. * This is a special control allowing the reduction of the specular highlights coming from the
  32375. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32376. */
  32377. _this.specularIntensity = 1.0;
  32378. /**
  32379. * Debug Control allowing disabling the bump map on this material.
  32380. */
  32381. _this.disableBumpMap = false;
  32382. /**
  32383. * AKA Occlusion Texture Intensity in other nomenclature.
  32384. */
  32385. _this.ambientTextureStrength = 1.0;
  32386. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32387. /**
  32388. * AKA Diffuse Color in other nomenclature.
  32389. */
  32390. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  32391. /**
  32392. * AKA Specular Color in other nomenclature.
  32393. */
  32394. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32395. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  32396. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32397. /**
  32398. * AKA Glossiness in other nomenclature.
  32399. */
  32400. _this.microSurface = 1.0;
  32401. /**
  32402. * source material index of refraction (IOR)' / 'destination material IOR.
  32403. */
  32404. _this.indexOfRefraction = 0.66;
  32405. /**
  32406. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32407. */
  32408. _this.invertRefractionY = false;
  32409. /**
  32410. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32411. * Materials half opaque for instance using refraction could benefit from this control.
  32412. */
  32413. _this.linkRefractionWithTransparency = false;
  32414. _this.useLightmapAsShadowmap = false;
  32415. /**
  32416. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32417. */
  32418. _this.useAlphaFromAlbedoTexture = false;
  32419. /**
  32420. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32421. */
  32422. _this.forceAlphaTest = false;
  32423. /**
  32424. * Defines the alpha limits in alpha test mode.
  32425. */
  32426. _this.alphaCutOff = 0.4;
  32427. /**
  32428. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32429. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32430. */
  32431. _this.useSpecularOverAlpha = true;
  32432. /**
  32433. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32434. */
  32435. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  32436. /**
  32437. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32438. */
  32439. _this.useRoughnessFromMetallicTextureAlpha = true;
  32440. /**
  32441. * Specifies if the metallic texture contains the roughness information in its green channel.
  32442. */
  32443. _this.useRoughnessFromMetallicTextureGreen = false;
  32444. /**
  32445. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32446. */
  32447. _this.useMetallnessFromMetallicTextureBlue = false;
  32448. /**
  32449. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32450. */
  32451. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  32452. /**
  32453. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32454. */
  32455. _this.useAmbientInGrayScale = false;
  32456. /**
  32457. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32458. * The material will try to infer what glossiness each pixel should be.
  32459. */
  32460. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  32461. /**
  32462. * BJS is using an harcoded light falloff based on a manually sets up range.
  32463. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32464. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32465. */
  32466. _this.usePhysicalLightFalloff = true;
  32467. /**
  32468. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32469. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32470. */
  32471. _this.useRadianceOverAlpha = true;
  32472. /**
  32473. * Allows using the bump map in parallax mode.
  32474. */
  32475. _this.useParallax = false;
  32476. /**
  32477. * Allows using the bump map in parallax occlusion mode.
  32478. */
  32479. _this.useParallaxOcclusion = false;
  32480. /**
  32481. * Controls the scale bias of the parallax mode.
  32482. */
  32483. _this.parallaxScaleBias = 0.05;
  32484. /**
  32485. * If sets to true, disables all the lights affecting the material.
  32486. */
  32487. _this.disableLighting = false;
  32488. /**
  32489. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32490. */
  32491. _this.forceIrradianceInFragment = false;
  32492. /**
  32493. * Number of Simultaneous lights allowed on the material.
  32494. */
  32495. _this.maxSimultaneousLights = 4;
  32496. /**
  32497. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32498. */
  32499. _this.invertNormalMapX = false;
  32500. /**
  32501. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32502. */
  32503. _this.invertNormalMapY = false;
  32504. /**
  32505. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32506. */
  32507. _this.twoSidedLighting = false;
  32508. /**
  32509. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32510. * in your scene composition.
  32511. */
  32512. _this.preMultiplyAlpha = false;
  32513. /**
  32514. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32515. * And/Or occlude the blended part.
  32516. */
  32517. _this.useAlphaFresnel = false;
  32518. /**
  32519. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32520. * And/Or occlude the blended part.
  32521. */
  32522. _this.environmentBRDFTexture = null;
  32523. /**
  32524. * Force normal to face away from face.
  32525. * (Temporary internal fix to remove before 3.1)
  32526. */
  32527. _this.forceNormalForward = false;
  32528. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32529. return _this;
  32530. }
  32531. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  32532. /**
  32533. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  32534. */
  32535. get: function () {
  32536. return this._PBRMATERIAL_OPAQUE;
  32537. },
  32538. enumerable: true,
  32539. configurable: true
  32540. });
  32541. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  32542. /**
  32543. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  32544. */
  32545. get: function () {
  32546. return this._PBRMATERIAL_ALPHATEST;
  32547. },
  32548. enumerable: true,
  32549. configurable: true
  32550. });
  32551. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  32552. /**
  32553. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32554. */
  32555. get: function () {
  32556. return this._PBRMATERIAL_ALPHABLEND;
  32557. },
  32558. enumerable: true,
  32559. configurable: true
  32560. });
  32561. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  32562. /**
  32563. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32564. * They are also discarded below the alpha cutoff threshold to improve performances.
  32565. */
  32566. get: function () {
  32567. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  32568. },
  32569. enumerable: true,
  32570. configurable: true
  32571. });
  32572. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  32573. /**
  32574. * Gets the image processing configuration used either in this material.
  32575. */
  32576. get: function () {
  32577. return this._imageProcessingConfiguration;
  32578. },
  32579. /**
  32580. * Sets the Default image processing configuration used either in the this material.
  32581. *
  32582. * If sets to null, the scene one is in use.
  32583. */
  32584. set: function (value) {
  32585. this._attachImageProcessingConfiguration(value);
  32586. // Ensure the effect will be rebuilt.
  32587. this._markAllSubMeshesAsTexturesDirty();
  32588. },
  32589. enumerable: true,
  32590. configurable: true
  32591. });
  32592. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  32593. /**
  32594. * Gets wether the color curves effect is enabled.
  32595. */
  32596. get: function () {
  32597. return this.imageProcessingConfiguration.colorCurvesEnabled;
  32598. },
  32599. /**
  32600. * Sets wether the color curves effect is enabled.
  32601. */
  32602. set: function (value) {
  32603. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  32604. },
  32605. enumerable: true,
  32606. configurable: true
  32607. });
  32608. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  32609. /**
  32610. * Gets wether the color grading effect is enabled.
  32611. */
  32612. get: function () {
  32613. return this.imageProcessingConfiguration.colorGradingEnabled;
  32614. },
  32615. /**
  32616. * Gets wether the color grading effect is enabled.
  32617. */
  32618. set: function (value) {
  32619. this.imageProcessingConfiguration.colorGradingEnabled = value;
  32620. },
  32621. enumerable: true,
  32622. configurable: true
  32623. });
  32624. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  32625. /**
  32626. * Gets wether tonemapping is enabled or not.
  32627. */
  32628. get: function () {
  32629. return this._imageProcessingConfiguration.toneMappingEnabled;
  32630. },
  32631. /**
  32632. * Sets wether tonemapping is enabled or not
  32633. */
  32634. set: function (value) {
  32635. this._imageProcessingConfiguration.toneMappingEnabled = value;
  32636. },
  32637. enumerable: true,
  32638. configurable: true
  32639. });
  32640. ;
  32641. ;
  32642. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  32643. /**
  32644. * The camera exposure used on this material.
  32645. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32646. * This corresponds to a photographic exposure.
  32647. */
  32648. get: function () {
  32649. return this._imageProcessingConfiguration.exposure;
  32650. },
  32651. /**
  32652. * The camera exposure used on this material.
  32653. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32654. * This corresponds to a photographic exposure.
  32655. */
  32656. set: function (value) {
  32657. this._imageProcessingConfiguration.exposure = value;
  32658. },
  32659. enumerable: true,
  32660. configurable: true
  32661. });
  32662. ;
  32663. ;
  32664. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  32665. /**
  32666. * Gets The camera contrast used on this material.
  32667. */
  32668. get: function () {
  32669. return this._imageProcessingConfiguration.contrast;
  32670. },
  32671. /**
  32672. * Sets The camera contrast used on this material.
  32673. */
  32674. set: function (value) {
  32675. this._imageProcessingConfiguration.contrast = value;
  32676. },
  32677. enumerable: true,
  32678. configurable: true
  32679. });
  32680. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  32681. /**
  32682. * Gets the Color Grading 2D Lookup Texture.
  32683. */
  32684. get: function () {
  32685. return this._imageProcessingConfiguration.colorGradingTexture;
  32686. },
  32687. /**
  32688. * Sets the Color Grading 2D Lookup Texture.
  32689. */
  32690. set: function (value) {
  32691. this._imageProcessingConfiguration.colorGradingTexture = value;
  32692. },
  32693. enumerable: true,
  32694. configurable: true
  32695. });
  32696. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  32697. /**
  32698. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32699. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32700. * 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;
  32701. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32702. */
  32703. get: function () {
  32704. return this._imageProcessingConfiguration.colorCurves;
  32705. },
  32706. /**
  32707. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32708. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32709. * 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;
  32710. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32711. */
  32712. set: function (value) {
  32713. this._imageProcessingConfiguration.colorCurves = value;
  32714. },
  32715. enumerable: true,
  32716. configurable: true
  32717. });
  32718. PBRMaterial.prototype.getClassName = function () {
  32719. return "PBRMaterial";
  32720. };
  32721. PBRMaterial.prototype.getActiveTextures = function () {
  32722. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32723. if (this._albedoTexture) {
  32724. activeTextures.push(this._albedoTexture);
  32725. }
  32726. if (this._ambientTexture) {
  32727. activeTextures.push(this._ambientTexture);
  32728. }
  32729. if (this._opacityTexture) {
  32730. activeTextures.push(this._opacityTexture);
  32731. }
  32732. if (this._reflectionTexture) {
  32733. activeTextures.push(this._reflectionTexture);
  32734. }
  32735. if (this._emissiveTexture) {
  32736. activeTextures.push(this._emissiveTexture);
  32737. }
  32738. if (this._reflectivityTexture) {
  32739. activeTextures.push(this._reflectivityTexture);
  32740. }
  32741. if (this._metallicTexture) {
  32742. activeTextures.push(this._metallicTexture);
  32743. }
  32744. if (this._microSurfaceTexture) {
  32745. activeTextures.push(this._microSurfaceTexture);
  32746. }
  32747. if (this._bumpTexture) {
  32748. activeTextures.push(this._bumpTexture);
  32749. }
  32750. if (this._lightmapTexture) {
  32751. activeTextures.push(this._lightmapTexture);
  32752. }
  32753. if (this._refractionTexture) {
  32754. activeTextures.push(this._refractionTexture);
  32755. }
  32756. return activeTextures;
  32757. };
  32758. PBRMaterial.prototype.hasTexture = function (texture) {
  32759. if (_super.prototype.hasTexture.call(this, texture)) {
  32760. return true;
  32761. }
  32762. if (this._albedoTexture === texture) {
  32763. return true;
  32764. }
  32765. if (this._ambientTexture === texture) {
  32766. return true;
  32767. }
  32768. if (this._opacityTexture === texture) {
  32769. return true;
  32770. }
  32771. if (this._reflectionTexture === texture) {
  32772. return true;
  32773. }
  32774. if (this._reflectivityTexture === texture) {
  32775. return true;
  32776. }
  32777. if (this._metallicTexture === texture) {
  32778. return true;
  32779. }
  32780. if (this._microSurfaceTexture === texture) {
  32781. return true;
  32782. }
  32783. if (this._bumpTexture === texture) {
  32784. return true;
  32785. }
  32786. if (this._lightmapTexture === texture) {
  32787. return true;
  32788. }
  32789. if (this._refractionTexture === texture) {
  32790. return true;
  32791. }
  32792. return false;
  32793. };
  32794. PBRMaterial.prototype.clone = function (name) {
  32795. var _this = this;
  32796. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  32797. };
  32798. PBRMaterial.prototype.serialize = function () {
  32799. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32800. serializationObject.customType = "BABYLON.PBRMaterial";
  32801. return serializationObject;
  32802. };
  32803. // Statics
  32804. PBRMaterial.Parse = function (source, scene, rootUrl) {
  32805. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  32806. };
  32807. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  32808. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  32809. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  32810. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  32811. __decorate([
  32812. BABYLON.serialize(),
  32813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32814. ], PBRMaterial.prototype, "directIntensity", void 0);
  32815. __decorate([
  32816. BABYLON.serialize(),
  32817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32818. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  32819. __decorate([
  32820. BABYLON.serialize(),
  32821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32822. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  32823. __decorate([
  32824. BABYLON.serialize(),
  32825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32826. ], PBRMaterial.prototype, "specularIntensity", void 0);
  32827. __decorate([
  32828. BABYLON.serialize(),
  32829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32830. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  32831. __decorate([
  32832. BABYLON.serializeAsTexture(),
  32833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32834. ], PBRMaterial.prototype, "albedoTexture", void 0);
  32835. __decorate([
  32836. BABYLON.serializeAsTexture(),
  32837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32838. ], PBRMaterial.prototype, "ambientTexture", void 0);
  32839. __decorate([
  32840. BABYLON.serialize(),
  32841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32842. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  32843. __decorate([
  32844. BABYLON.serializeAsTexture(),
  32845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32846. ], PBRMaterial.prototype, "opacityTexture", void 0);
  32847. __decorate([
  32848. BABYLON.serializeAsTexture(),
  32849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32850. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  32851. __decorate([
  32852. BABYLON.serializeAsTexture(),
  32853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32854. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  32855. __decorate([
  32856. BABYLON.serializeAsTexture(),
  32857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32858. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  32859. __decorate([
  32860. BABYLON.serializeAsTexture(),
  32861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32862. ], PBRMaterial.prototype, "metallicTexture", void 0);
  32863. __decorate([
  32864. BABYLON.serialize(),
  32865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32866. ], PBRMaterial.prototype, "metallic", void 0);
  32867. __decorate([
  32868. BABYLON.serialize(),
  32869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32870. ], PBRMaterial.prototype, "roughness", void 0);
  32871. __decorate([
  32872. BABYLON.serializeAsTexture(),
  32873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32874. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  32875. __decorate([
  32876. BABYLON.serializeAsTexture(),
  32877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32878. ], PBRMaterial.prototype, "bumpTexture", void 0);
  32879. __decorate([
  32880. BABYLON.serializeAsTexture(),
  32881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  32882. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  32883. __decorate([
  32884. BABYLON.serializeAsTexture(),
  32885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32886. ], PBRMaterial.prototype, "refractionTexture", void 0);
  32887. __decorate([
  32888. BABYLON.serializeAsColor3("ambient"),
  32889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32890. ], PBRMaterial.prototype, "ambientColor", void 0);
  32891. __decorate([
  32892. BABYLON.serializeAsColor3("albedo"),
  32893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32894. ], PBRMaterial.prototype, "albedoColor", void 0);
  32895. __decorate([
  32896. BABYLON.serializeAsColor3("reflectivity"),
  32897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32898. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  32899. __decorate([
  32900. BABYLON.serializeAsColor3("reflection"),
  32901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32902. ], PBRMaterial.prototype, "reflectionColor", void 0);
  32903. __decorate([
  32904. BABYLON.serializeAsColor3("emissive"),
  32905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32906. ], PBRMaterial.prototype, "emissiveColor", void 0);
  32907. __decorate([
  32908. BABYLON.serialize(),
  32909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32910. ], PBRMaterial.prototype, "microSurface", void 0);
  32911. __decorate([
  32912. BABYLON.serialize(),
  32913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32914. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  32915. __decorate([
  32916. BABYLON.serialize(),
  32917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32918. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  32919. __decorate([
  32920. BABYLON.serialize(),
  32921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32922. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  32923. __decorate([
  32924. BABYLON.serialize(),
  32925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32926. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  32927. __decorate([
  32928. BABYLON.serialize(),
  32929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32930. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  32931. __decorate([
  32932. BABYLON.serialize(),
  32933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32934. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  32935. __decorate([
  32936. BABYLON.serialize(),
  32937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32938. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  32939. __decorate([
  32940. BABYLON.serialize(),
  32941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32942. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  32943. __decorate([
  32944. BABYLON.serialize(),
  32945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32946. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  32947. __decorate([
  32948. BABYLON.serialize(),
  32949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32950. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  32951. __decorate([
  32952. BABYLON.serialize(),
  32953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32954. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  32955. __decorate([
  32956. BABYLON.serialize(),
  32957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32958. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  32959. __decorate([
  32960. BABYLON.serialize(),
  32961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32962. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  32963. __decorate([
  32964. BABYLON.serialize(),
  32965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32966. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  32967. __decorate([
  32968. BABYLON.serialize(),
  32969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32970. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  32971. __decorate([
  32972. BABYLON.serialize(),
  32973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32974. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  32975. __decorate([
  32976. BABYLON.serialize(),
  32977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32978. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  32979. __decorate([
  32980. BABYLON.serialize(),
  32981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32982. ], PBRMaterial.prototype, "useParallax", void 0);
  32983. __decorate([
  32984. BABYLON.serialize(),
  32985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32986. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  32987. __decorate([
  32988. BABYLON.serialize(),
  32989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32990. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  32991. __decorate([
  32992. BABYLON.serialize(),
  32993. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32994. ], PBRMaterial.prototype, "disableLighting", void 0);
  32995. __decorate([
  32996. BABYLON.serialize(),
  32997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32998. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  32999. __decorate([
  33000. BABYLON.serialize(),
  33001. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33002. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33003. __decorate([
  33004. BABYLON.serialize(),
  33005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33006. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33007. __decorate([
  33008. BABYLON.serialize(),
  33009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33010. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33011. __decorate([
  33012. BABYLON.serialize(),
  33013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33014. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33015. __decorate([
  33016. BABYLON.serialize(),
  33017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33018. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33019. __decorate([
  33020. BABYLON.serialize(),
  33021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33022. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33023. __decorate([
  33024. BABYLON.serializeAsTexture(),
  33025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33026. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33027. __decorate([
  33028. BABYLON.serialize(),
  33029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33030. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33031. return PBRMaterial;
  33032. }(BABYLON.PBRBaseMaterial));
  33033. BABYLON.PBRMaterial = PBRMaterial;
  33034. })(BABYLON || (BABYLON = {}));
  33035. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33036. var BABYLON;
  33037. (function (BABYLON) {
  33038. /**
  33039. * The PBR material of BJS following the metal roughness convention.
  33040. *
  33041. * This fits to the PBR convention in the GLTF definition:
  33042. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33043. */
  33044. var PBRMetallicRoughnessMaterial = (function (_super) {
  33045. __extends(PBRMetallicRoughnessMaterial, _super);
  33046. /**
  33047. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33048. *
  33049. * @param name The material name
  33050. * @param scene The scene the material will be use in.
  33051. */
  33052. function PBRMetallicRoughnessMaterial(name, scene) {
  33053. var _this = _super.call(this, name, scene) || this;
  33054. _this._useRoughnessFromMetallicTextureAlpha = false;
  33055. _this._useRoughnessFromMetallicTextureGreen = true;
  33056. _this._useMetallnessFromMetallicTextureBlue = true;
  33057. return _this;
  33058. }
  33059. /**
  33060. * Return the currrent class name of the material.
  33061. */
  33062. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33063. return "PBRMetallicRoughnessMaterial";
  33064. };
  33065. /**
  33066. * Return the active textures of the material.
  33067. */
  33068. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33069. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33070. if (this.baseTexture) {
  33071. activeTextures.push(this.baseTexture);
  33072. }
  33073. if (this.metallicRoughnessTexture) {
  33074. activeTextures.push(this.metallicRoughnessTexture);
  33075. }
  33076. return activeTextures;
  33077. };
  33078. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33079. if (_super.prototype.hasTexture.call(this, texture)) {
  33080. return true;
  33081. }
  33082. if (this.baseTexture === texture) {
  33083. return true;
  33084. }
  33085. if (this.metallicRoughnessTexture === texture) {
  33086. return true;
  33087. }
  33088. return false;
  33089. };
  33090. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33091. var _this = this;
  33092. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33093. };
  33094. /**
  33095. * Serialize the material to a parsable JSON object.
  33096. */
  33097. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  33098. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33099. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  33100. return serializationObject;
  33101. };
  33102. /**
  33103. * Parses a JSON object correponding to the serialize function.
  33104. */
  33105. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33106. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33107. };
  33108. __decorate([
  33109. BABYLON.serializeAsColor3(),
  33110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33111. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33112. __decorate([
  33113. BABYLON.serializeAsTexture(),
  33114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33115. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33116. __decorate([
  33117. BABYLON.serialize(),
  33118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33119. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33120. __decorate([
  33121. BABYLON.serialize(),
  33122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33123. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33124. __decorate([
  33125. BABYLON.serializeAsTexture(),
  33126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33127. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33128. return PBRMetallicRoughnessMaterial;
  33129. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33130. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33131. })(BABYLON || (BABYLON = {}));
  33132. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33133. var BABYLON;
  33134. (function (BABYLON) {
  33135. /**
  33136. * The PBR material of BJS following the specular glossiness convention.
  33137. *
  33138. * This fits to the PBR convention in the GLTF definition:
  33139. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  33140. */
  33141. var PBRSpecularGlossinessMaterial = (function (_super) {
  33142. __extends(PBRSpecularGlossinessMaterial, _super);
  33143. /**
  33144. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  33145. *
  33146. * @param name The material name
  33147. * @param scene The scene the material will be use in.
  33148. */
  33149. function PBRSpecularGlossinessMaterial(name, scene) {
  33150. var _this = _super.call(this, name, scene) || this;
  33151. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  33152. return _this;
  33153. }
  33154. /**
  33155. * Return the currrent class name of the material.
  33156. */
  33157. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  33158. return "PBRSpecularGlossinessMaterial";
  33159. };
  33160. /**
  33161. * Return the active textures of the material.
  33162. */
  33163. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  33164. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33165. if (this.diffuseTexture) {
  33166. activeTextures.push(this.diffuseTexture);
  33167. }
  33168. if (this.specularGlossinessTexture) {
  33169. activeTextures.push(this.specularGlossinessTexture);
  33170. }
  33171. return activeTextures;
  33172. };
  33173. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  33174. if (_super.prototype.hasTexture.call(this, texture)) {
  33175. return true;
  33176. }
  33177. if (this.diffuseTexture === texture) {
  33178. return true;
  33179. }
  33180. if (this.specularGlossinessTexture === texture) {
  33181. return true;
  33182. }
  33183. return false;
  33184. };
  33185. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  33186. var _this = this;
  33187. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  33188. };
  33189. /**
  33190. * Serialize the material to a parsable JSON object.
  33191. */
  33192. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  33193. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33194. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  33195. return serializationObject;
  33196. };
  33197. /**
  33198. * Parses a JSON object correponding to the serialize function.
  33199. */
  33200. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  33201. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  33202. };
  33203. __decorate([
  33204. BABYLON.serializeAsColor3("diffuse"),
  33205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33206. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  33207. __decorate([
  33208. BABYLON.serializeAsTexture(),
  33209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33210. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  33211. __decorate([
  33212. BABYLON.serializeAsColor3("specular"),
  33213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  33214. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  33215. __decorate([
  33216. BABYLON.serialize(),
  33217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  33218. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  33219. __decorate([
  33220. BABYLON.serializeAsTexture(),
  33221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  33222. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  33223. return PBRSpecularGlossinessMaterial;
  33224. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33225. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  33226. })(BABYLON || (BABYLON = {}));
  33227. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  33228. var BABYLON;
  33229. (function (BABYLON) {
  33230. BABYLON.CameraInputTypes = {};
  33231. var CameraInputsManager = (function () {
  33232. function CameraInputsManager(camera) {
  33233. this.attached = {};
  33234. this.camera = camera;
  33235. this.checkInputs = function () { };
  33236. }
  33237. CameraInputsManager.prototype.add = function (input) {
  33238. var type = input.getSimpleName();
  33239. if (this.attached[type]) {
  33240. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  33241. return;
  33242. }
  33243. this.attached[type] = input;
  33244. input.camera = this.camera;
  33245. //for checkInputs, we are dynamically creating a function
  33246. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  33247. if (input.checkInputs) {
  33248. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33249. }
  33250. if (this.attachedElement) {
  33251. input.attachControl(this.attachedElement);
  33252. }
  33253. };
  33254. CameraInputsManager.prototype.remove = function (inputToRemove) {
  33255. for (var cam in this.attached) {
  33256. var input = this.attached[cam];
  33257. if (input === inputToRemove) {
  33258. input.detachControl(this.attachedElement);
  33259. input.camera = null;
  33260. delete this.attached[cam];
  33261. this.rebuildInputCheck();
  33262. }
  33263. }
  33264. };
  33265. CameraInputsManager.prototype.removeByType = function (inputType) {
  33266. for (var cam in this.attached) {
  33267. var input = this.attached[cam];
  33268. if (input.getClassName() === inputType) {
  33269. input.detachControl(this.attachedElement);
  33270. input.camera = null;
  33271. delete this.attached[cam];
  33272. this.rebuildInputCheck();
  33273. }
  33274. }
  33275. };
  33276. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  33277. var current = this.checkInputs;
  33278. return function () {
  33279. current();
  33280. fn();
  33281. };
  33282. };
  33283. CameraInputsManager.prototype.attachInput = function (input) {
  33284. input.attachControl(this.attachedElement, this.noPreventDefault);
  33285. };
  33286. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  33287. if (this.attachedElement) {
  33288. return;
  33289. }
  33290. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33291. this.attachedElement = element;
  33292. this.noPreventDefault = noPreventDefault;
  33293. for (var cam in this.attached) {
  33294. var input = this.attached[cam];
  33295. this.attached[cam].attachControl(element, noPreventDefault);
  33296. }
  33297. };
  33298. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  33299. if (disconnect === void 0) { disconnect = false; }
  33300. if (this.attachedElement !== element) {
  33301. return;
  33302. }
  33303. for (var cam in this.attached) {
  33304. var input = this.attached[cam];
  33305. this.attached[cam].detachControl(element);
  33306. if (disconnect) {
  33307. this.attached[cam].camera = null;
  33308. }
  33309. }
  33310. this.attachedElement = null;
  33311. };
  33312. CameraInputsManager.prototype.rebuildInputCheck = function () {
  33313. this.checkInputs = function () { };
  33314. for (var cam in this.attached) {
  33315. var input = this.attached[cam];
  33316. if (input.checkInputs) {
  33317. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33318. }
  33319. }
  33320. };
  33321. CameraInputsManager.prototype.clear = function () {
  33322. if (this.attachedElement) {
  33323. this.detachElement(this.attachedElement, true);
  33324. }
  33325. this.attached = {};
  33326. this.attachedElement = null;
  33327. this.checkInputs = function () { };
  33328. };
  33329. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  33330. var inputs = {};
  33331. for (var cam in this.attached) {
  33332. var input = this.attached[cam];
  33333. var res = BABYLON.SerializationHelper.Serialize(input);
  33334. inputs[input.getClassName()] = res;
  33335. }
  33336. serializedCamera.inputsmgr = inputs;
  33337. };
  33338. CameraInputsManager.prototype.parse = function (parsedCamera) {
  33339. var parsedInputs = parsedCamera.inputsmgr;
  33340. if (parsedInputs) {
  33341. this.clear();
  33342. for (var n in parsedInputs) {
  33343. var construct = BABYLON.CameraInputTypes[n];
  33344. if (construct) {
  33345. var parsedinput = parsedInputs[n];
  33346. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  33347. this.add(input);
  33348. }
  33349. }
  33350. }
  33351. else {
  33352. //2016-03-08 this part is for managing backward compatibility
  33353. for (var n in this.attached) {
  33354. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  33355. if (construct) {
  33356. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  33357. this.remove(this.attached[n]);
  33358. this.add(input);
  33359. }
  33360. }
  33361. }
  33362. };
  33363. return CameraInputsManager;
  33364. }());
  33365. BABYLON.CameraInputsManager = CameraInputsManager;
  33366. })(BABYLON || (BABYLON = {}));
  33367. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  33368. var BABYLON;
  33369. (function (BABYLON) {
  33370. var FreeCameraMouseInput = (function () {
  33371. function FreeCameraMouseInput(touchEnabled) {
  33372. if (touchEnabled === void 0) { touchEnabled = true; }
  33373. this.touchEnabled = touchEnabled;
  33374. this.buttons = [0, 1, 2];
  33375. this.angularSensibility = 2000.0;
  33376. }
  33377. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  33378. var _this = this;
  33379. var engine = this.camera.getEngine();
  33380. if (!this._pointerInput) {
  33381. this._pointerInput = function (p, s) {
  33382. var evt = p.event;
  33383. if (!_this.touchEnabled && evt.pointerType === "touch") {
  33384. return;
  33385. }
  33386. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  33387. return;
  33388. }
  33389. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  33390. try {
  33391. evt.srcElement.setPointerCapture(evt.pointerId);
  33392. }
  33393. catch (e) {
  33394. //Nothing to do with the error. Execution will continue.
  33395. }
  33396. _this.previousPosition = {
  33397. x: evt.clientX,
  33398. y: evt.clientY
  33399. };
  33400. if (!noPreventDefault) {
  33401. evt.preventDefault();
  33402. element.focus();
  33403. }
  33404. }
  33405. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  33406. try {
  33407. evt.srcElement.releasePointerCapture(evt.pointerId);
  33408. }
  33409. catch (e) {
  33410. //Nothing to do with the error.
  33411. }
  33412. _this.previousPosition = null;
  33413. if (!noPreventDefault) {
  33414. evt.preventDefault();
  33415. }
  33416. }
  33417. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  33418. if (!_this.previousPosition || engine.isPointerLock) {
  33419. return;
  33420. }
  33421. var offsetX = evt.clientX - _this.previousPosition.x;
  33422. var offsetY = evt.clientY - _this.previousPosition.y;
  33423. if (_this.camera.getScene().useRightHandedSystem) {
  33424. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33425. }
  33426. else {
  33427. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33428. }
  33429. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33430. _this.previousPosition = {
  33431. x: evt.clientX,
  33432. y: evt.clientY
  33433. };
  33434. if (!noPreventDefault) {
  33435. evt.preventDefault();
  33436. }
  33437. }
  33438. };
  33439. }
  33440. this._onMouseMove = function (evt) {
  33441. if (!engine.isPointerLock) {
  33442. return;
  33443. }
  33444. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  33445. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  33446. if (_this.camera.getScene().useRightHandedSystem) {
  33447. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33448. }
  33449. else {
  33450. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33451. }
  33452. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33453. _this.previousPosition = null;
  33454. if (!noPreventDefault) {
  33455. evt.preventDefault();
  33456. }
  33457. };
  33458. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  33459. element.addEventListener("mousemove", this._onMouseMove, false);
  33460. };
  33461. FreeCameraMouseInput.prototype.detachControl = function (element) {
  33462. if (this._observer && element) {
  33463. this.camera.getScene().onPointerObservable.remove(this._observer);
  33464. element.removeEventListener("mousemove", this._onMouseMove);
  33465. this._observer = null;
  33466. this._onMouseMove = null;
  33467. this.previousPosition = null;
  33468. }
  33469. };
  33470. FreeCameraMouseInput.prototype.getClassName = function () {
  33471. return "FreeCameraMouseInput";
  33472. };
  33473. FreeCameraMouseInput.prototype.getSimpleName = function () {
  33474. return "mouse";
  33475. };
  33476. __decorate([
  33477. BABYLON.serialize()
  33478. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  33479. __decorate([
  33480. BABYLON.serialize()
  33481. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  33482. return FreeCameraMouseInput;
  33483. }());
  33484. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  33485. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  33486. })(BABYLON || (BABYLON = {}));
  33487. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  33488. var BABYLON;
  33489. (function (BABYLON) {
  33490. var FreeCameraKeyboardMoveInput = (function () {
  33491. function FreeCameraKeyboardMoveInput() {
  33492. this._keys = [];
  33493. this.keysUp = [38];
  33494. this.keysDown = [40];
  33495. this.keysLeft = [37];
  33496. this.keysRight = [39];
  33497. }
  33498. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  33499. var _this = this;
  33500. if (!this._onKeyDown) {
  33501. element.tabIndex = 1;
  33502. this._onKeyDown = function (evt) {
  33503. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33504. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33505. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33506. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33507. var index = _this._keys.indexOf(evt.keyCode);
  33508. if (index === -1) {
  33509. _this._keys.push(evt.keyCode);
  33510. }
  33511. if (!noPreventDefault) {
  33512. evt.preventDefault();
  33513. }
  33514. }
  33515. };
  33516. this._onKeyUp = function (evt) {
  33517. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33518. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33519. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33520. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33521. var index = _this._keys.indexOf(evt.keyCode);
  33522. if (index >= 0) {
  33523. _this._keys.splice(index, 1);
  33524. }
  33525. if (!noPreventDefault) {
  33526. evt.preventDefault();
  33527. }
  33528. }
  33529. };
  33530. element.addEventListener("keydown", this._onKeyDown, false);
  33531. element.addEventListener("keyup", this._onKeyUp, false);
  33532. BABYLON.Tools.RegisterTopRootEvents([
  33533. { name: "blur", handler: this._onLostFocus }
  33534. ]);
  33535. }
  33536. };
  33537. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  33538. if (this._onKeyDown) {
  33539. element.removeEventListener("keydown", this._onKeyDown);
  33540. element.removeEventListener("keyup", this._onKeyUp);
  33541. BABYLON.Tools.UnregisterTopRootEvents([
  33542. { name: "blur", handler: this._onLostFocus }
  33543. ]);
  33544. this._keys = [];
  33545. this._onKeyDown = null;
  33546. this._onKeyUp = null;
  33547. }
  33548. };
  33549. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  33550. if (this._onKeyDown) {
  33551. var camera = this.camera;
  33552. // Keyboard
  33553. for (var index = 0; index < this._keys.length; index++) {
  33554. var keyCode = this._keys[index];
  33555. var speed = camera._computeLocalCameraSpeed();
  33556. if (this.keysLeft.indexOf(keyCode) !== -1) {
  33557. camera._localDirection.copyFromFloats(-speed, 0, 0);
  33558. }
  33559. else if (this.keysUp.indexOf(keyCode) !== -1) {
  33560. camera._localDirection.copyFromFloats(0, 0, speed);
  33561. }
  33562. else if (this.keysRight.indexOf(keyCode) !== -1) {
  33563. camera._localDirection.copyFromFloats(speed, 0, 0);
  33564. }
  33565. else if (this.keysDown.indexOf(keyCode) !== -1) {
  33566. camera._localDirection.copyFromFloats(0, 0, -speed);
  33567. }
  33568. if (camera.getScene().useRightHandedSystem) {
  33569. camera._localDirection.z *= -1;
  33570. }
  33571. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  33572. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  33573. camera.cameraDirection.addInPlace(camera._transformedDirection);
  33574. }
  33575. }
  33576. };
  33577. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  33578. return "FreeCameraKeyboardMoveInput";
  33579. };
  33580. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  33581. this._keys = [];
  33582. };
  33583. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  33584. return "keyboard";
  33585. };
  33586. __decorate([
  33587. BABYLON.serialize()
  33588. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  33589. __decorate([
  33590. BABYLON.serialize()
  33591. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  33592. __decorate([
  33593. BABYLON.serialize()
  33594. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  33595. __decorate([
  33596. BABYLON.serialize()
  33597. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  33598. return FreeCameraKeyboardMoveInput;
  33599. }());
  33600. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  33601. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  33602. })(BABYLON || (BABYLON = {}));
  33603. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  33604. var BABYLON;
  33605. (function (BABYLON) {
  33606. var FreeCameraInputsManager = (function (_super) {
  33607. __extends(FreeCameraInputsManager, _super);
  33608. function FreeCameraInputsManager(camera) {
  33609. return _super.call(this, camera) || this;
  33610. }
  33611. FreeCameraInputsManager.prototype.addKeyboard = function () {
  33612. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  33613. return this;
  33614. };
  33615. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  33616. if (touchEnabled === void 0) { touchEnabled = true; }
  33617. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  33618. return this;
  33619. };
  33620. FreeCameraInputsManager.prototype.addGamepad = function () {
  33621. this.add(new BABYLON.FreeCameraGamepadInput());
  33622. return this;
  33623. };
  33624. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  33625. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  33626. return this;
  33627. };
  33628. FreeCameraInputsManager.prototype.addTouch = function () {
  33629. this.add(new BABYLON.FreeCameraTouchInput());
  33630. return this;
  33631. };
  33632. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  33633. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  33634. return this;
  33635. };
  33636. return FreeCameraInputsManager;
  33637. }(BABYLON.CameraInputsManager));
  33638. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  33639. })(BABYLON || (BABYLON = {}));
  33640. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  33641. /// <reference path="babylon.camera.ts" />
  33642. var BABYLON;
  33643. (function (BABYLON) {
  33644. var TargetCamera = (function (_super) {
  33645. __extends(TargetCamera, _super);
  33646. function TargetCamera(name, position, scene) {
  33647. var _this = _super.call(this, name, position, scene) || this;
  33648. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  33649. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  33650. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  33651. _this.speed = 2.0;
  33652. _this.noRotationConstraint = false;
  33653. _this.lockedTarget = null;
  33654. _this._currentTarget = BABYLON.Vector3.Zero();
  33655. _this._viewMatrix = BABYLON.Matrix.Zero();
  33656. _this._camMatrix = BABYLON.Matrix.Zero();
  33657. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  33658. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  33659. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  33660. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  33661. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  33662. _this._lookAtTemp = BABYLON.Matrix.Zero();
  33663. _this._tempMatrix = BABYLON.Matrix.Zero();
  33664. return _this;
  33665. }
  33666. TargetCamera.prototype.getFrontPosition = function (distance) {
  33667. var direction = this.getTarget().subtract(this.position);
  33668. direction.normalize();
  33669. direction.scaleInPlace(distance);
  33670. return this.globalPosition.add(direction);
  33671. };
  33672. TargetCamera.prototype._getLockedTargetPosition = function () {
  33673. if (!this.lockedTarget) {
  33674. return null;
  33675. }
  33676. if (this.lockedTarget.absolutePosition) {
  33677. this.lockedTarget.computeWorldMatrix();
  33678. }
  33679. return this.lockedTarget.absolutePosition || this.lockedTarget;
  33680. };
  33681. // Cache
  33682. TargetCamera.prototype._initCache = function () {
  33683. _super.prototype._initCache.call(this);
  33684. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33685. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33686. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  33687. };
  33688. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  33689. if (!ignoreParentClass) {
  33690. _super.prototype._updateCache.call(this);
  33691. }
  33692. var lockedTargetPosition = this._getLockedTargetPosition();
  33693. if (!lockedTargetPosition) {
  33694. this._cache.lockedTarget = null;
  33695. }
  33696. else {
  33697. if (!this._cache.lockedTarget) {
  33698. this._cache.lockedTarget = lockedTargetPosition.clone();
  33699. }
  33700. else {
  33701. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  33702. }
  33703. }
  33704. this._cache.rotation.copyFrom(this.rotation);
  33705. if (this.rotationQuaternion)
  33706. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33707. };
  33708. // Synchronized
  33709. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  33710. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  33711. return false;
  33712. }
  33713. var lockedTargetPosition = this._getLockedTargetPosition();
  33714. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  33715. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  33716. };
  33717. // Methods
  33718. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  33719. var engine = this.getEngine();
  33720. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  33721. };
  33722. // Target
  33723. TargetCamera.prototype.setTarget = function (target) {
  33724. this.upVector.normalize();
  33725. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  33726. this._camMatrix.invert();
  33727. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  33728. var vDir = target.subtract(this.position);
  33729. if (vDir.x >= 0.0) {
  33730. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  33731. }
  33732. else {
  33733. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  33734. }
  33735. this.rotation.z = 0;
  33736. if (isNaN(this.rotation.x)) {
  33737. this.rotation.x = 0;
  33738. }
  33739. if (isNaN(this.rotation.y)) {
  33740. this.rotation.y = 0;
  33741. }
  33742. if (isNaN(this.rotation.z)) {
  33743. this.rotation.z = 0;
  33744. }
  33745. if (this.rotationQuaternion) {
  33746. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  33747. }
  33748. };
  33749. /**
  33750. * Return the current target position of the camera. This value is expressed in local space.
  33751. */
  33752. TargetCamera.prototype.getTarget = function () {
  33753. return this._currentTarget;
  33754. };
  33755. TargetCamera.prototype._decideIfNeedsToMove = function () {
  33756. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  33757. };
  33758. TargetCamera.prototype._updatePosition = function () {
  33759. if (this.parent) {
  33760. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  33761. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  33762. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  33763. return;
  33764. }
  33765. this.position.addInPlace(this.cameraDirection);
  33766. };
  33767. TargetCamera.prototype._checkInputs = function () {
  33768. var needToMove = this._decideIfNeedsToMove();
  33769. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  33770. // Move
  33771. if (needToMove) {
  33772. this._updatePosition();
  33773. }
  33774. // Rotate
  33775. if (needToRotate) {
  33776. this.rotation.x += this.cameraRotation.x;
  33777. this.rotation.y += this.cameraRotation.y;
  33778. //rotate, if quaternion is set and rotation was used
  33779. if (this.rotationQuaternion) {
  33780. var len = this.rotation.lengthSquared();
  33781. if (len) {
  33782. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  33783. }
  33784. }
  33785. if (!this.noRotationConstraint) {
  33786. var limit = (Math.PI / 2) * 0.95;
  33787. if (this.rotation.x > limit)
  33788. this.rotation.x = limit;
  33789. if (this.rotation.x < -limit)
  33790. this.rotation.x = -limit;
  33791. }
  33792. }
  33793. // Inertia
  33794. if (needToMove) {
  33795. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  33796. this.cameraDirection.x = 0;
  33797. }
  33798. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  33799. this.cameraDirection.y = 0;
  33800. }
  33801. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  33802. this.cameraDirection.z = 0;
  33803. }
  33804. this.cameraDirection.scaleInPlace(this.inertia);
  33805. }
  33806. if (needToRotate) {
  33807. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  33808. this.cameraRotation.x = 0;
  33809. }
  33810. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  33811. this.cameraRotation.y = 0;
  33812. }
  33813. this.cameraRotation.scaleInPlace(this.inertia);
  33814. }
  33815. _super.prototype._checkInputs.call(this);
  33816. };
  33817. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  33818. if (this.rotationQuaternion) {
  33819. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  33820. //update the up vector!
  33821. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  33822. }
  33823. else {
  33824. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  33825. }
  33826. };
  33827. TargetCamera.prototype._getViewMatrix = function () {
  33828. if (!this.lockedTarget) {
  33829. // Compute
  33830. this._updateCameraRotationMatrix();
  33831. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  33832. // Computing target and final matrix
  33833. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  33834. }
  33835. else {
  33836. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  33837. }
  33838. if (this.getScene().useRightHandedSystem) {
  33839. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  33840. }
  33841. else {
  33842. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  33843. }
  33844. return this._viewMatrix;
  33845. };
  33846. /**
  33847. * @override
  33848. * Override Camera.createRigCamera
  33849. */
  33850. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33851. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  33852. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  33853. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  33854. if (!this.rotationQuaternion) {
  33855. this.rotationQuaternion = new BABYLON.Quaternion();
  33856. }
  33857. rigCamera._cameraRigParams = {};
  33858. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  33859. }
  33860. return rigCamera;
  33861. }
  33862. return null;
  33863. };
  33864. /**
  33865. * @override
  33866. * Override Camera._updateRigCameras
  33867. */
  33868. TargetCamera.prototype._updateRigCameras = function () {
  33869. var camLeft = this._rigCameras[0];
  33870. var camRight = this._rigCameras[1];
  33871. switch (this.cameraRigMode) {
  33872. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33873. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33874. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33875. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33876. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  33877. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  33878. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  33879. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  33880. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  33881. camLeft.setTarget(this.getTarget());
  33882. camRight.setTarget(this.getTarget());
  33883. break;
  33884. case BABYLON.Camera.RIG_MODE_VR:
  33885. if (camLeft.rotationQuaternion) {
  33886. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33887. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  33888. }
  33889. else {
  33890. camLeft.rotation.copyFrom(this.rotation);
  33891. camRight.rotation.copyFrom(this.rotation);
  33892. }
  33893. camLeft.position.copyFrom(this.position);
  33894. camRight.position.copyFrom(this.position);
  33895. break;
  33896. }
  33897. _super.prototype._updateRigCameras.call(this);
  33898. };
  33899. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  33900. if (!this._rigCamTransformMatrix) {
  33901. this._rigCamTransformMatrix = new BABYLON.Matrix();
  33902. }
  33903. var target = this.getTarget();
  33904. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  33905. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  33906. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  33907. };
  33908. TargetCamera.prototype.getClassName = function () {
  33909. return "TargetCamera";
  33910. };
  33911. __decorate([
  33912. BABYLON.serializeAsVector3()
  33913. ], TargetCamera.prototype, "rotation", void 0);
  33914. __decorate([
  33915. BABYLON.serialize()
  33916. ], TargetCamera.prototype, "speed", void 0);
  33917. __decorate([
  33918. BABYLON.serializeAsMeshReference("lockedTargetId")
  33919. ], TargetCamera.prototype, "lockedTarget", void 0);
  33920. return TargetCamera;
  33921. }(BABYLON.Camera));
  33922. BABYLON.TargetCamera = TargetCamera;
  33923. })(BABYLON || (BABYLON = {}));
  33924. //# sourceMappingURL=babylon.targetCamera.js.map
  33925. var BABYLON;
  33926. (function (BABYLON) {
  33927. var FreeCamera = (function (_super) {
  33928. __extends(FreeCamera, _super);
  33929. function FreeCamera(name, position, scene) {
  33930. var _this = _super.call(this, name, position, scene) || this;
  33931. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  33932. _this.checkCollisions = false;
  33933. _this.applyGravity = false;
  33934. _this._needMoveForGravity = false;
  33935. _this._oldPosition = BABYLON.Vector3.Zero();
  33936. _this._diffPosition = BABYLON.Vector3.Zero();
  33937. _this._newPosition = BABYLON.Vector3.Zero();
  33938. // Collisions
  33939. _this._collisionMask = -1;
  33940. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  33941. if (collidedMesh === void 0) { collidedMesh = null; }
  33942. //TODO move this to the collision coordinator!
  33943. if (_this.getScene().workerCollisions)
  33944. newPosition.multiplyInPlace(_this._collider.radius);
  33945. var updatePosition = function (newPos) {
  33946. _this._newPosition.copyFrom(newPos);
  33947. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  33948. var oldPosition = _this.position.clone();
  33949. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  33950. _this.position.addInPlace(_this._diffPosition);
  33951. if (_this.onCollide && collidedMesh) {
  33952. _this.onCollide(collidedMesh);
  33953. }
  33954. }
  33955. };
  33956. updatePosition(newPosition);
  33957. };
  33958. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  33959. _this.inputs.addKeyboard().addMouse();
  33960. return _this;
  33961. }
  33962. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  33963. //-- begin properties for backward compatibility for inputs
  33964. get: function () {
  33965. var mouse = this.inputs.attached["mouse"];
  33966. if (mouse)
  33967. return mouse.angularSensibility;
  33968. },
  33969. set: function (value) {
  33970. var mouse = this.inputs.attached["mouse"];
  33971. if (mouse)
  33972. mouse.angularSensibility = value;
  33973. },
  33974. enumerable: true,
  33975. configurable: true
  33976. });
  33977. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  33978. get: function () {
  33979. var keyboard = this.inputs.attached["keyboard"];
  33980. if (keyboard)
  33981. return keyboard.keysUp;
  33982. },
  33983. set: function (value) {
  33984. var keyboard = this.inputs.attached["keyboard"];
  33985. if (keyboard)
  33986. keyboard.keysUp = value;
  33987. },
  33988. enumerable: true,
  33989. configurable: true
  33990. });
  33991. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  33992. get: function () {
  33993. var keyboard = this.inputs.attached["keyboard"];
  33994. if (keyboard)
  33995. return keyboard.keysDown;
  33996. },
  33997. set: function (value) {
  33998. var keyboard = this.inputs.attached["keyboard"];
  33999. if (keyboard)
  34000. keyboard.keysDown = value;
  34001. },
  34002. enumerable: true,
  34003. configurable: true
  34004. });
  34005. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34006. get: function () {
  34007. var keyboard = this.inputs.attached["keyboard"];
  34008. if (keyboard)
  34009. return keyboard.keysLeft;
  34010. },
  34011. set: function (value) {
  34012. var keyboard = this.inputs.attached["keyboard"];
  34013. if (keyboard)
  34014. keyboard.keysLeft = value;
  34015. },
  34016. enumerable: true,
  34017. configurable: true
  34018. });
  34019. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34020. get: function () {
  34021. var keyboard = this.inputs.attached["keyboard"];
  34022. if (keyboard)
  34023. return keyboard.keysRight;
  34024. },
  34025. set: function (value) {
  34026. var keyboard = this.inputs.attached["keyboard"];
  34027. if (keyboard)
  34028. keyboard.keysRight = value;
  34029. },
  34030. enumerable: true,
  34031. configurable: true
  34032. });
  34033. // Controls
  34034. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34035. this.inputs.attachElement(element, noPreventDefault);
  34036. };
  34037. FreeCamera.prototype.detachControl = function (element) {
  34038. this.inputs.detachElement(element);
  34039. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34040. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34041. };
  34042. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34043. get: function () {
  34044. return this._collisionMask;
  34045. },
  34046. set: function (mask) {
  34047. this._collisionMask = !isNaN(mask) ? mask : -1;
  34048. },
  34049. enumerable: true,
  34050. configurable: true
  34051. });
  34052. FreeCamera.prototype._collideWithWorld = function (velocity) {
  34053. var globalPosition;
  34054. if (this.parent) {
  34055. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34056. }
  34057. else {
  34058. globalPosition = this.position;
  34059. }
  34060. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34061. if (!this._collider) {
  34062. this._collider = new BABYLON.Collider();
  34063. }
  34064. this._collider.radius = this.ellipsoid;
  34065. this._collider.collisionMask = this._collisionMask;
  34066. //no need for clone, as long as gravity is not on.
  34067. var actualVelocity = velocity;
  34068. //add gravity to the velocity to prevent the dual-collision checking
  34069. if (this.applyGravity) {
  34070. //this prevents mending with cameraDirection, a global variable of the free camera class.
  34071. actualVelocity = velocity.add(this.getScene().gravity);
  34072. }
  34073. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34074. };
  34075. FreeCamera.prototype._checkInputs = function () {
  34076. if (!this._localDirection) {
  34077. this._localDirection = BABYLON.Vector3.Zero();
  34078. this._transformedDirection = BABYLON.Vector3.Zero();
  34079. }
  34080. this.inputs.checkInputs();
  34081. _super.prototype._checkInputs.call(this);
  34082. };
  34083. FreeCamera.prototype._decideIfNeedsToMove = function () {
  34084. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34085. };
  34086. FreeCamera.prototype._updatePosition = function () {
  34087. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  34088. this._collideWithWorld(this.cameraDirection);
  34089. }
  34090. else {
  34091. _super.prototype._updatePosition.call(this);
  34092. }
  34093. };
  34094. FreeCamera.prototype.dispose = function () {
  34095. this.inputs.clear();
  34096. _super.prototype.dispose.call(this);
  34097. };
  34098. FreeCamera.prototype.getClassName = function () {
  34099. return "FreeCamera";
  34100. };
  34101. __decorate([
  34102. BABYLON.serializeAsVector3()
  34103. ], FreeCamera.prototype, "ellipsoid", void 0);
  34104. __decorate([
  34105. BABYLON.serialize()
  34106. ], FreeCamera.prototype, "checkCollisions", void 0);
  34107. __decorate([
  34108. BABYLON.serialize()
  34109. ], FreeCamera.prototype, "applyGravity", void 0);
  34110. return FreeCamera;
  34111. }(BABYLON.TargetCamera));
  34112. BABYLON.FreeCamera = FreeCamera;
  34113. })(BABYLON || (BABYLON = {}));
  34114. //# sourceMappingURL=babylon.freeCamera.js.map
  34115. var BABYLON;
  34116. (function (BABYLON) {
  34117. var ArcRotateCameraKeyboardMoveInput = (function () {
  34118. function ArcRotateCameraKeyboardMoveInput() {
  34119. this._keys = [];
  34120. this.keysUp = [38];
  34121. this.keysDown = [40];
  34122. this.keysLeft = [37];
  34123. this.keysRight = [39];
  34124. }
  34125. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34126. var _this = this;
  34127. element.tabIndex = 1;
  34128. this._onKeyDown = function (evt) {
  34129. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34130. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34131. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34132. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34133. var index = _this._keys.indexOf(evt.keyCode);
  34134. if (index === -1) {
  34135. _this._keys.push(evt.keyCode);
  34136. }
  34137. if (evt.preventDefault) {
  34138. if (!noPreventDefault) {
  34139. evt.preventDefault();
  34140. }
  34141. }
  34142. }
  34143. };
  34144. this._onKeyUp = function (evt) {
  34145. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34146. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34147. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34148. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34149. var index = _this._keys.indexOf(evt.keyCode);
  34150. if (index >= 0) {
  34151. _this._keys.splice(index, 1);
  34152. }
  34153. if (evt.preventDefault) {
  34154. if (!noPreventDefault) {
  34155. evt.preventDefault();
  34156. }
  34157. }
  34158. }
  34159. };
  34160. this._onLostFocus = function () {
  34161. _this._keys = [];
  34162. };
  34163. this._onFocus = function () {
  34164. element.addEventListener("keydown", _this._onKeyDown, false);
  34165. element.addEventListener("keyup", _this._onKeyUp, false);
  34166. };
  34167. this._onBlur = function () {
  34168. element.removeEventListener("keydown", _this._onKeyDown);
  34169. element.removeEventListener("keyup", _this._onKeyUp);
  34170. };
  34171. element.addEventListener("focus", this._onFocus);
  34172. element.addEventListener("blur", this._onBlur);
  34173. BABYLON.Tools.RegisterTopRootEvents([
  34174. { name: "blur", handler: this._onLostFocus }
  34175. ]);
  34176. };
  34177. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34178. if (element && this._onBlur) {
  34179. this._onBlur();
  34180. element.removeEventListener("focus", this._onFocus);
  34181. element.removeEventListener("blur", this._onBlur);
  34182. }
  34183. BABYLON.Tools.UnregisterTopRootEvents([
  34184. { name: "blur", handler: this._onLostFocus }
  34185. ]);
  34186. this._keys = [];
  34187. this._onKeyDown = null;
  34188. this._onKeyUp = null;
  34189. this._onLostFocus = null;
  34190. this._onBlur = null;
  34191. this._onFocus = null;
  34192. };
  34193. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34194. if (this._onKeyDown) {
  34195. var camera = this.camera;
  34196. for (var index = 0; index < this._keys.length; index++) {
  34197. var keyCode = this._keys[index];
  34198. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34199. camera.inertialAlphaOffset -= 0.01;
  34200. }
  34201. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34202. camera.inertialBetaOffset -= 0.01;
  34203. }
  34204. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34205. camera.inertialAlphaOffset += 0.01;
  34206. }
  34207. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34208. camera.inertialBetaOffset += 0.01;
  34209. }
  34210. }
  34211. }
  34212. };
  34213. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  34214. return "ArcRotateCameraKeyboardMoveInput";
  34215. };
  34216. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34217. return "keyboard";
  34218. };
  34219. __decorate([
  34220. BABYLON.serialize()
  34221. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34222. __decorate([
  34223. BABYLON.serialize()
  34224. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34225. __decorate([
  34226. BABYLON.serialize()
  34227. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34228. __decorate([
  34229. BABYLON.serialize()
  34230. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34231. return ArcRotateCameraKeyboardMoveInput;
  34232. }());
  34233. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  34234. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  34235. })(BABYLON || (BABYLON = {}));
  34236. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  34237. var BABYLON;
  34238. (function (BABYLON) {
  34239. var ArcRotateCameraMouseWheelInput = (function () {
  34240. function ArcRotateCameraMouseWheelInput() {
  34241. this.wheelPrecision = 3.0;
  34242. }
  34243. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  34244. var _this = this;
  34245. this._wheel = function (p, s) {
  34246. //sanity check - this should be a PointerWheel event.
  34247. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  34248. return;
  34249. var event = p.event;
  34250. var delta = 0;
  34251. if (event.wheelDelta) {
  34252. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  34253. }
  34254. else if (event.detail) {
  34255. delta = -event.detail / _this.wheelPrecision;
  34256. }
  34257. if (delta)
  34258. _this.camera.inertialRadiusOffset += delta;
  34259. if (event.preventDefault) {
  34260. if (!noPreventDefault) {
  34261. event.preventDefault();
  34262. }
  34263. }
  34264. };
  34265. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  34266. };
  34267. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  34268. if (this._observer && element) {
  34269. this.camera.getScene().onPointerObservable.remove(this._observer);
  34270. this._observer = null;
  34271. this._wheel = null;
  34272. }
  34273. };
  34274. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  34275. return "ArcRotateCameraMouseWheelInput";
  34276. };
  34277. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  34278. return "mousewheel";
  34279. };
  34280. __decorate([
  34281. BABYLON.serialize()
  34282. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  34283. return ArcRotateCameraMouseWheelInput;
  34284. }());
  34285. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  34286. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  34287. })(BABYLON || (BABYLON = {}));
  34288. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  34289. var BABYLON;
  34290. (function (BABYLON) {
  34291. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  34292. var ArcRotateCameraPointersInput = (function () {
  34293. function ArcRotateCameraPointersInput() {
  34294. this.buttons = [0, 1, 2];
  34295. this.angularSensibilityX = 1000.0;
  34296. this.angularSensibilityY = 1000.0;
  34297. this.pinchPrecision = 6.0;
  34298. this.panningSensibility = 50.0;
  34299. this._isPanClick = false;
  34300. this.pinchInwards = true;
  34301. }
  34302. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  34303. var _this = this;
  34304. var engine = this.camera.getEngine();
  34305. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  34306. var pointA, pointB;
  34307. var previousPinchDistance = 0;
  34308. this._pointerInput = function (p, s) {
  34309. var evt = p.event;
  34310. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34311. return;
  34312. }
  34313. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34314. try {
  34315. evt.srcElement.setPointerCapture(evt.pointerId);
  34316. }
  34317. catch (e) {
  34318. //Nothing to do with the error. Execution will continue.
  34319. }
  34320. // Manage panning with pan button click
  34321. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  34322. // manage pointers
  34323. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  34324. if (pointA === undefined) {
  34325. pointA = cacheSoloPointer;
  34326. }
  34327. else if (pointB === undefined) {
  34328. pointB = cacheSoloPointer;
  34329. }
  34330. if (!noPreventDefault) {
  34331. evt.preventDefault();
  34332. element.focus();
  34333. }
  34334. }
  34335. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34336. try {
  34337. evt.srcElement.releasePointerCapture(evt.pointerId);
  34338. }
  34339. catch (e) {
  34340. //Nothing to do with the error.
  34341. }
  34342. cacheSoloPointer = null;
  34343. previousPinchDistance = 0;
  34344. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  34345. //but emptying completly pointers collection is required to fix a bug on iPhone :
  34346. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  34347. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  34348. pointA = pointB = undefined;
  34349. if (!noPreventDefault) {
  34350. evt.preventDefault();
  34351. }
  34352. }
  34353. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34354. if (!noPreventDefault) {
  34355. evt.preventDefault();
  34356. }
  34357. // One button down
  34358. if (pointA && pointB === undefined) {
  34359. if (_this.panningSensibility !== 0 &&
  34360. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  34361. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  34362. _this.camera
  34363. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  34364. _this.camera
  34365. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  34366. }
  34367. else {
  34368. var offsetX = evt.clientX - cacheSoloPointer.x;
  34369. var offsetY = evt.clientY - cacheSoloPointer.y;
  34370. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34371. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34372. }
  34373. cacheSoloPointer.x = evt.clientX;
  34374. cacheSoloPointer.y = evt.clientY;
  34375. }
  34376. else if (pointA && pointB) {
  34377. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  34378. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  34379. ed.x = evt.clientX;
  34380. ed.y = evt.clientY;
  34381. var direction = _this.pinchInwards ? 1 : -1;
  34382. var distX = pointA.x - pointB.x;
  34383. var distY = pointA.y - pointB.y;
  34384. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  34385. if (previousPinchDistance === 0) {
  34386. previousPinchDistance = pinchSquaredDistance;
  34387. return;
  34388. }
  34389. if (pinchSquaredDistance !== previousPinchDistance) {
  34390. _this.camera
  34391. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  34392. (_this.pinchPrecision *
  34393. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  34394. direction);
  34395. previousPinchDistance = pinchSquaredDistance;
  34396. }
  34397. }
  34398. }
  34399. };
  34400. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34401. this._onContextMenu = function (evt) {
  34402. evt.preventDefault();
  34403. };
  34404. if (!this.camera._useCtrlForPanning) {
  34405. element.addEventListener("contextmenu", this._onContextMenu, false);
  34406. }
  34407. this._onLostFocus = function () {
  34408. //this._keys = [];
  34409. pointA = pointB = undefined;
  34410. previousPinchDistance = 0;
  34411. cacheSoloPointer = null;
  34412. };
  34413. this._onMouseMove = function (evt) {
  34414. if (!engine.isPointerLock) {
  34415. return;
  34416. }
  34417. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34418. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34419. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34420. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34421. if (!noPreventDefault) {
  34422. evt.preventDefault();
  34423. }
  34424. };
  34425. this._onGestureStart = function (e) {
  34426. if (window.MSGesture === undefined) {
  34427. return;
  34428. }
  34429. if (!_this._MSGestureHandler) {
  34430. _this._MSGestureHandler = new MSGesture();
  34431. _this._MSGestureHandler.target = element;
  34432. }
  34433. _this._MSGestureHandler.addPointer(e.pointerId);
  34434. };
  34435. this._onGesture = function (e) {
  34436. _this.camera.radius *= e.scale;
  34437. if (e.preventDefault) {
  34438. if (!noPreventDefault) {
  34439. e.stopPropagation();
  34440. e.preventDefault();
  34441. }
  34442. }
  34443. };
  34444. element.addEventListener("mousemove", this._onMouseMove, false);
  34445. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  34446. element.addEventListener("MSGestureChange", this._onGesture, false);
  34447. BABYLON.Tools.RegisterTopRootEvents([
  34448. { name: "blur", handler: this._onLostFocus }
  34449. ]);
  34450. };
  34451. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  34452. BABYLON.Tools.UnregisterTopRootEvents([
  34453. { name: "blur", handler: this._onLostFocus }
  34454. ]);
  34455. if (element && this._observer) {
  34456. this.camera.getScene().onPointerObservable.remove(this._observer);
  34457. this._observer = null;
  34458. element.removeEventListener("contextmenu", this._onContextMenu);
  34459. element.removeEventListener("mousemove", this._onMouseMove);
  34460. element.removeEventListener("MSPointerDown", this._onGestureStart);
  34461. element.removeEventListener("MSGestureChange", this._onGesture);
  34462. this._isPanClick = false;
  34463. this.pinchInwards = true;
  34464. this._onMouseMove = null;
  34465. this._onGestureStart = null;
  34466. this._onGesture = null;
  34467. this._MSGestureHandler = null;
  34468. this._onLostFocus = null;
  34469. this._onContextMenu = null;
  34470. }
  34471. };
  34472. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  34473. return "ArcRotateCameraPointersInput";
  34474. };
  34475. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  34476. return "pointers";
  34477. };
  34478. __decorate([
  34479. BABYLON.serialize()
  34480. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  34481. __decorate([
  34482. BABYLON.serialize()
  34483. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  34484. __decorate([
  34485. BABYLON.serialize()
  34486. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  34487. __decorate([
  34488. BABYLON.serialize()
  34489. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  34490. __decorate([
  34491. BABYLON.serialize()
  34492. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  34493. return ArcRotateCameraPointersInput;
  34494. }());
  34495. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  34496. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  34497. })(BABYLON || (BABYLON = {}));
  34498. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  34499. /// <reference path="babylon.targetCamera.ts" />
  34500. /// <reference path="..\Tools\babylon.tools.ts" />
  34501. var BABYLON;
  34502. (function (BABYLON) {
  34503. var ArcRotateCamera = (function (_super) {
  34504. __extends(ArcRotateCamera, _super);
  34505. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  34506. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  34507. _this.inertialAlphaOffset = 0;
  34508. _this.inertialBetaOffset = 0;
  34509. _this.inertialRadiusOffset = 0;
  34510. _this.lowerAlphaLimit = null;
  34511. _this.upperAlphaLimit = null;
  34512. _this.lowerBetaLimit = 0.01;
  34513. _this.upperBetaLimit = Math.PI;
  34514. _this.lowerRadiusLimit = null;
  34515. _this.upperRadiusLimit = null;
  34516. _this.inertialPanningX = 0;
  34517. _this.inertialPanningY = 0;
  34518. _this.panningInertia = 0.9;
  34519. //-- end properties for backward compatibility for inputs
  34520. _this.zoomOnFactor = 1;
  34521. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  34522. _this.allowUpsideDown = true;
  34523. _this._viewMatrix = new BABYLON.Matrix();
  34524. // Panning
  34525. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  34526. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  34527. _this.checkCollisions = false;
  34528. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  34529. _this._previousPosition = BABYLON.Vector3.Zero();
  34530. _this._collisionVelocity = BABYLON.Vector3.Zero();
  34531. _this._newPosition = BABYLON.Vector3.Zero();
  34532. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34533. if (collidedMesh === void 0) { collidedMesh = null; }
  34534. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  34535. newPosition.multiplyInPlace(_this._collider.radius);
  34536. }
  34537. if (!collidedMesh) {
  34538. _this._previousPosition.copyFrom(_this.position);
  34539. }
  34540. else {
  34541. _this.setPosition(newPosition);
  34542. if (_this.onCollide) {
  34543. _this.onCollide(collidedMesh);
  34544. }
  34545. }
  34546. // Recompute because of constraints
  34547. var cosa = Math.cos(_this.alpha);
  34548. var sina = Math.sin(_this.alpha);
  34549. var cosb = Math.cos(_this.beta);
  34550. var sinb = Math.sin(_this.beta);
  34551. if (sinb === 0) {
  34552. sinb = 0.0001;
  34553. }
  34554. var target = _this._getTargetPosition();
  34555. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  34556. _this.position.copyFrom(_this._newPosition);
  34557. var up = _this.upVector;
  34558. if (_this.allowUpsideDown && _this.beta < 0) {
  34559. up = up.clone();
  34560. up = up.negate();
  34561. }
  34562. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  34563. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  34564. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  34565. _this._collisionTriggered = false;
  34566. };
  34567. _this._target = BABYLON.Vector3.Zero();
  34568. if (target) {
  34569. _this.setTarget(target);
  34570. }
  34571. _this.alpha = alpha;
  34572. _this.beta = beta;
  34573. _this.radius = radius;
  34574. _this.getViewMatrix();
  34575. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  34576. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  34577. return _this;
  34578. }
  34579. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  34580. get: function () {
  34581. return this._target;
  34582. },
  34583. set: function (value) {
  34584. this.setTarget(value);
  34585. },
  34586. enumerable: true,
  34587. configurable: true
  34588. });
  34589. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  34590. //-- begin properties for backward compatibility for inputs
  34591. get: function () {
  34592. var pointers = this.inputs.attached["pointers"];
  34593. if (pointers)
  34594. return pointers.angularSensibilityX;
  34595. },
  34596. set: function (value) {
  34597. var pointers = this.inputs.attached["pointers"];
  34598. if (pointers) {
  34599. pointers.angularSensibilityX = value;
  34600. }
  34601. },
  34602. enumerable: true,
  34603. configurable: true
  34604. });
  34605. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  34606. get: function () {
  34607. var pointers = this.inputs.attached["pointers"];
  34608. if (pointers)
  34609. return pointers.angularSensibilityY;
  34610. },
  34611. set: function (value) {
  34612. var pointers = this.inputs.attached["pointers"];
  34613. if (pointers) {
  34614. pointers.angularSensibilityY = value;
  34615. }
  34616. },
  34617. enumerable: true,
  34618. configurable: true
  34619. });
  34620. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  34621. get: function () {
  34622. var pointers = this.inputs.attached["pointers"];
  34623. if (pointers)
  34624. return pointers.pinchPrecision;
  34625. },
  34626. set: function (value) {
  34627. var pointers = this.inputs.attached["pointers"];
  34628. if (pointers) {
  34629. pointers.pinchPrecision = value;
  34630. }
  34631. },
  34632. enumerable: true,
  34633. configurable: true
  34634. });
  34635. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  34636. get: function () {
  34637. var pointers = this.inputs.attached["pointers"];
  34638. if (pointers)
  34639. return pointers.panningSensibility;
  34640. },
  34641. set: function (value) {
  34642. var pointers = this.inputs.attached["pointers"];
  34643. if (pointers) {
  34644. pointers.panningSensibility = value;
  34645. }
  34646. },
  34647. enumerable: true,
  34648. configurable: true
  34649. });
  34650. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  34651. get: function () {
  34652. var keyboard = this.inputs.attached["keyboard"];
  34653. if (keyboard)
  34654. return keyboard.keysUp;
  34655. },
  34656. set: function (value) {
  34657. var keyboard = this.inputs.attached["keyboard"];
  34658. if (keyboard)
  34659. keyboard.keysUp = value;
  34660. },
  34661. enumerable: true,
  34662. configurable: true
  34663. });
  34664. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  34665. get: function () {
  34666. var keyboard = this.inputs.attached["keyboard"];
  34667. if (keyboard)
  34668. return keyboard.keysDown;
  34669. },
  34670. set: function (value) {
  34671. var keyboard = this.inputs.attached["keyboard"];
  34672. if (keyboard)
  34673. keyboard.keysDown = value;
  34674. },
  34675. enumerable: true,
  34676. configurable: true
  34677. });
  34678. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  34679. get: function () {
  34680. var keyboard = this.inputs.attached["keyboard"];
  34681. if (keyboard)
  34682. return keyboard.keysLeft;
  34683. },
  34684. set: function (value) {
  34685. var keyboard = this.inputs.attached["keyboard"];
  34686. if (keyboard)
  34687. keyboard.keysLeft = value;
  34688. },
  34689. enumerable: true,
  34690. configurable: true
  34691. });
  34692. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  34693. get: function () {
  34694. var keyboard = this.inputs.attached["keyboard"];
  34695. if (keyboard)
  34696. return keyboard.keysRight;
  34697. },
  34698. set: function (value) {
  34699. var keyboard = this.inputs.attached["keyboard"];
  34700. if (keyboard)
  34701. keyboard.keysRight = value;
  34702. },
  34703. enumerable: true,
  34704. configurable: true
  34705. });
  34706. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  34707. get: function () {
  34708. var mousewheel = this.inputs.attached["mousewheel"];
  34709. if (mousewheel)
  34710. return mousewheel.wheelPrecision;
  34711. },
  34712. set: function (value) {
  34713. var mousewheel = this.inputs.attached["mousewheel"];
  34714. if (mousewheel)
  34715. mousewheel.wheelPrecision = value;
  34716. },
  34717. enumerable: true,
  34718. configurable: true
  34719. });
  34720. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  34721. get: function () {
  34722. return this._bouncingBehavior;
  34723. },
  34724. enumerable: true,
  34725. configurable: true
  34726. });
  34727. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  34728. get: function () {
  34729. return this._bouncingBehavior != null;
  34730. },
  34731. set: function (value) {
  34732. if (value === this.useBouncingBehavior) {
  34733. return;
  34734. }
  34735. if (value) {
  34736. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  34737. this.addBehavior(this._bouncingBehavior);
  34738. }
  34739. else {
  34740. this.removeBehavior(this._bouncingBehavior);
  34741. this._bouncingBehavior = null;
  34742. }
  34743. },
  34744. enumerable: true,
  34745. configurable: true
  34746. });
  34747. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  34748. get: function () {
  34749. return this._framingBehavior;
  34750. },
  34751. enumerable: true,
  34752. configurable: true
  34753. });
  34754. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  34755. get: function () {
  34756. return this._framingBehavior != null;
  34757. },
  34758. set: function (value) {
  34759. if (value === this.useFramingBehavior) {
  34760. return;
  34761. }
  34762. if (value) {
  34763. this._framingBehavior = new BABYLON.FramingBehavior();
  34764. this.addBehavior(this._framingBehavior);
  34765. }
  34766. else {
  34767. this.removeBehavior(this._framingBehavior);
  34768. this._framingBehavior = null;
  34769. }
  34770. },
  34771. enumerable: true,
  34772. configurable: true
  34773. });
  34774. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  34775. get: function () {
  34776. return this._autoRotationBehavior;
  34777. },
  34778. enumerable: true,
  34779. configurable: true
  34780. });
  34781. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  34782. get: function () {
  34783. return this._autoRotationBehavior != null;
  34784. },
  34785. set: function (value) {
  34786. if (value === this.useAutoRotationBehavior) {
  34787. return;
  34788. }
  34789. if (value) {
  34790. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  34791. this.addBehavior(this._autoRotationBehavior);
  34792. }
  34793. else {
  34794. this.removeBehavior(this._autoRotationBehavior);
  34795. this._autoRotationBehavior = null;
  34796. }
  34797. },
  34798. enumerable: true,
  34799. configurable: true
  34800. });
  34801. // Cache
  34802. ArcRotateCamera.prototype._initCache = function () {
  34803. _super.prototype._initCache.call(this);
  34804. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34805. this._cache.alpha = undefined;
  34806. this._cache.beta = undefined;
  34807. this._cache.radius = undefined;
  34808. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  34809. };
  34810. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  34811. if (!ignoreParentClass) {
  34812. _super.prototype._updateCache.call(this);
  34813. }
  34814. this._cache._target.copyFrom(this._getTargetPosition());
  34815. this._cache.alpha = this.alpha;
  34816. this._cache.beta = this.beta;
  34817. this._cache.radius = this.radius;
  34818. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  34819. };
  34820. ArcRotateCamera.prototype._getTargetPosition = function () {
  34821. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  34822. var pos = this._targetHost.getAbsolutePosition();
  34823. if (this._targetBoundingCenter) {
  34824. pos.addToRef(this._targetBoundingCenter, this._target);
  34825. }
  34826. else {
  34827. this._target.copyFrom(pos);
  34828. }
  34829. }
  34830. var lockedTargetPosition = this._getLockedTargetPosition();
  34831. if (lockedTargetPosition) {
  34832. return lockedTargetPosition;
  34833. }
  34834. return this._target;
  34835. };
  34836. // Synchronized
  34837. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  34838. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  34839. return false;
  34840. return this._cache._target.equals(this._getTargetPosition())
  34841. && this._cache.alpha === this.alpha
  34842. && this._cache.beta === this.beta
  34843. && this._cache.radius === this.radius
  34844. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  34845. };
  34846. // Methods
  34847. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  34848. var _this = this;
  34849. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  34850. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  34851. this._useCtrlForPanning = useCtrlForPanning;
  34852. this._panningMouseButton = panningMouseButton;
  34853. this.inputs.attachElement(element, noPreventDefault);
  34854. this._reset = function () {
  34855. _this.inertialAlphaOffset = 0;
  34856. _this.inertialBetaOffset = 0;
  34857. _this.inertialRadiusOffset = 0;
  34858. };
  34859. };
  34860. ArcRotateCamera.prototype.detachControl = function (element) {
  34861. this.inputs.detachElement(element);
  34862. if (this._reset) {
  34863. this._reset();
  34864. }
  34865. };
  34866. ArcRotateCamera.prototype._checkInputs = function () {
  34867. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  34868. if (this._collisionTriggered) {
  34869. return;
  34870. }
  34871. this.inputs.checkInputs();
  34872. // Inertia
  34873. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  34874. if (this.getScene().useRightHandedSystem) {
  34875. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  34876. }
  34877. else {
  34878. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  34879. }
  34880. this.beta += this.inertialBetaOffset;
  34881. this.radius -= this.inertialRadiusOffset;
  34882. this.inertialAlphaOffset *= this.inertia;
  34883. this.inertialBetaOffset *= this.inertia;
  34884. this.inertialRadiusOffset *= this.inertia;
  34885. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  34886. this.inertialAlphaOffset = 0;
  34887. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  34888. this.inertialBetaOffset = 0;
  34889. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  34890. this.inertialRadiusOffset = 0;
  34891. }
  34892. // Panning inertia
  34893. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  34894. if (!this._localDirection) {
  34895. this._localDirection = BABYLON.Vector3.Zero();
  34896. this._transformedDirection = BABYLON.Vector3.Zero();
  34897. }
  34898. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  34899. this._localDirection.multiplyInPlace(this.panningAxis);
  34900. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  34901. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  34902. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  34903. if (!this.panningAxis.y) {
  34904. this._transformedDirection.y = 0;
  34905. }
  34906. if (!this._targetHost) {
  34907. this._target.addInPlace(this._transformedDirection);
  34908. }
  34909. this.inertialPanningX *= this.panningInertia;
  34910. this.inertialPanningY *= this.panningInertia;
  34911. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  34912. this.inertialPanningX = 0;
  34913. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  34914. this.inertialPanningY = 0;
  34915. }
  34916. // Limits
  34917. this._checkLimits();
  34918. _super.prototype._checkInputs.call(this);
  34919. };
  34920. ArcRotateCamera.prototype._checkLimits = function () {
  34921. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  34922. if (this.allowUpsideDown && this.beta > Math.PI) {
  34923. this.beta = this.beta - (2 * Math.PI);
  34924. }
  34925. }
  34926. else {
  34927. if (this.beta < this.lowerBetaLimit) {
  34928. this.beta = this.lowerBetaLimit;
  34929. }
  34930. }
  34931. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  34932. if (this.allowUpsideDown && this.beta < -Math.PI) {
  34933. this.beta = this.beta + (2 * Math.PI);
  34934. }
  34935. }
  34936. else {
  34937. if (this.beta > this.upperBetaLimit) {
  34938. this.beta = this.upperBetaLimit;
  34939. }
  34940. }
  34941. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  34942. this.alpha = this.lowerAlphaLimit;
  34943. }
  34944. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  34945. this.alpha = this.upperAlphaLimit;
  34946. }
  34947. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  34948. this.radius = this.lowerRadiusLimit;
  34949. }
  34950. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  34951. this.radius = this.upperRadiusLimit;
  34952. }
  34953. };
  34954. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  34955. var radiusv3 = this.position.subtract(this._getTargetPosition());
  34956. this.radius = radiusv3.length();
  34957. if (this.radius === 0) {
  34958. this.radius = 0.0001; // Just to avoid division by zero
  34959. }
  34960. // Alpha
  34961. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  34962. if (radiusv3.z < 0) {
  34963. this.alpha = 2 * Math.PI - this.alpha;
  34964. }
  34965. // Beta
  34966. this.beta = Math.acos(radiusv3.y / this.radius);
  34967. this._checkLimits();
  34968. };
  34969. ArcRotateCamera.prototype.setPosition = function (position) {
  34970. if (this.position.equals(position)) {
  34971. return;
  34972. }
  34973. this.position.copyFrom(position);
  34974. this.rebuildAnglesAndRadius();
  34975. };
  34976. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  34977. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  34978. if (allowSamePosition === void 0) { allowSamePosition = false; }
  34979. if (target.getBoundingInfo) {
  34980. if (toBoundingCenter) {
  34981. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  34982. }
  34983. else {
  34984. this._targetBoundingCenter = null;
  34985. }
  34986. this._targetHost = target;
  34987. this._target = this._getTargetPosition();
  34988. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  34989. }
  34990. else {
  34991. var newTarget = target;
  34992. var currentTarget = this._getTargetPosition();
  34993. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  34994. return;
  34995. }
  34996. this._targetHost = null;
  34997. this._target = newTarget;
  34998. this._targetBoundingCenter = null;
  34999. this.onMeshTargetChangedObservable.notifyObservers(null);
  35000. }
  35001. this.rebuildAnglesAndRadius();
  35002. };
  35003. ArcRotateCamera.prototype._getViewMatrix = function () {
  35004. // Compute
  35005. var cosa = Math.cos(this.alpha);
  35006. var sina = Math.sin(this.alpha);
  35007. var cosb = Math.cos(this.beta);
  35008. var sinb = Math.sin(this.beta);
  35009. if (sinb === 0) {
  35010. sinb = 0.0001;
  35011. }
  35012. var target = this._getTargetPosition();
  35013. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  35014. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  35015. if (!this._collider) {
  35016. this._collider = new BABYLON.Collider();
  35017. }
  35018. this._collider.radius = this.collisionRadius;
  35019. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  35020. this._collisionTriggered = true;
  35021. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35022. }
  35023. else {
  35024. this.position.copyFrom(this._newPosition);
  35025. var up = this.upVector;
  35026. if (this.allowUpsideDown && sinb < 0) {
  35027. up = up.clone();
  35028. up = up.negate();
  35029. }
  35030. if (this.getScene().useRightHandedSystem) {
  35031. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  35032. }
  35033. else {
  35034. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  35035. }
  35036. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  35037. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  35038. }
  35039. this._currentTarget = target;
  35040. return this._viewMatrix;
  35041. };
  35042. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  35043. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35044. meshes = meshes || this.getScene().meshes;
  35045. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  35046. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  35047. this.radius = distance * this.zoomOnFactor;
  35048. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  35049. };
  35050. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  35051. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35052. var meshesOrMinMaxVector;
  35053. var distance;
  35054. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  35055. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  35056. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  35057. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  35058. }
  35059. else {
  35060. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  35061. distance = meshesOrMinMaxVectorAndDistance.distance;
  35062. }
  35063. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  35064. if (!doNotUpdateMaxZ) {
  35065. this.maxZ = distance * 2;
  35066. }
  35067. };
  35068. /**
  35069. * @override
  35070. * Override Camera.createRigCamera
  35071. */
  35072. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  35073. var alphaShift;
  35074. switch (this.cameraRigMode) {
  35075. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35076. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35077. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35078. case BABYLON.Camera.RIG_MODE_VR:
  35079. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  35080. break;
  35081. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35082. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  35083. break;
  35084. }
  35085. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  35086. rigCam._cameraRigParams = {};
  35087. return rigCam;
  35088. };
  35089. /**
  35090. * @override
  35091. * Override Camera._updateRigCameras
  35092. */
  35093. ArcRotateCamera.prototype._updateRigCameras = function () {
  35094. var camLeft = this._rigCameras[0];
  35095. var camRight = this._rigCameras[1];
  35096. camLeft.beta = camRight.beta = this.beta;
  35097. camLeft.radius = camRight.radius = this.radius;
  35098. switch (this.cameraRigMode) {
  35099. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35100. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35101. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35102. case BABYLON.Camera.RIG_MODE_VR:
  35103. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35104. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35105. break;
  35106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35107. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35108. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35109. break;
  35110. }
  35111. _super.prototype._updateRigCameras.call(this);
  35112. };
  35113. ArcRotateCamera.prototype.dispose = function () {
  35114. this.inputs.clear();
  35115. _super.prototype.dispose.call(this);
  35116. };
  35117. ArcRotateCamera.prototype.getClassName = function () {
  35118. return "ArcRotateCamera";
  35119. };
  35120. __decorate([
  35121. BABYLON.serialize()
  35122. ], ArcRotateCamera.prototype, "alpha", void 0);
  35123. __decorate([
  35124. BABYLON.serialize()
  35125. ], ArcRotateCamera.prototype, "beta", void 0);
  35126. __decorate([
  35127. BABYLON.serialize()
  35128. ], ArcRotateCamera.prototype, "radius", void 0);
  35129. __decorate([
  35130. BABYLON.serializeAsVector3("target")
  35131. ], ArcRotateCamera.prototype, "_target", void 0);
  35132. __decorate([
  35133. BABYLON.serialize()
  35134. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  35135. __decorate([
  35136. BABYLON.serialize()
  35137. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  35138. __decorate([
  35139. BABYLON.serialize()
  35140. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  35141. __decorate([
  35142. BABYLON.serialize()
  35143. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  35144. __decorate([
  35145. BABYLON.serialize()
  35146. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  35147. __decorate([
  35148. BABYLON.serialize()
  35149. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  35150. __decorate([
  35151. BABYLON.serialize()
  35152. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  35153. __decorate([
  35154. BABYLON.serialize()
  35155. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  35156. __decorate([
  35157. BABYLON.serialize()
  35158. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  35159. __decorate([
  35160. BABYLON.serialize()
  35161. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  35162. __decorate([
  35163. BABYLON.serialize()
  35164. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  35165. __decorate([
  35166. BABYLON.serialize()
  35167. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  35168. __decorate([
  35169. BABYLON.serialize()
  35170. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  35171. __decorate([
  35172. BABYLON.serialize()
  35173. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  35174. return ArcRotateCamera;
  35175. }(BABYLON.TargetCamera));
  35176. BABYLON.ArcRotateCamera = ArcRotateCamera;
  35177. })(BABYLON || (BABYLON = {}));
  35178. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  35179. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  35180. var BABYLON;
  35181. (function (BABYLON) {
  35182. var ArcRotateCameraInputsManager = (function (_super) {
  35183. __extends(ArcRotateCameraInputsManager, _super);
  35184. function ArcRotateCameraInputsManager(camera) {
  35185. return _super.call(this, camera) || this;
  35186. }
  35187. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  35188. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  35189. return this;
  35190. };
  35191. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  35192. this.add(new BABYLON.ArcRotateCameraPointersInput());
  35193. return this;
  35194. };
  35195. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  35196. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  35197. return this;
  35198. };
  35199. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  35200. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  35201. return this;
  35202. };
  35203. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  35204. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  35205. return this;
  35206. };
  35207. return ArcRotateCameraInputsManager;
  35208. }(BABYLON.CameraInputsManager));
  35209. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  35210. })(BABYLON || (BABYLON = {}));
  35211. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  35212. var BABYLON;
  35213. (function (BABYLON) {
  35214. var HemisphericLight = (function (_super) {
  35215. __extends(HemisphericLight, _super);
  35216. /**
  35217. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  35218. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  35219. * The HemisphericLight can't cast shadows.
  35220. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35221. */
  35222. function HemisphericLight(name, direction, scene) {
  35223. var _this = _super.call(this, name, scene) || this;
  35224. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35225. _this.direction = direction || BABYLON.Vector3.Up();
  35226. return _this;
  35227. }
  35228. HemisphericLight.prototype._buildUniformLayout = function () {
  35229. this._uniformBuffer.addUniform("vLightData", 4);
  35230. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35231. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35232. this._uniformBuffer.addUniform("vLightGround", 3);
  35233. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35234. this._uniformBuffer.addUniform("depthValues", 2);
  35235. this._uniformBuffer.create();
  35236. };
  35237. /**
  35238. * Returns the string "HemisphericLight".
  35239. */
  35240. HemisphericLight.prototype.getClassName = function () {
  35241. return "HemisphericLight";
  35242. };
  35243. /**
  35244. * Sets the HemisphericLight direction towards the passed target (Vector3).
  35245. * Returns the updated direction.
  35246. */
  35247. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  35248. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  35249. return this.direction;
  35250. };
  35251. HemisphericLight.prototype.getShadowGenerator = function () {
  35252. return null;
  35253. };
  35254. /**
  35255. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  35256. * Returns the HemisphericLight.
  35257. */
  35258. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  35259. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35260. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  35261. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  35262. return this;
  35263. };
  35264. HemisphericLight.prototype._getWorldMatrix = function () {
  35265. if (!this._worldMatrix) {
  35266. this._worldMatrix = BABYLON.Matrix.Identity();
  35267. }
  35268. return this._worldMatrix;
  35269. };
  35270. /**
  35271. * Returns the integer 3.
  35272. */
  35273. HemisphericLight.prototype.getTypeID = function () {
  35274. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  35275. };
  35276. __decorate([
  35277. BABYLON.serializeAsColor3()
  35278. ], HemisphericLight.prototype, "groundColor", void 0);
  35279. __decorate([
  35280. BABYLON.serializeAsVector3()
  35281. ], HemisphericLight.prototype, "direction", void 0);
  35282. return HemisphericLight;
  35283. }(BABYLON.Light));
  35284. BABYLON.HemisphericLight = HemisphericLight;
  35285. })(BABYLON || (BABYLON = {}));
  35286. //# sourceMappingURL=babylon.hemisphericLight.js.map
  35287. var BABYLON;
  35288. (function (BABYLON) {
  35289. var ShadowLight = (function (_super) {
  35290. __extends(ShadowLight, _super);
  35291. function ShadowLight() {
  35292. var _this = _super !== null && _super.apply(this, arguments) || this;
  35293. _this._needProjectionMatrixCompute = true;
  35294. return _this;
  35295. }
  35296. Object.defineProperty(ShadowLight.prototype, "direction", {
  35297. get: function () {
  35298. return this._direction;
  35299. },
  35300. set: function (value) {
  35301. this._direction = value;
  35302. },
  35303. enumerable: true,
  35304. configurable: true
  35305. });
  35306. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  35307. get: function () {
  35308. return this._shadowMinZ;
  35309. },
  35310. set: function (value) {
  35311. this._shadowMinZ = value;
  35312. this.forceProjectionMatrixCompute();
  35313. },
  35314. enumerable: true,
  35315. configurable: true
  35316. });
  35317. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  35318. get: function () {
  35319. return this._shadowMaxZ;
  35320. },
  35321. set: function (value) {
  35322. this._shadowMaxZ = value;
  35323. this.forceProjectionMatrixCompute();
  35324. },
  35325. enumerable: true,
  35326. configurable: true
  35327. });
  35328. /**
  35329. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  35330. */
  35331. ShadowLight.prototype.computeTransformedInformation = function () {
  35332. if (this.parent && this.parent.getWorldMatrix) {
  35333. if (!this.transformedPosition) {
  35334. this.transformedPosition = BABYLON.Vector3.Zero();
  35335. }
  35336. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  35337. // In case the direction is present.
  35338. if (this.direction) {
  35339. if (!this.transformedDirection) {
  35340. this.transformedDirection = BABYLON.Vector3.Zero();
  35341. }
  35342. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  35343. }
  35344. return true;
  35345. }
  35346. return false;
  35347. };
  35348. /**
  35349. * Return the depth scale used for the shadow map.
  35350. */
  35351. ShadowLight.prototype.getDepthScale = function () {
  35352. return 50.0;
  35353. };
  35354. /**
  35355. * Returns the light direction (Vector3) for any passed face index.
  35356. */
  35357. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  35358. return this.transformedDirection ? this.transformedDirection : this.direction;
  35359. };
  35360. /**
  35361. * Returns the DirectionalLight absolute position in the World.
  35362. */
  35363. ShadowLight.prototype.getAbsolutePosition = function () {
  35364. return this.transformedPosition ? this.transformedPosition : this.position;
  35365. };
  35366. /**
  35367. * Sets the DirectionalLight direction toward the passed target (Vector3).
  35368. * Returns the updated DirectionalLight direction (Vector3).
  35369. */
  35370. ShadowLight.prototype.setDirectionToTarget = function (target) {
  35371. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  35372. return this.direction;
  35373. };
  35374. /**
  35375. * Returns the light rotation (Vector3).
  35376. */
  35377. ShadowLight.prototype.getRotation = function () {
  35378. this.direction.normalize();
  35379. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  35380. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  35381. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  35382. };
  35383. /**
  35384. * Boolean : false by default.
  35385. */
  35386. ShadowLight.prototype.needCube = function () {
  35387. return false;
  35388. };
  35389. /**
  35390. * Specifies wether or not the projection matrix should be recomputed this frame.
  35391. */
  35392. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  35393. return this._needProjectionMatrixCompute;
  35394. };
  35395. /**
  35396. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  35397. */
  35398. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  35399. this._needProjectionMatrixCompute = true;
  35400. };
  35401. /**
  35402. * Get the world matrix of the sahdow lights.
  35403. */
  35404. ShadowLight.prototype._getWorldMatrix = function () {
  35405. if (!this._worldMatrix) {
  35406. this._worldMatrix = BABYLON.Matrix.Identity();
  35407. }
  35408. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  35409. return this._worldMatrix;
  35410. };
  35411. /**
  35412. * Gets the minZ used for shadow according to both the scene and the light.
  35413. * @param activeCamera
  35414. */
  35415. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  35416. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  35417. };
  35418. /**
  35419. * Gets the maxZ used for shadow according to both the scene and the light.
  35420. * @param activeCamera
  35421. */
  35422. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  35423. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  35424. };
  35425. /**
  35426. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  35427. * Returns the light.
  35428. */
  35429. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35430. if (this.customProjectionMatrixBuilder) {
  35431. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  35432. }
  35433. else {
  35434. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35435. }
  35436. return this;
  35437. };
  35438. __decorate([
  35439. BABYLON.serializeAsVector3()
  35440. ], ShadowLight.prototype, "position", void 0);
  35441. __decorate([
  35442. BABYLON.serializeAsVector3()
  35443. ], ShadowLight.prototype, "direction", null);
  35444. __decorate([
  35445. BABYLON.serialize()
  35446. ], ShadowLight.prototype, "shadowMinZ", null);
  35447. __decorate([
  35448. BABYLON.serialize()
  35449. ], ShadowLight.prototype, "shadowMaxZ", null);
  35450. return ShadowLight;
  35451. }(BABYLON.Light));
  35452. BABYLON.ShadowLight = ShadowLight;
  35453. })(BABYLON || (BABYLON = {}));
  35454. //# sourceMappingURL=babylon.shadowLight.js.map
  35455. var BABYLON;
  35456. (function (BABYLON) {
  35457. var PointLight = (function (_super) {
  35458. __extends(PointLight, _super);
  35459. /**
  35460. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  35461. * A PointLight emits the light in every direction.
  35462. * It can cast shadows.
  35463. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  35464. * ```javascript
  35465. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  35466. * ```
  35467. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35468. */
  35469. function PointLight(name, position, scene) {
  35470. var _this = _super.call(this, name, scene) || this;
  35471. _this._shadowAngle = Math.PI / 2;
  35472. _this.position = position;
  35473. return _this;
  35474. }
  35475. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  35476. /**
  35477. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35478. * This specifies what angle the shadow will use to be created.
  35479. *
  35480. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35481. */
  35482. get: function () {
  35483. return this._shadowAngle;
  35484. },
  35485. /**
  35486. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35487. * This specifies what angle the shadow will use to be created.
  35488. *
  35489. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35490. */
  35491. set: function (value) {
  35492. this._shadowAngle = value;
  35493. this.forceProjectionMatrixCompute();
  35494. },
  35495. enumerable: true,
  35496. configurable: true
  35497. });
  35498. Object.defineProperty(PointLight.prototype, "direction", {
  35499. get: function () {
  35500. return this._direction;
  35501. },
  35502. /**
  35503. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35504. */
  35505. set: function (value) {
  35506. var previousNeedCube = this.needCube();
  35507. this._direction = value;
  35508. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  35509. this._shadowGenerator.recreateShadowMap();
  35510. }
  35511. },
  35512. enumerable: true,
  35513. configurable: true
  35514. });
  35515. /**
  35516. * Returns the string "PointLight"
  35517. */
  35518. PointLight.prototype.getClassName = function () {
  35519. return "PointLight";
  35520. };
  35521. /**
  35522. * Returns the integer 0.
  35523. */
  35524. PointLight.prototype.getTypeID = function () {
  35525. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  35526. };
  35527. /**
  35528. * Specifies wether or not the shadowmap should be a cube texture.
  35529. */
  35530. PointLight.prototype.needCube = function () {
  35531. return !this.direction;
  35532. };
  35533. /**
  35534. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  35535. */
  35536. PointLight.prototype.getShadowDirection = function (faceIndex) {
  35537. if (this.direction) {
  35538. return _super.prototype.getShadowDirection.call(this, faceIndex);
  35539. }
  35540. else {
  35541. switch (faceIndex) {
  35542. case 0:
  35543. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  35544. case 1:
  35545. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  35546. case 2:
  35547. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  35548. case 3:
  35549. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  35550. case 4:
  35551. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  35552. case 5:
  35553. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  35554. }
  35555. }
  35556. return BABYLON.Vector3.Zero();
  35557. };
  35558. /**
  35559. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  35560. * - fov = PI / 2
  35561. * - aspect ratio : 1.0
  35562. * - z-near and far equal to the active camera minZ and maxZ.
  35563. * Returns the PointLight.
  35564. */
  35565. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35566. var activeCamera = this.getScene().activeCamera;
  35567. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35568. };
  35569. PointLight.prototype._buildUniformLayout = function () {
  35570. this._uniformBuffer.addUniform("vLightData", 4);
  35571. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35572. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35573. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35574. this._uniformBuffer.addUniform("depthValues", 2);
  35575. this._uniformBuffer.create();
  35576. };
  35577. /**
  35578. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  35579. * Returns the PointLight.
  35580. */
  35581. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  35582. if (this.computeTransformedInformation()) {
  35583. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  35584. return this;
  35585. }
  35586. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  35587. return this;
  35588. };
  35589. __decorate([
  35590. BABYLON.serialize()
  35591. ], PointLight.prototype, "shadowAngle", null);
  35592. return PointLight;
  35593. }(BABYLON.ShadowLight));
  35594. BABYLON.PointLight = PointLight;
  35595. })(BABYLON || (BABYLON = {}));
  35596. //# sourceMappingURL=babylon.pointLight.js.map
  35597. /// <reference path="babylon.light.ts" />
  35598. var BABYLON;
  35599. (function (BABYLON) {
  35600. var DirectionalLight = (function (_super) {
  35601. __extends(DirectionalLight, _super);
  35602. /**
  35603. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  35604. * The directional light is emitted from everywhere in the given direction.
  35605. * It can cast shawdows.
  35606. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35607. */
  35608. function DirectionalLight(name, direction, scene) {
  35609. var _this = _super.call(this, name, scene) || this;
  35610. _this._shadowFrustumSize = 0;
  35611. _this._shadowOrthoScale = 0.5;
  35612. _this.autoUpdateExtends = true;
  35613. // Cache
  35614. _this._orthoLeft = Number.MAX_VALUE;
  35615. _this._orthoRight = Number.MIN_VALUE;
  35616. _this._orthoTop = Number.MIN_VALUE;
  35617. _this._orthoBottom = Number.MAX_VALUE;
  35618. _this.position = direction.scale(-1.0);
  35619. _this.direction = direction;
  35620. return _this;
  35621. }
  35622. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  35623. /**
  35624. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  35625. */
  35626. get: function () {
  35627. return this._shadowFrustumSize;
  35628. },
  35629. /**
  35630. * Specifies a fix frustum size for the shadow generation.
  35631. */
  35632. set: function (value) {
  35633. this._shadowFrustumSize = value;
  35634. this.forceProjectionMatrixCompute();
  35635. },
  35636. enumerable: true,
  35637. configurable: true
  35638. });
  35639. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  35640. get: function () {
  35641. return this._shadowOrthoScale;
  35642. },
  35643. set: function (value) {
  35644. this._shadowOrthoScale = value;
  35645. this.forceProjectionMatrixCompute();
  35646. },
  35647. enumerable: true,
  35648. configurable: true
  35649. });
  35650. /**
  35651. * Returns the string "DirectionalLight".
  35652. */
  35653. DirectionalLight.prototype.getClassName = function () {
  35654. return "DirectionalLight";
  35655. };
  35656. /**
  35657. * Returns the integer 1.
  35658. */
  35659. DirectionalLight.prototype.getTypeID = function () {
  35660. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  35661. };
  35662. /**
  35663. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  35664. * Returns the DirectionalLight Shadow projection matrix.
  35665. */
  35666. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35667. if (this.shadowFrustumSize > 0) {
  35668. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  35669. }
  35670. else {
  35671. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35672. }
  35673. };
  35674. /**
  35675. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  35676. * Returns the DirectionalLight Shadow projection matrix.
  35677. */
  35678. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  35679. var activeCamera = this.getScene().activeCamera;
  35680. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  35681. };
  35682. /**
  35683. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  35684. * Returns the DirectionalLight Shadow projection matrix.
  35685. */
  35686. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35687. var activeCamera = this.getScene().activeCamera;
  35688. // Check extends
  35689. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  35690. var tempVector3 = BABYLON.Vector3.Zero();
  35691. this._orthoLeft = Number.MAX_VALUE;
  35692. this._orthoRight = Number.MIN_VALUE;
  35693. this._orthoTop = Number.MIN_VALUE;
  35694. this._orthoBottom = Number.MAX_VALUE;
  35695. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  35696. var mesh = renderList[meshIndex];
  35697. if (!mesh) {
  35698. continue;
  35699. }
  35700. var boundingInfo = mesh.getBoundingInfo();
  35701. if (!boundingInfo) {
  35702. continue;
  35703. }
  35704. var boundingBox = boundingInfo.boundingBox;
  35705. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  35706. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  35707. if (tempVector3.x < this._orthoLeft)
  35708. this._orthoLeft = tempVector3.x;
  35709. if (tempVector3.y < this._orthoBottom)
  35710. this._orthoBottom = tempVector3.y;
  35711. if (tempVector3.x > this._orthoRight)
  35712. this._orthoRight = tempVector3.x;
  35713. if (tempVector3.y > this._orthoTop)
  35714. this._orthoTop = tempVector3.y;
  35715. }
  35716. }
  35717. }
  35718. var xOffset = this._orthoRight - this._orthoLeft;
  35719. var yOffset = this._orthoTop - this._orthoBottom;
  35720. 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);
  35721. };
  35722. DirectionalLight.prototype._buildUniformLayout = function () {
  35723. this._uniformBuffer.addUniform("vLightData", 4);
  35724. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35725. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35726. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35727. this._uniformBuffer.addUniform("depthValues", 2);
  35728. this._uniformBuffer.create();
  35729. };
  35730. /**
  35731. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  35732. * Returns the DirectionalLight.
  35733. */
  35734. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  35735. if (this.computeTransformedInformation()) {
  35736. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  35737. return this;
  35738. }
  35739. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  35740. return this;
  35741. };
  35742. /**
  35743. * Gets the minZ used for shadow according to both the scene and the light.
  35744. *
  35745. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35746. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35747. * @param activeCamera
  35748. */
  35749. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  35750. return 1;
  35751. };
  35752. /**
  35753. * Gets the maxZ used for shadow according to both the scene and the light.
  35754. *
  35755. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  35756. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  35757. * @param activeCamera
  35758. */
  35759. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  35760. return 1;
  35761. };
  35762. __decorate([
  35763. BABYLON.serialize()
  35764. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  35765. __decorate([
  35766. BABYLON.serialize()
  35767. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  35768. __decorate([
  35769. BABYLON.serialize()
  35770. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  35771. return DirectionalLight;
  35772. }(BABYLON.ShadowLight));
  35773. BABYLON.DirectionalLight = DirectionalLight;
  35774. })(BABYLON || (BABYLON = {}));
  35775. //# sourceMappingURL=babylon.directionalLight.js.map
  35776. var BABYLON;
  35777. (function (BABYLON) {
  35778. var SpotLight = (function (_super) {
  35779. __extends(SpotLight, _super);
  35780. /**
  35781. * Creates a SpotLight object in the scene with the passed parameters :
  35782. * - `position` (Vector3) is the initial SpotLight position,
  35783. * - `direction` (Vector3) is the initial SpotLight direction,
  35784. * - `angle` (float, in radians) is the spot light cone angle,
  35785. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  35786. * A spot light is a simply light oriented cone.
  35787. * It can cast shadows.
  35788. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35789. */
  35790. function SpotLight(name, position, direction, angle, exponent, scene) {
  35791. var _this = _super.call(this, name, scene) || this;
  35792. _this.position = position;
  35793. _this.direction = direction;
  35794. _this.angle = angle;
  35795. _this.exponent = exponent;
  35796. return _this;
  35797. }
  35798. Object.defineProperty(SpotLight.prototype, "angle", {
  35799. get: function () {
  35800. return this._angle;
  35801. },
  35802. set: function (value) {
  35803. this._angle = value;
  35804. this.forceProjectionMatrixCompute();
  35805. },
  35806. enumerable: true,
  35807. configurable: true
  35808. });
  35809. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  35810. get: function () {
  35811. return this._shadowAngleScale;
  35812. },
  35813. /**
  35814. * Allows scaling the angle of the light for shadow generation only.
  35815. */
  35816. set: function (value) {
  35817. this._shadowAngleScale = value;
  35818. this.forceProjectionMatrixCompute();
  35819. },
  35820. enumerable: true,
  35821. configurable: true
  35822. });
  35823. /**
  35824. * Returns the string "SpotLight".
  35825. */
  35826. SpotLight.prototype.getClassName = function () {
  35827. return "SpotLight";
  35828. };
  35829. /**
  35830. * Returns the integer 2.
  35831. */
  35832. SpotLight.prototype.getTypeID = function () {
  35833. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  35834. };
  35835. /**
  35836. * 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.
  35837. * Returns the SpotLight.
  35838. */
  35839. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35840. var activeCamera = this.getScene().activeCamera;
  35841. this._shadowAngleScale = this._shadowAngleScale || 1;
  35842. var angle = this._shadowAngleScale * this._angle;
  35843. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35844. };
  35845. SpotLight.prototype._buildUniformLayout = function () {
  35846. this._uniformBuffer.addUniform("vLightData", 4);
  35847. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35848. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35849. this._uniformBuffer.addUniform("vLightDirection", 3);
  35850. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35851. this._uniformBuffer.addUniform("depthValues", 2);
  35852. this._uniformBuffer.create();
  35853. };
  35854. /**
  35855. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  35856. * Return the SpotLight.
  35857. */
  35858. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  35859. var normalizeDirection;
  35860. if (this.computeTransformedInformation()) {
  35861. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  35862. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  35863. }
  35864. else {
  35865. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  35866. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35867. }
  35868. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  35869. return this;
  35870. };
  35871. __decorate([
  35872. BABYLON.serialize()
  35873. ], SpotLight.prototype, "angle", null);
  35874. __decorate([
  35875. BABYLON.serialize()
  35876. /**
  35877. * Allows scaling the angle of the light for shadow generation only.
  35878. */
  35879. ], SpotLight.prototype, "shadowAngleScale", null);
  35880. __decorate([
  35881. BABYLON.serialize()
  35882. ], SpotLight.prototype, "exponent", void 0);
  35883. return SpotLight;
  35884. }(BABYLON.ShadowLight));
  35885. BABYLON.SpotLight = SpotLight;
  35886. })(BABYLON || (BABYLON = {}));
  35887. //# sourceMappingURL=babylon.spotLight.js.map
  35888. var BABYLON;
  35889. (function (BABYLON) {
  35890. var AnimationRange = (function () {
  35891. function AnimationRange(name, from, to) {
  35892. this.name = name;
  35893. this.from = from;
  35894. this.to = to;
  35895. }
  35896. AnimationRange.prototype.clone = function () {
  35897. return new AnimationRange(this.name, this.from, this.to);
  35898. };
  35899. return AnimationRange;
  35900. }());
  35901. BABYLON.AnimationRange = AnimationRange;
  35902. /**
  35903. * Composed of a frame, and an action function
  35904. */
  35905. var AnimationEvent = (function () {
  35906. function AnimationEvent(frame, action, onlyOnce) {
  35907. this.frame = frame;
  35908. this.action = action;
  35909. this.onlyOnce = onlyOnce;
  35910. this.isDone = false;
  35911. }
  35912. return AnimationEvent;
  35913. }());
  35914. BABYLON.AnimationEvent = AnimationEvent;
  35915. var PathCursor = (function () {
  35916. function PathCursor(path) {
  35917. this.path = path;
  35918. this._onchange = new Array();
  35919. this.value = 0;
  35920. this.animations = new Array();
  35921. }
  35922. PathCursor.prototype.getPoint = function () {
  35923. var point = this.path.getPointAtLengthPosition(this.value);
  35924. return new BABYLON.Vector3(point.x, 0, point.y);
  35925. };
  35926. PathCursor.prototype.moveAhead = function (step) {
  35927. if (step === void 0) { step = 0.002; }
  35928. this.move(step);
  35929. return this;
  35930. };
  35931. PathCursor.prototype.moveBack = function (step) {
  35932. if (step === void 0) { step = 0.002; }
  35933. this.move(-step);
  35934. return this;
  35935. };
  35936. PathCursor.prototype.move = function (step) {
  35937. if (Math.abs(step) > 1) {
  35938. throw "step size should be less than 1.";
  35939. }
  35940. this.value += step;
  35941. this.ensureLimits();
  35942. this.raiseOnChange();
  35943. return this;
  35944. };
  35945. PathCursor.prototype.ensureLimits = function () {
  35946. while (this.value > 1) {
  35947. this.value -= 1;
  35948. }
  35949. while (this.value < 0) {
  35950. this.value += 1;
  35951. }
  35952. return this;
  35953. };
  35954. // used by animation engine
  35955. PathCursor.prototype.markAsDirty = function (propertyName) {
  35956. this.ensureLimits();
  35957. this.raiseOnChange();
  35958. return this;
  35959. };
  35960. PathCursor.prototype.raiseOnChange = function () {
  35961. var _this = this;
  35962. this._onchange.forEach(function (f) { return f(_this); });
  35963. return this;
  35964. };
  35965. PathCursor.prototype.onchange = function (f) {
  35966. this._onchange.push(f);
  35967. return this;
  35968. };
  35969. return PathCursor;
  35970. }());
  35971. BABYLON.PathCursor = PathCursor;
  35972. var Animation = (function () {
  35973. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  35974. this.name = name;
  35975. this.targetProperty = targetProperty;
  35976. this.framePerSecond = framePerSecond;
  35977. this.dataType = dataType;
  35978. this.loopMode = loopMode;
  35979. this.enableBlending = enableBlending;
  35980. this._offsetsCache = {};
  35981. this._highLimitsCache = {};
  35982. this._stopped = false;
  35983. this._blendingFactor = 0;
  35984. // The set of event that will be linked to this animation
  35985. this._events = new Array();
  35986. this.allowMatricesInterpolation = false;
  35987. this.blendingSpeed = 0.01;
  35988. this._ranges = {};
  35989. this.targetPropertyPath = targetProperty.split(".");
  35990. this.dataType = dataType;
  35991. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  35992. }
  35993. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  35994. var dataType = undefined;
  35995. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  35996. dataType = Animation.ANIMATIONTYPE_FLOAT;
  35997. }
  35998. else if (from instanceof BABYLON.Quaternion) {
  35999. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  36000. }
  36001. else if (from instanceof BABYLON.Vector3) {
  36002. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  36003. }
  36004. else if (from instanceof BABYLON.Vector2) {
  36005. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  36006. }
  36007. else if (from instanceof BABYLON.Color3) {
  36008. dataType = Animation.ANIMATIONTYPE_COLOR3;
  36009. }
  36010. else if (from instanceof BABYLON.Size) {
  36011. dataType = Animation.ANIMATIONTYPE_SIZE;
  36012. }
  36013. if (dataType == undefined) {
  36014. return null;
  36015. }
  36016. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  36017. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  36018. animation.setKeys(keys);
  36019. if (easingFunction !== undefined) {
  36020. animation.setEasingFunction(easingFunction);
  36021. }
  36022. return animation;
  36023. };
  36024. /**
  36025. * Sets up an animation.
  36026. * @param property the property to animate
  36027. * @param animationType the animation type to apply
  36028. * @param easingFunction the easing function used in the animation
  36029. * @returns The created animation
  36030. */
  36031. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  36032. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36033. animation.setEasingFunction(easingFunction);
  36034. return animation;
  36035. };
  36036. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36037. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36038. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36039. };
  36040. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36041. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36042. node.animations.push(animation);
  36043. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36044. };
  36045. /**
  36046. * Transition property of the Camera to the target Value.
  36047. * @param property The property to transition
  36048. * @param targetValue The target Value of the property
  36049. * @param host The object where the property to animate belongs
  36050. * @param scene Scene used to run the animation
  36051. * @param frameRate Framerate (in frame/s) to use
  36052. * @param transition The transition type we want to use
  36053. * @param duration The duration of the animation, in milliseconds
  36054. * @param onAnimationEnd Call back trigger at the end of the animation.
  36055. */
  36056. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  36057. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  36058. if (duration <= 0) {
  36059. host[property] = targetValue;
  36060. if (onAnimationEnd) {
  36061. onAnimationEnd();
  36062. }
  36063. return;
  36064. }
  36065. var endFrame = frameRate * (duration / 1000);
  36066. transition.setKeys([{
  36067. frame: 0,
  36068. value: host[property].clone ? host[property].clone() : host[property]
  36069. },
  36070. {
  36071. frame: endFrame,
  36072. value: targetValue
  36073. }]);
  36074. if (!host.animations) {
  36075. host.animations = [];
  36076. }
  36077. host.animations.push(transition);
  36078. var animation = scene.beginAnimation(host, 0, endFrame, false);
  36079. animation.onAnimationEnd = onAnimationEnd;
  36080. return animation;
  36081. };
  36082. // Methods
  36083. /**
  36084. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  36085. */
  36086. Animation.prototype.toString = function (fullDetails) {
  36087. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  36088. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  36089. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  36090. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  36091. if (fullDetails) {
  36092. ret += ", Ranges: {";
  36093. var first = true;
  36094. for (var name in this._ranges) {
  36095. if (first) {
  36096. ret += ", ";
  36097. first = false;
  36098. }
  36099. ret += name;
  36100. }
  36101. ret += "}";
  36102. }
  36103. return ret;
  36104. };
  36105. /**
  36106. * Add an event to this animation.
  36107. */
  36108. Animation.prototype.addEvent = function (event) {
  36109. this._events.push(event);
  36110. };
  36111. /**
  36112. * Remove all events found at the given frame
  36113. * @param frame
  36114. */
  36115. Animation.prototype.removeEvents = function (frame) {
  36116. for (var index = 0; index < this._events.length; index++) {
  36117. if (this._events[index].frame === frame) {
  36118. this._events.splice(index, 1);
  36119. index--;
  36120. }
  36121. }
  36122. };
  36123. Animation.prototype.createRange = function (name, from, to) {
  36124. // check name not already in use; could happen for bones after serialized
  36125. if (!this._ranges[name]) {
  36126. this._ranges[name] = new AnimationRange(name, from, to);
  36127. }
  36128. };
  36129. Animation.prototype.deleteRange = function (name, deleteFrames) {
  36130. if (deleteFrames === void 0) { deleteFrames = true; }
  36131. if (this._ranges[name]) {
  36132. if (deleteFrames) {
  36133. var from = this._ranges[name].from;
  36134. var to = this._ranges[name].to;
  36135. // this loop MUST go high to low for multiple splices to work
  36136. for (var key = this._keys.length - 1; key >= 0; key--) {
  36137. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  36138. this._keys.splice(key, 1);
  36139. }
  36140. }
  36141. }
  36142. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  36143. }
  36144. };
  36145. Animation.prototype.getRange = function (name) {
  36146. return this._ranges[name];
  36147. };
  36148. Animation.prototype.reset = function () {
  36149. this._offsetsCache = {};
  36150. this._highLimitsCache = {};
  36151. this.currentFrame = 0;
  36152. this._blendingFactor = 0;
  36153. this._originalBlendValue = null;
  36154. };
  36155. Animation.prototype.isStopped = function () {
  36156. return this._stopped;
  36157. };
  36158. Animation.prototype.getKeys = function () {
  36159. return this._keys;
  36160. };
  36161. Animation.prototype.getHighestFrame = function () {
  36162. var ret = 0;
  36163. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  36164. if (ret < this._keys[key].frame) {
  36165. ret = this._keys[key].frame;
  36166. }
  36167. }
  36168. return ret;
  36169. };
  36170. Animation.prototype.getEasingFunction = function () {
  36171. return this._easingFunction;
  36172. };
  36173. Animation.prototype.setEasingFunction = function (easingFunction) {
  36174. this._easingFunction = easingFunction;
  36175. };
  36176. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  36177. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  36178. };
  36179. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36180. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36181. };
  36182. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  36183. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  36184. };
  36185. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36186. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  36187. };
  36188. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  36189. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  36190. };
  36191. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36192. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36193. };
  36194. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  36195. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  36196. };
  36197. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36198. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36199. };
  36200. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  36201. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  36202. };
  36203. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  36204. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  36205. };
  36206. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  36207. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  36208. };
  36209. Animation.prototype.clone = function () {
  36210. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  36211. clone.enableBlending = this.enableBlending;
  36212. clone.blendingSpeed = this.blendingSpeed;
  36213. if (this._keys) {
  36214. clone.setKeys(this._keys);
  36215. }
  36216. if (this._ranges) {
  36217. clone._ranges = {};
  36218. for (var name in this._ranges) {
  36219. clone._ranges[name] = this._ranges[name].clone();
  36220. }
  36221. }
  36222. return clone;
  36223. };
  36224. Animation.prototype.setKeys = function (values) {
  36225. this._keys = values.slice(0);
  36226. this._offsetsCache = {};
  36227. this._highLimitsCache = {};
  36228. };
  36229. Animation.prototype._getKeyValue = function (value) {
  36230. if (typeof value === "function") {
  36231. return value();
  36232. }
  36233. return value;
  36234. };
  36235. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  36236. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  36237. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  36238. }
  36239. this.currentFrame = currentFrame;
  36240. // Try to get a hash to find the right key
  36241. 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));
  36242. if (this._keys[startKeyIndex].frame >= currentFrame) {
  36243. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  36244. startKeyIndex--;
  36245. }
  36246. }
  36247. for (var key = startKeyIndex; key < this._keys.length; key++) {
  36248. var endKey = this._keys[key + 1];
  36249. if (endKey.frame >= currentFrame) {
  36250. var startKey = this._keys[key];
  36251. var startValue = this._getKeyValue(startKey.value);
  36252. var endValue = this._getKeyValue(endKey.value);
  36253. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  36254. var frameDelta = endKey.frame - startKey.frame;
  36255. // gradient : percent of currentFrame between the frame inf and the frame sup
  36256. var gradient = (currentFrame - startKey.frame) / frameDelta;
  36257. // check for easingFunction and correction of gradient
  36258. if (this._easingFunction != null) {
  36259. gradient = this._easingFunction.ease(gradient);
  36260. }
  36261. switch (this.dataType) {
  36262. // Float
  36263. case Animation.ANIMATIONTYPE_FLOAT:
  36264. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  36265. switch (loopMode) {
  36266. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36267. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36268. return floatValue;
  36269. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36270. return offsetValue * repeatCount + floatValue;
  36271. }
  36272. break;
  36273. // Quaternion
  36274. case Animation.ANIMATIONTYPE_QUATERNION:
  36275. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  36276. switch (loopMode) {
  36277. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36278. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36279. return quatValue;
  36280. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36281. return quatValue.add(offsetValue.scale(repeatCount));
  36282. }
  36283. return quatValue;
  36284. // Vector3
  36285. case Animation.ANIMATIONTYPE_VECTOR3:
  36286. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  36287. switch (loopMode) {
  36288. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36289. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36290. return vec3Value;
  36291. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36292. return vec3Value.add(offsetValue.scale(repeatCount));
  36293. }
  36294. // Vector2
  36295. case Animation.ANIMATIONTYPE_VECTOR2:
  36296. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  36297. switch (loopMode) {
  36298. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36299. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36300. return vec2Value;
  36301. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36302. return vec2Value.add(offsetValue.scale(repeatCount));
  36303. }
  36304. // Size
  36305. case Animation.ANIMATIONTYPE_SIZE:
  36306. switch (loopMode) {
  36307. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36308. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36309. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  36310. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36311. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36312. }
  36313. // Color3
  36314. case Animation.ANIMATIONTYPE_COLOR3:
  36315. switch (loopMode) {
  36316. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36317. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36318. return this.color3InterpolateFunction(startValue, endValue, gradient);
  36319. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36320. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36321. }
  36322. // Matrix
  36323. case Animation.ANIMATIONTYPE_MATRIX:
  36324. switch (loopMode) {
  36325. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36326. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36327. if (this.allowMatricesInterpolation) {
  36328. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  36329. }
  36330. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36331. return startValue;
  36332. }
  36333. default:
  36334. break;
  36335. }
  36336. break;
  36337. }
  36338. }
  36339. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  36340. };
  36341. Animation.prototype.setValue = function (currentValue, blend) {
  36342. if (blend === void 0) { blend = false; }
  36343. // Set value
  36344. var path;
  36345. var destination;
  36346. if (this.targetPropertyPath.length > 1) {
  36347. var property = this._target[this.targetPropertyPath[0]];
  36348. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  36349. property = property[this.targetPropertyPath[index]];
  36350. }
  36351. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  36352. destination = property;
  36353. }
  36354. else {
  36355. path = this.targetPropertyPath[0];
  36356. destination = this._target;
  36357. }
  36358. // Blending
  36359. if (this.enableBlending && this._blendingFactor <= 1.0) {
  36360. if (!this._originalBlendValue) {
  36361. if (destination[path].clone) {
  36362. this._originalBlendValue = destination[path].clone();
  36363. }
  36364. else {
  36365. this._originalBlendValue = destination[path];
  36366. }
  36367. }
  36368. if (this._originalBlendValue.prototype) {
  36369. if (this._originalBlendValue.prototype.Lerp) {
  36370. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  36371. }
  36372. else {
  36373. destination[path] = currentValue;
  36374. }
  36375. }
  36376. else if (this._originalBlendValue.m) {
  36377. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  36378. }
  36379. else {
  36380. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  36381. }
  36382. this._blendingFactor += this.blendingSpeed;
  36383. }
  36384. else {
  36385. destination[path] = currentValue;
  36386. }
  36387. if (this._target.markAsDirty) {
  36388. this._target.markAsDirty(this.targetProperty);
  36389. }
  36390. };
  36391. Animation.prototype.goToFrame = function (frame) {
  36392. if (frame < this._keys[0].frame) {
  36393. frame = this._keys[0].frame;
  36394. }
  36395. else if (frame > this._keys[this._keys.length - 1].frame) {
  36396. frame = this._keys[this._keys.length - 1].frame;
  36397. }
  36398. var currentValue = this._interpolate(frame, 0, this.loopMode);
  36399. this.setValue(currentValue);
  36400. };
  36401. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  36402. if (blend === void 0) { blend = false; }
  36403. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  36404. this._stopped = true;
  36405. return false;
  36406. }
  36407. var returnValue = true;
  36408. // Adding a start key at frame 0 if missing
  36409. if (this._keys[0].frame !== 0) {
  36410. var newKey = { frame: 0, value: this._keys[0].value };
  36411. this._keys.splice(0, 0, newKey);
  36412. }
  36413. // Check limits
  36414. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  36415. from = this._keys[0].frame;
  36416. }
  36417. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  36418. to = this._keys[this._keys.length - 1].frame;
  36419. }
  36420. //to and from cannot be the same key
  36421. if (from === to) {
  36422. from++;
  36423. }
  36424. // Compute ratio
  36425. var range = to - from;
  36426. var offsetValue;
  36427. // ratio represents the frame delta between from and to
  36428. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  36429. var highLimitValue = 0;
  36430. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  36431. returnValue = false;
  36432. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  36433. }
  36434. else {
  36435. // Get max value if required
  36436. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  36437. var keyOffset = to.toString() + from.toString();
  36438. if (!this._offsetsCache[keyOffset]) {
  36439. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36440. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36441. switch (this.dataType) {
  36442. // Float
  36443. case Animation.ANIMATIONTYPE_FLOAT:
  36444. this._offsetsCache[keyOffset] = toValue - fromValue;
  36445. break;
  36446. // Quaternion
  36447. case Animation.ANIMATIONTYPE_QUATERNION:
  36448. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36449. break;
  36450. // Vector3
  36451. case Animation.ANIMATIONTYPE_VECTOR3:
  36452. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36453. // Vector2
  36454. case Animation.ANIMATIONTYPE_VECTOR2:
  36455. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36456. // Size
  36457. case Animation.ANIMATIONTYPE_SIZE:
  36458. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36459. // Color3
  36460. case Animation.ANIMATIONTYPE_COLOR3:
  36461. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36462. default:
  36463. break;
  36464. }
  36465. this._highLimitsCache[keyOffset] = toValue;
  36466. }
  36467. highLimitValue = this._highLimitsCache[keyOffset];
  36468. offsetValue = this._offsetsCache[keyOffset];
  36469. }
  36470. }
  36471. if (offsetValue === undefined) {
  36472. switch (this.dataType) {
  36473. // Float
  36474. case Animation.ANIMATIONTYPE_FLOAT:
  36475. offsetValue = 0;
  36476. break;
  36477. // Quaternion
  36478. case Animation.ANIMATIONTYPE_QUATERNION:
  36479. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  36480. break;
  36481. // Vector3
  36482. case Animation.ANIMATIONTYPE_VECTOR3:
  36483. offsetValue = BABYLON.Vector3.Zero();
  36484. break;
  36485. // Vector2
  36486. case Animation.ANIMATIONTYPE_VECTOR2:
  36487. offsetValue = BABYLON.Vector2.Zero();
  36488. break;
  36489. // Size
  36490. case Animation.ANIMATIONTYPE_SIZE:
  36491. offsetValue = BABYLON.Size.Zero();
  36492. break;
  36493. // Color3
  36494. case Animation.ANIMATIONTYPE_COLOR3:
  36495. offsetValue = BABYLON.Color3.Black();
  36496. }
  36497. }
  36498. // Compute value
  36499. var repeatCount = (ratio / range) >> 0;
  36500. var currentFrame = returnValue ? from + ratio % range : to;
  36501. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  36502. // Set value
  36503. this.setValue(currentValue);
  36504. // Check events
  36505. for (var index = 0; index < this._events.length; index++) {
  36506. // Make sure current frame has passed event frame and that event frame is within the current range
  36507. // Also, handle both forward and reverse animations
  36508. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  36509. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  36510. var event = this._events[index];
  36511. if (!event.isDone) {
  36512. // If event should be done only once, remove it.
  36513. if (event.onlyOnce) {
  36514. this._events.splice(index, 1);
  36515. index--;
  36516. }
  36517. event.isDone = true;
  36518. event.action();
  36519. } // Don't do anything if the event has already be done.
  36520. }
  36521. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  36522. // reset event, the animation is looping
  36523. this._events[index].isDone = false;
  36524. }
  36525. }
  36526. if (!returnValue) {
  36527. this._stopped = true;
  36528. }
  36529. return returnValue;
  36530. };
  36531. Animation.prototype.serialize = function () {
  36532. var serializationObject = {};
  36533. serializationObject.name = this.name;
  36534. serializationObject.property = this.targetProperty;
  36535. serializationObject.framePerSecond = this.framePerSecond;
  36536. serializationObject.dataType = this.dataType;
  36537. serializationObject.loopBehavior = this.loopMode;
  36538. serializationObject.enableBlending = this.enableBlending;
  36539. serializationObject.blendingSpeed = this.blendingSpeed;
  36540. var dataType = this.dataType;
  36541. serializationObject.keys = [];
  36542. var keys = this.getKeys();
  36543. for (var index = 0; index < keys.length; index++) {
  36544. var animationKey = keys[index];
  36545. var key = {};
  36546. key.frame = animationKey.frame;
  36547. switch (dataType) {
  36548. case Animation.ANIMATIONTYPE_FLOAT:
  36549. key.values = [animationKey.value];
  36550. break;
  36551. case Animation.ANIMATIONTYPE_QUATERNION:
  36552. case Animation.ANIMATIONTYPE_MATRIX:
  36553. case Animation.ANIMATIONTYPE_VECTOR3:
  36554. case Animation.ANIMATIONTYPE_COLOR3:
  36555. key.values = animationKey.value.asArray();
  36556. break;
  36557. }
  36558. serializationObject.keys.push(key);
  36559. }
  36560. serializationObject.ranges = [];
  36561. for (var name in this._ranges) {
  36562. var range = {};
  36563. range.name = name;
  36564. range.from = this._ranges[name].from;
  36565. range.to = this._ranges[name].to;
  36566. serializationObject.ranges.push(range);
  36567. }
  36568. return serializationObject;
  36569. };
  36570. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  36571. get: function () {
  36572. return Animation._ANIMATIONTYPE_FLOAT;
  36573. },
  36574. enumerable: true,
  36575. configurable: true
  36576. });
  36577. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  36578. get: function () {
  36579. return Animation._ANIMATIONTYPE_VECTOR3;
  36580. },
  36581. enumerable: true,
  36582. configurable: true
  36583. });
  36584. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  36585. get: function () {
  36586. return Animation._ANIMATIONTYPE_VECTOR2;
  36587. },
  36588. enumerable: true,
  36589. configurable: true
  36590. });
  36591. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  36592. get: function () {
  36593. return Animation._ANIMATIONTYPE_SIZE;
  36594. },
  36595. enumerable: true,
  36596. configurable: true
  36597. });
  36598. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  36599. get: function () {
  36600. return Animation._ANIMATIONTYPE_QUATERNION;
  36601. },
  36602. enumerable: true,
  36603. configurable: true
  36604. });
  36605. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  36606. get: function () {
  36607. return Animation._ANIMATIONTYPE_MATRIX;
  36608. },
  36609. enumerable: true,
  36610. configurable: true
  36611. });
  36612. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  36613. get: function () {
  36614. return Animation._ANIMATIONTYPE_COLOR3;
  36615. },
  36616. enumerable: true,
  36617. configurable: true
  36618. });
  36619. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  36620. get: function () {
  36621. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  36622. },
  36623. enumerable: true,
  36624. configurable: true
  36625. });
  36626. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  36627. get: function () {
  36628. return Animation._ANIMATIONLOOPMODE_CYCLE;
  36629. },
  36630. enumerable: true,
  36631. configurable: true
  36632. });
  36633. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  36634. get: function () {
  36635. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  36636. },
  36637. enumerable: true,
  36638. configurable: true
  36639. });
  36640. Animation.Parse = function (parsedAnimation) {
  36641. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  36642. var dataType = parsedAnimation.dataType;
  36643. var keys = [];
  36644. var data;
  36645. var index;
  36646. if (parsedAnimation.enableBlending) {
  36647. animation.enableBlending = parsedAnimation.enableBlending;
  36648. }
  36649. if (parsedAnimation.blendingSpeed) {
  36650. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  36651. }
  36652. for (index = 0; index < parsedAnimation.keys.length; index++) {
  36653. var key = parsedAnimation.keys[index];
  36654. switch (dataType) {
  36655. case Animation.ANIMATIONTYPE_FLOAT:
  36656. data = key.values[0];
  36657. break;
  36658. case Animation.ANIMATIONTYPE_QUATERNION:
  36659. data = BABYLON.Quaternion.FromArray(key.values);
  36660. break;
  36661. case Animation.ANIMATIONTYPE_MATRIX:
  36662. data = BABYLON.Matrix.FromArray(key.values);
  36663. break;
  36664. case Animation.ANIMATIONTYPE_COLOR3:
  36665. data = BABYLON.Color3.FromArray(key.values);
  36666. break;
  36667. case Animation.ANIMATIONTYPE_VECTOR3:
  36668. default:
  36669. data = BABYLON.Vector3.FromArray(key.values);
  36670. break;
  36671. }
  36672. keys.push({
  36673. frame: key.frame,
  36674. value: data
  36675. });
  36676. }
  36677. animation.setKeys(keys);
  36678. if (parsedAnimation.ranges) {
  36679. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  36680. data = parsedAnimation.ranges[index];
  36681. animation.createRange(data.name, data.from, data.to);
  36682. }
  36683. }
  36684. return animation;
  36685. };
  36686. Animation.AppendSerializedAnimations = function (source, destination) {
  36687. if (source.animations) {
  36688. destination.animations = [];
  36689. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  36690. var animation = source.animations[animationIndex];
  36691. destination.animations.push(animation.serialize());
  36692. }
  36693. }
  36694. };
  36695. // Statics
  36696. Animation._ANIMATIONTYPE_FLOAT = 0;
  36697. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  36698. Animation._ANIMATIONTYPE_QUATERNION = 2;
  36699. Animation._ANIMATIONTYPE_MATRIX = 3;
  36700. Animation._ANIMATIONTYPE_COLOR3 = 4;
  36701. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  36702. Animation._ANIMATIONTYPE_SIZE = 6;
  36703. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  36704. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  36705. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  36706. return Animation;
  36707. }());
  36708. BABYLON.Animation = Animation;
  36709. })(BABYLON || (BABYLON = {}));
  36710. //# sourceMappingURL=babylon.animation.js.map
  36711. var BABYLON;
  36712. (function (BABYLON) {
  36713. var Animatable = (function () {
  36714. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  36715. if (fromFrame === void 0) { fromFrame = 0; }
  36716. if (toFrame === void 0) { toFrame = 100; }
  36717. if (loopAnimation === void 0) { loopAnimation = false; }
  36718. if (speedRatio === void 0) { speedRatio = 1.0; }
  36719. this.target = target;
  36720. this.fromFrame = fromFrame;
  36721. this.toFrame = toFrame;
  36722. this.loopAnimation = loopAnimation;
  36723. this.speedRatio = speedRatio;
  36724. this.onAnimationEnd = onAnimationEnd;
  36725. this._localDelayOffset = null;
  36726. this._pausedDelay = null;
  36727. this._animations = new Array();
  36728. this._paused = false;
  36729. this.animationStarted = false;
  36730. if (animations) {
  36731. this.appendAnimations(target, animations);
  36732. }
  36733. this._scene = scene;
  36734. scene._activeAnimatables.push(this);
  36735. }
  36736. // Methods
  36737. Animatable.prototype.getAnimations = function () {
  36738. return this._animations;
  36739. };
  36740. Animatable.prototype.appendAnimations = function (target, animations) {
  36741. for (var index = 0; index < animations.length; index++) {
  36742. var animation = animations[index];
  36743. animation._target = target;
  36744. this._animations.push(animation);
  36745. }
  36746. };
  36747. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  36748. var animations = this._animations;
  36749. for (var index = 0; index < animations.length; index++) {
  36750. if (animations[index].targetProperty === property) {
  36751. return animations[index];
  36752. }
  36753. }
  36754. return null;
  36755. };
  36756. Animatable.prototype.reset = function () {
  36757. var animations = this._animations;
  36758. for (var index = 0; index < animations.length; index++) {
  36759. animations[index].reset();
  36760. }
  36761. this._localDelayOffset = null;
  36762. this._pausedDelay = null;
  36763. };
  36764. Animatable.prototype.enableBlending = function (blendingSpeed) {
  36765. var animations = this._animations;
  36766. for (var index = 0; index < animations.length; index++) {
  36767. animations[index].enableBlending = true;
  36768. animations[index].blendingSpeed = blendingSpeed;
  36769. }
  36770. };
  36771. Animatable.prototype.disableBlending = function () {
  36772. var animations = this._animations;
  36773. for (var index = 0; index < animations.length; index++) {
  36774. animations[index].enableBlending = false;
  36775. }
  36776. };
  36777. Animatable.prototype.goToFrame = function (frame) {
  36778. var animations = this._animations;
  36779. if (animations[0]) {
  36780. var fps = animations[0].framePerSecond;
  36781. var currentFrame = animations[0].currentFrame;
  36782. var adjustTime = frame - currentFrame;
  36783. var delay = adjustTime * 1000 / fps;
  36784. this._localDelayOffset -= delay;
  36785. }
  36786. for (var index = 0; index < animations.length; index++) {
  36787. animations[index].goToFrame(frame);
  36788. }
  36789. };
  36790. Animatable.prototype.pause = function () {
  36791. if (this._paused) {
  36792. return;
  36793. }
  36794. this._paused = true;
  36795. };
  36796. Animatable.prototype.restart = function () {
  36797. this._paused = false;
  36798. };
  36799. Animatable.prototype.stop = function (animationName) {
  36800. if (animationName) {
  36801. var idx = this._scene._activeAnimatables.indexOf(this);
  36802. if (idx > -1) {
  36803. var animations = this._animations;
  36804. for (var index = animations.length - 1; index >= 0; index--) {
  36805. if (typeof animationName === "string" && animations[index].name != animationName) {
  36806. continue;
  36807. }
  36808. animations[index].reset();
  36809. animations.splice(index, 1);
  36810. }
  36811. if (animations.length == 0) {
  36812. this._scene._activeAnimatables.splice(idx, 1);
  36813. if (this.onAnimationEnd) {
  36814. this.onAnimationEnd();
  36815. }
  36816. }
  36817. }
  36818. }
  36819. else {
  36820. var index = this._scene._activeAnimatables.indexOf(this);
  36821. if (index > -1) {
  36822. this._scene._activeAnimatables.splice(index, 1);
  36823. var animations = this._animations;
  36824. for (var index = 0; index < animations.length; index++) {
  36825. animations[index].reset();
  36826. }
  36827. if (this.onAnimationEnd) {
  36828. this.onAnimationEnd();
  36829. }
  36830. }
  36831. }
  36832. };
  36833. Animatable.prototype._animate = function (delay) {
  36834. if (this._paused) {
  36835. this.animationStarted = false;
  36836. if (this._pausedDelay === null) {
  36837. this._pausedDelay = delay;
  36838. }
  36839. return true;
  36840. }
  36841. if (this._localDelayOffset === null) {
  36842. this._localDelayOffset = delay;
  36843. }
  36844. else if (this._pausedDelay !== null) {
  36845. this._localDelayOffset += delay - this._pausedDelay;
  36846. this._pausedDelay = null;
  36847. }
  36848. // Animating
  36849. var running = false;
  36850. var animations = this._animations;
  36851. var index;
  36852. for (index = 0; index < animations.length; index++) {
  36853. var animation = animations[index];
  36854. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  36855. running = running || isRunning;
  36856. }
  36857. this.animationStarted = running;
  36858. if (!running) {
  36859. // Remove from active animatables
  36860. index = this._scene._activeAnimatables.indexOf(this);
  36861. this._scene._activeAnimatables.splice(index, 1);
  36862. }
  36863. if (!running && this.onAnimationEnd) {
  36864. this.onAnimationEnd();
  36865. this.onAnimationEnd = null;
  36866. }
  36867. return running;
  36868. };
  36869. return Animatable;
  36870. }());
  36871. BABYLON.Animatable = Animatable;
  36872. })(BABYLON || (BABYLON = {}));
  36873. //# sourceMappingURL=babylon.animatable.js.map
  36874. var BABYLON;
  36875. (function (BABYLON) {
  36876. var EasingFunction = (function () {
  36877. function EasingFunction() {
  36878. // Properties
  36879. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  36880. }
  36881. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  36882. get: function () {
  36883. return EasingFunction._EASINGMODE_EASEIN;
  36884. },
  36885. enumerable: true,
  36886. configurable: true
  36887. });
  36888. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  36889. get: function () {
  36890. return EasingFunction._EASINGMODE_EASEOUT;
  36891. },
  36892. enumerable: true,
  36893. configurable: true
  36894. });
  36895. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  36896. get: function () {
  36897. return EasingFunction._EASINGMODE_EASEINOUT;
  36898. },
  36899. enumerable: true,
  36900. configurable: true
  36901. });
  36902. EasingFunction.prototype.setEasingMode = function (easingMode) {
  36903. var n = Math.min(Math.max(easingMode, 0), 2);
  36904. this._easingMode = n;
  36905. };
  36906. EasingFunction.prototype.getEasingMode = function () {
  36907. return this._easingMode;
  36908. };
  36909. EasingFunction.prototype.easeInCore = function (gradient) {
  36910. throw new Error('You must implement this method');
  36911. };
  36912. EasingFunction.prototype.ease = function (gradient) {
  36913. switch (this._easingMode) {
  36914. case EasingFunction.EASINGMODE_EASEIN:
  36915. return this.easeInCore(gradient);
  36916. case EasingFunction.EASINGMODE_EASEOUT:
  36917. return (1 - this.easeInCore(1 - gradient));
  36918. }
  36919. if (gradient >= 0.5) {
  36920. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  36921. }
  36922. return (this.easeInCore(gradient * 2) * 0.5);
  36923. };
  36924. //Statics
  36925. EasingFunction._EASINGMODE_EASEIN = 0;
  36926. EasingFunction._EASINGMODE_EASEOUT = 1;
  36927. EasingFunction._EASINGMODE_EASEINOUT = 2;
  36928. return EasingFunction;
  36929. }());
  36930. BABYLON.EasingFunction = EasingFunction;
  36931. var CircleEase = (function (_super) {
  36932. __extends(CircleEase, _super);
  36933. function CircleEase() {
  36934. return _super !== null && _super.apply(this, arguments) || this;
  36935. }
  36936. CircleEase.prototype.easeInCore = function (gradient) {
  36937. gradient = Math.max(0, Math.min(1, gradient));
  36938. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  36939. };
  36940. return CircleEase;
  36941. }(EasingFunction));
  36942. BABYLON.CircleEase = CircleEase;
  36943. var BackEase = (function (_super) {
  36944. __extends(BackEase, _super);
  36945. function BackEase(amplitude) {
  36946. if (amplitude === void 0) { amplitude = 1; }
  36947. var _this = _super.call(this) || this;
  36948. _this.amplitude = amplitude;
  36949. return _this;
  36950. }
  36951. BackEase.prototype.easeInCore = function (gradient) {
  36952. var num = Math.max(0, this.amplitude);
  36953. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  36954. };
  36955. return BackEase;
  36956. }(EasingFunction));
  36957. BABYLON.BackEase = BackEase;
  36958. var BounceEase = (function (_super) {
  36959. __extends(BounceEase, _super);
  36960. function BounceEase(bounces, bounciness) {
  36961. if (bounces === void 0) { bounces = 3; }
  36962. if (bounciness === void 0) { bounciness = 2; }
  36963. var _this = _super.call(this) || this;
  36964. _this.bounces = bounces;
  36965. _this.bounciness = bounciness;
  36966. return _this;
  36967. }
  36968. BounceEase.prototype.easeInCore = function (gradient) {
  36969. var y = Math.max(0.0, this.bounces);
  36970. var bounciness = this.bounciness;
  36971. if (bounciness <= 1.0) {
  36972. bounciness = 1.001;
  36973. }
  36974. var num9 = Math.pow(bounciness, y);
  36975. var num5 = 1.0 - bounciness;
  36976. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  36977. var num15 = gradient * num4;
  36978. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  36979. var num3 = Math.floor(num65);
  36980. var num13 = num3 + 1.0;
  36981. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  36982. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  36983. var num7 = (num8 + num12) * 0.5;
  36984. var num6 = gradient - num7;
  36985. var num2 = num7 - num8;
  36986. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  36987. };
  36988. return BounceEase;
  36989. }(EasingFunction));
  36990. BABYLON.BounceEase = BounceEase;
  36991. var CubicEase = (function (_super) {
  36992. __extends(CubicEase, _super);
  36993. function CubicEase() {
  36994. return _super !== null && _super.apply(this, arguments) || this;
  36995. }
  36996. CubicEase.prototype.easeInCore = function (gradient) {
  36997. return (gradient * gradient * gradient);
  36998. };
  36999. return CubicEase;
  37000. }(EasingFunction));
  37001. BABYLON.CubicEase = CubicEase;
  37002. var ElasticEase = (function (_super) {
  37003. __extends(ElasticEase, _super);
  37004. function ElasticEase(oscillations, springiness) {
  37005. if (oscillations === void 0) { oscillations = 3; }
  37006. if (springiness === void 0) { springiness = 3; }
  37007. var _this = _super.call(this) || this;
  37008. _this.oscillations = oscillations;
  37009. _this.springiness = springiness;
  37010. return _this;
  37011. }
  37012. ElasticEase.prototype.easeInCore = function (gradient) {
  37013. var num2;
  37014. var num3 = Math.max(0.0, this.oscillations);
  37015. var num = Math.max(0.0, this.springiness);
  37016. if (num == 0) {
  37017. num2 = gradient;
  37018. }
  37019. else {
  37020. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  37021. }
  37022. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  37023. };
  37024. return ElasticEase;
  37025. }(EasingFunction));
  37026. BABYLON.ElasticEase = ElasticEase;
  37027. var ExponentialEase = (function (_super) {
  37028. __extends(ExponentialEase, _super);
  37029. function ExponentialEase(exponent) {
  37030. if (exponent === void 0) { exponent = 2; }
  37031. var _this = _super.call(this) || this;
  37032. _this.exponent = exponent;
  37033. return _this;
  37034. }
  37035. ExponentialEase.prototype.easeInCore = function (gradient) {
  37036. if (this.exponent <= 0) {
  37037. return gradient;
  37038. }
  37039. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  37040. };
  37041. return ExponentialEase;
  37042. }(EasingFunction));
  37043. BABYLON.ExponentialEase = ExponentialEase;
  37044. var PowerEase = (function (_super) {
  37045. __extends(PowerEase, _super);
  37046. function PowerEase(power) {
  37047. if (power === void 0) { power = 2; }
  37048. var _this = _super.call(this) || this;
  37049. _this.power = power;
  37050. return _this;
  37051. }
  37052. PowerEase.prototype.easeInCore = function (gradient) {
  37053. var y = Math.max(0.0, this.power);
  37054. return Math.pow(gradient, y);
  37055. };
  37056. return PowerEase;
  37057. }(EasingFunction));
  37058. BABYLON.PowerEase = PowerEase;
  37059. var QuadraticEase = (function (_super) {
  37060. __extends(QuadraticEase, _super);
  37061. function QuadraticEase() {
  37062. return _super !== null && _super.apply(this, arguments) || this;
  37063. }
  37064. QuadraticEase.prototype.easeInCore = function (gradient) {
  37065. return (gradient * gradient);
  37066. };
  37067. return QuadraticEase;
  37068. }(EasingFunction));
  37069. BABYLON.QuadraticEase = QuadraticEase;
  37070. var QuarticEase = (function (_super) {
  37071. __extends(QuarticEase, _super);
  37072. function QuarticEase() {
  37073. return _super !== null && _super.apply(this, arguments) || this;
  37074. }
  37075. QuarticEase.prototype.easeInCore = function (gradient) {
  37076. return (gradient * gradient * gradient * gradient);
  37077. };
  37078. return QuarticEase;
  37079. }(EasingFunction));
  37080. BABYLON.QuarticEase = QuarticEase;
  37081. var QuinticEase = (function (_super) {
  37082. __extends(QuinticEase, _super);
  37083. function QuinticEase() {
  37084. return _super !== null && _super.apply(this, arguments) || this;
  37085. }
  37086. QuinticEase.prototype.easeInCore = function (gradient) {
  37087. return (gradient * gradient * gradient * gradient * gradient);
  37088. };
  37089. return QuinticEase;
  37090. }(EasingFunction));
  37091. BABYLON.QuinticEase = QuinticEase;
  37092. var SineEase = (function (_super) {
  37093. __extends(SineEase, _super);
  37094. function SineEase() {
  37095. return _super !== null && _super.apply(this, arguments) || this;
  37096. }
  37097. SineEase.prototype.easeInCore = function (gradient) {
  37098. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  37099. };
  37100. return SineEase;
  37101. }(EasingFunction));
  37102. BABYLON.SineEase = SineEase;
  37103. var BezierCurveEase = (function (_super) {
  37104. __extends(BezierCurveEase, _super);
  37105. function BezierCurveEase(x1, y1, x2, y2) {
  37106. if (x1 === void 0) { x1 = 0; }
  37107. if (y1 === void 0) { y1 = 0; }
  37108. if (x2 === void 0) { x2 = 1; }
  37109. if (y2 === void 0) { y2 = 1; }
  37110. var _this = _super.call(this) || this;
  37111. _this.x1 = x1;
  37112. _this.y1 = y1;
  37113. _this.x2 = x2;
  37114. _this.y2 = y2;
  37115. return _this;
  37116. }
  37117. BezierCurveEase.prototype.easeInCore = function (gradient) {
  37118. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  37119. };
  37120. return BezierCurveEase;
  37121. }(EasingFunction));
  37122. BABYLON.BezierCurveEase = BezierCurveEase;
  37123. })(BABYLON || (BABYLON = {}));
  37124. //# sourceMappingURL=babylon.easing.js.map
  37125. var BABYLON;
  37126. (function (BABYLON) {
  37127. var Condition = (function () {
  37128. function Condition(actionManager) {
  37129. this._actionManager = actionManager;
  37130. }
  37131. Condition.prototype.isValid = function () {
  37132. return true;
  37133. };
  37134. Condition.prototype._getProperty = function (propertyPath) {
  37135. return this._actionManager._getProperty(propertyPath);
  37136. };
  37137. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  37138. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37139. };
  37140. Condition.prototype.serialize = function () {
  37141. };
  37142. Condition.prototype._serialize = function (serializedCondition) {
  37143. return {
  37144. type: 2,
  37145. children: [],
  37146. name: serializedCondition.name,
  37147. properties: serializedCondition.properties
  37148. };
  37149. };
  37150. return Condition;
  37151. }());
  37152. BABYLON.Condition = Condition;
  37153. var ValueCondition = (function (_super) {
  37154. __extends(ValueCondition, _super);
  37155. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  37156. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  37157. var _this = _super.call(this, actionManager) || this;
  37158. _this.propertyPath = propertyPath;
  37159. _this.value = value;
  37160. _this.operator = operator;
  37161. _this._target = target;
  37162. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  37163. _this._property = _this._getProperty(_this.propertyPath);
  37164. return _this;
  37165. }
  37166. Object.defineProperty(ValueCondition, "IsEqual", {
  37167. get: function () {
  37168. return ValueCondition._IsEqual;
  37169. },
  37170. enumerable: true,
  37171. configurable: true
  37172. });
  37173. Object.defineProperty(ValueCondition, "IsDifferent", {
  37174. get: function () {
  37175. return ValueCondition._IsDifferent;
  37176. },
  37177. enumerable: true,
  37178. configurable: true
  37179. });
  37180. Object.defineProperty(ValueCondition, "IsGreater", {
  37181. get: function () {
  37182. return ValueCondition._IsGreater;
  37183. },
  37184. enumerable: true,
  37185. configurable: true
  37186. });
  37187. Object.defineProperty(ValueCondition, "IsLesser", {
  37188. get: function () {
  37189. return ValueCondition._IsLesser;
  37190. },
  37191. enumerable: true,
  37192. configurable: true
  37193. });
  37194. // Methods
  37195. ValueCondition.prototype.isValid = function () {
  37196. switch (this.operator) {
  37197. case ValueCondition.IsGreater:
  37198. return this._effectiveTarget[this._property] > this.value;
  37199. case ValueCondition.IsLesser:
  37200. return this._effectiveTarget[this._property] < this.value;
  37201. case ValueCondition.IsEqual:
  37202. case ValueCondition.IsDifferent:
  37203. var check;
  37204. if (this.value.equals) {
  37205. check = this.value.equals(this._effectiveTarget[this._property]);
  37206. }
  37207. else {
  37208. check = this.value === this._effectiveTarget[this._property];
  37209. }
  37210. return this.operator === ValueCondition.IsEqual ? check : !check;
  37211. }
  37212. return false;
  37213. };
  37214. ValueCondition.prototype.serialize = function () {
  37215. return this._serialize({
  37216. name: "ValueCondition",
  37217. properties: [
  37218. BABYLON.Action._GetTargetProperty(this._target),
  37219. { name: "propertyPath", value: this.propertyPath },
  37220. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37221. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  37222. ]
  37223. });
  37224. };
  37225. ValueCondition.GetOperatorName = function (operator) {
  37226. switch (operator) {
  37227. case ValueCondition._IsEqual: return "IsEqual";
  37228. case ValueCondition._IsDifferent: return "IsDifferent";
  37229. case ValueCondition._IsGreater: return "IsGreater";
  37230. case ValueCondition._IsLesser: return "IsLesser";
  37231. default: return "";
  37232. }
  37233. };
  37234. // Statics
  37235. ValueCondition._IsEqual = 0;
  37236. ValueCondition._IsDifferent = 1;
  37237. ValueCondition._IsGreater = 2;
  37238. ValueCondition._IsLesser = 3;
  37239. return ValueCondition;
  37240. }(Condition));
  37241. BABYLON.ValueCondition = ValueCondition;
  37242. var PredicateCondition = (function (_super) {
  37243. __extends(PredicateCondition, _super);
  37244. function PredicateCondition(actionManager, predicate) {
  37245. var _this = _super.call(this, actionManager) || this;
  37246. _this.predicate = predicate;
  37247. return _this;
  37248. }
  37249. PredicateCondition.prototype.isValid = function () {
  37250. return this.predicate();
  37251. };
  37252. return PredicateCondition;
  37253. }(Condition));
  37254. BABYLON.PredicateCondition = PredicateCondition;
  37255. var StateCondition = (function (_super) {
  37256. __extends(StateCondition, _super);
  37257. function StateCondition(actionManager, target, value) {
  37258. var _this = _super.call(this, actionManager) || this;
  37259. _this.value = value;
  37260. _this._target = target;
  37261. return _this;
  37262. }
  37263. // Methods
  37264. StateCondition.prototype.isValid = function () {
  37265. return this._target.state === this.value;
  37266. };
  37267. StateCondition.prototype.serialize = function () {
  37268. return this._serialize({
  37269. name: "StateCondition",
  37270. properties: [
  37271. BABYLON.Action._GetTargetProperty(this._target),
  37272. { name: "value", value: this.value }
  37273. ]
  37274. });
  37275. };
  37276. return StateCondition;
  37277. }(Condition));
  37278. BABYLON.StateCondition = StateCondition;
  37279. })(BABYLON || (BABYLON = {}));
  37280. //# sourceMappingURL=babylon.condition.js.map
  37281. var BABYLON;
  37282. (function (BABYLON) {
  37283. var Action = (function () {
  37284. function Action(triggerOptions, condition) {
  37285. this.triggerOptions = triggerOptions;
  37286. if (triggerOptions.parameter) {
  37287. this.trigger = triggerOptions.trigger;
  37288. this._triggerParameter = triggerOptions.parameter;
  37289. }
  37290. else {
  37291. this.trigger = triggerOptions;
  37292. }
  37293. this._nextActiveAction = this;
  37294. this._condition = condition;
  37295. }
  37296. // Methods
  37297. Action.prototype._prepare = function () {
  37298. };
  37299. Action.prototype.getTriggerParameter = function () {
  37300. return this._triggerParameter;
  37301. };
  37302. Action.prototype._executeCurrent = function (evt) {
  37303. if (this._nextActiveAction._condition) {
  37304. var condition = this._nextActiveAction._condition;
  37305. var currentRenderId = this._actionManager.getScene().getRenderId();
  37306. // We cache the current evaluation for the current frame
  37307. if (condition._evaluationId === currentRenderId) {
  37308. if (!condition._currentResult) {
  37309. return;
  37310. }
  37311. }
  37312. else {
  37313. condition._evaluationId = currentRenderId;
  37314. if (!condition.isValid()) {
  37315. condition._currentResult = false;
  37316. return;
  37317. }
  37318. condition._currentResult = true;
  37319. }
  37320. }
  37321. this._nextActiveAction.execute(evt);
  37322. this.skipToNextActiveAction();
  37323. };
  37324. Action.prototype.execute = function (evt) {
  37325. };
  37326. Action.prototype.skipToNextActiveAction = function () {
  37327. if (this._nextActiveAction._child) {
  37328. if (!this._nextActiveAction._child._actionManager) {
  37329. this._nextActiveAction._child._actionManager = this._actionManager;
  37330. }
  37331. this._nextActiveAction = this._nextActiveAction._child;
  37332. }
  37333. else {
  37334. this._nextActiveAction = this;
  37335. }
  37336. };
  37337. Action.prototype.then = function (action) {
  37338. this._child = action;
  37339. action._actionManager = this._actionManager;
  37340. action._prepare();
  37341. return action;
  37342. };
  37343. Action.prototype._getProperty = function (propertyPath) {
  37344. return this._actionManager._getProperty(propertyPath);
  37345. };
  37346. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  37347. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37348. };
  37349. Action.prototype.serialize = function (parent) {
  37350. };
  37351. // Called by BABYLON.Action objects in serialize(...). Internal use
  37352. Action.prototype._serialize = function (serializedAction, parent) {
  37353. var serializationObject = {
  37354. type: 1,
  37355. children: [],
  37356. name: serializedAction.name,
  37357. properties: serializedAction.properties || []
  37358. };
  37359. // Serialize child
  37360. if (this._child) {
  37361. this._child.serialize(serializationObject);
  37362. }
  37363. // Check if "this" has a condition
  37364. if (this._condition) {
  37365. var serializedCondition = this._condition.serialize();
  37366. serializedCondition.children.push(serializationObject);
  37367. if (parent) {
  37368. parent.children.push(serializedCondition);
  37369. }
  37370. return serializedCondition;
  37371. }
  37372. if (parent) {
  37373. parent.children.push(serializationObject);
  37374. }
  37375. return serializationObject;
  37376. };
  37377. Action._SerializeValueAsString = function (value) {
  37378. if (typeof value === "number") {
  37379. return value.toString();
  37380. }
  37381. if (typeof value === "boolean") {
  37382. return value ? "true" : "false";
  37383. }
  37384. if (value instanceof BABYLON.Vector2) {
  37385. return value.x + ", " + value.y;
  37386. }
  37387. if (value instanceof BABYLON.Vector3) {
  37388. return value.x + ", " + value.y + ", " + value.z;
  37389. }
  37390. if (value instanceof BABYLON.Color3) {
  37391. return value.r + ", " + value.g + ", " + value.b;
  37392. }
  37393. if (value instanceof BABYLON.Color4) {
  37394. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  37395. }
  37396. return value; // string
  37397. };
  37398. Action._GetTargetProperty = function (target) {
  37399. return {
  37400. name: "target",
  37401. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  37402. : target instanceof BABYLON.Light ? "LightProperties"
  37403. : target instanceof BABYLON.Camera ? "CameraProperties"
  37404. : "SceneProperties",
  37405. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  37406. };
  37407. };
  37408. return Action;
  37409. }());
  37410. BABYLON.Action = Action;
  37411. })(BABYLON || (BABYLON = {}));
  37412. //# sourceMappingURL=babylon.action.js.map
  37413. var BABYLON;
  37414. (function (BABYLON) {
  37415. /**
  37416. * ActionEvent is the event beint sent when an action is triggered.
  37417. */
  37418. var ActionEvent = (function () {
  37419. /**
  37420. * @param source The mesh or sprite that triggered the action.
  37421. * @param pointerX The X mouse cursor position at the time of the event
  37422. * @param pointerY The Y mouse cursor position at the time of the event
  37423. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  37424. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  37425. */
  37426. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  37427. this.source = source;
  37428. this.pointerX = pointerX;
  37429. this.pointerY = pointerY;
  37430. this.meshUnderPointer = meshUnderPointer;
  37431. this.sourceEvent = sourceEvent;
  37432. this.additionalData = additionalData;
  37433. }
  37434. /**
  37435. * Helper function to auto-create an ActionEvent from a source mesh.
  37436. * @param source The source mesh that triggered the event
  37437. * @param evt {Event} The original (browser) event
  37438. */
  37439. ActionEvent.CreateNew = function (source, evt, additionalData) {
  37440. var scene = source.getScene();
  37441. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37442. };
  37443. /**
  37444. * Helper function to auto-create an ActionEvent from a source mesh.
  37445. * @param source The source sprite that triggered the event
  37446. * @param scene Scene associated with the sprite
  37447. * @param evt {Event} The original (browser) event
  37448. */
  37449. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  37450. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37451. };
  37452. /**
  37453. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  37454. * @param scene the scene where the event occurred
  37455. * @param evt {Event} The original (browser) event
  37456. */
  37457. ActionEvent.CreateNewFromScene = function (scene, evt) {
  37458. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  37459. };
  37460. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  37461. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  37462. };
  37463. return ActionEvent;
  37464. }());
  37465. BABYLON.ActionEvent = ActionEvent;
  37466. /**
  37467. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  37468. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  37469. */
  37470. var ActionManager = (function () {
  37471. function ActionManager(scene) {
  37472. // Members
  37473. this.actions = new Array();
  37474. this.hoverCursor = '';
  37475. this._scene = scene;
  37476. scene._actionManagers.push(this);
  37477. }
  37478. Object.defineProperty(ActionManager, "NothingTrigger", {
  37479. get: function () {
  37480. return ActionManager._NothingTrigger;
  37481. },
  37482. enumerable: true,
  37483. configurable: true
  37484. });
  37485. Object.defineProperty(ActionManager, "OnPickTrigger", {
  37486. get: function () {
  37487. return ActionManager._OnPickTrigger;
  37488. },
  37489. enumerable: true,
  37490. configurable: true
  37491. });
  37492. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  37493. get: function () {
  37494. return ActionManager._OnLeftPickTrigger;
  37495. },
  37496. enumerable: true,
  37497. configurable: true
  37498. });
  37499. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  37500. get: function () {
  37501. return ActionManager._OnRightPickTrigger;
  37502. },
  37503. enumerable: true,
  37504. configurable: true
  37505. });
  37506. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  37507. get: function () {
  37508. return ActionManager._OnCenterPickTrigger;
  37509. },
  37510. enumerable: true,
  37511. configurable: true
  37512. });
  37513. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  37514. get: function () {
  37515. return ActionManager._OnPickDownTrigger;
  37516. },
  37517. enumerable: true,
  37518. configurable: true
  37519. });
  37520. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  37521. get: function () {
  37522. return ActionManager._OnDoublePickTrigger;
  37523. },
  37524. enumerable: true,
  37525. configurable: true
  37526. });
  37527. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  37528. get: function () {
  37529. return ActionManager._OnPickUpTrigger;
  37530. },
  37531. enumerable: true,
  37532. configurable: true
  37533. });
  37534. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  37535. /// This trigger will only be raised if you also declared a OnPickDown
  37536. get: function () {
  37537. return ActionManager._OnPickOutTrigger;
  37538. },
  37539. enumerable: true,
  37540. configurable: true
  37541. });
  37542. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  37543. get: function () {
  37544. return ActionManager._OnLongPressTrigger;
  37545. },
  37546. enumerable: true,
  37547. configurable: true
  37548. });
  37549. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  37550. get: function () {
  37551. return ActionManager._OnPointerOverTrigger;
  37552. },
  37553. enumerable: true,
  37554. configurable: true
  37555. });
  37556. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  37557. get: function () {
  37558. return ActionManager._OnPointerOutTrigger;
  37559. },
  37560. enumerable: true,
  37561. configurable: true
  37562. });
  37563. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  37564. get: function () {
  37565. return ActionManager._OnEveryFrameTrigger;
  37566. },
  37567. enumerable: true,
  37568. configurable: true
  37569. });
  37570. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  37571. get: function () {
  37572. return ActionManager._OnIntersectionEnterTrigger;
  37573. },
  37574. enumerable: true,
  37575. configurable: true
  37576. });
  37577. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  37578. get: function () {
  37579. return ActionManager._OnIntersectionExitTrigger;
  37580. },
  37581. enumerable: true,
  37582. configurable: true
  37583. });
  37584. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  37585. get: function () {
  37586. return ActionManager._OnKeyDownTrigger;
  37587. },
  37588. enumerable: true,
  37589. configurable: true
  37590. });
  37591. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  37592. get: function () {
  37593. return ActionManager._OnKeyUpTrigger;
  37594. },
  37595. enumerable: true,
  37596. configurable: true
  37597. });
  37598. // Methods
  37599. ActionManager.prototype.dispose = function () {
  37600. var index = this._scene._actionManagers.indexOf(this);
  37601. for (var i = 0; i < this.actions.length; i++) {
  37602. var action = this.actions[i];
  37603. ActionManager.Triggers[action.trigger]--;
  37604. if (ActionManager.Triggers[action.trigger] === 0) {
  37605. delete ActionManager.Triggers[action.trigger];
  37606. }
  37607. }
  37608. if (index > -1) {
  37609. this._scene._actionManagers.splice(index, 1);
  37610. }
  37611. };
  37612. ActionManager.prototype.getScene = function () {
  37613. return this._scene;
  37614. };
  37615. /**
  37616. * Does this action manager handles actions of any of the given triggers
  37617. * @param {number[]} triggers - the triggers to be tested
  37618. * @return {boolean} whether one (or more) of the triggers is handeled
  37619. */
  37620. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  37621. for (var index = 0; index < this.actions.length; index++) {
  37622. var action = this.actions[index];
  37623. if (triggers.indexOf(action.trigger) > -1) {
  37624. return true;
  37625. }
  37626. }
  37627. return false;
  37628. };
  37629. /**
  37630. * Does this action manager handles actions of a given trigger
  37631. * @param {number} trigger - the trigger to be tested
  37632. * @return {boolean} whether the trigger is handeled
  37633. */
  37634. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  37635. for (var index = 0; index < this.actions.length; index++) {
  37636. var action = this.actions[index];
  37637. if (action.trigger === trigger) {
  37638. return true;
  37639. }
  37640. }
  37641. return false;
  37642. };
  37643. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  37644. /**
  37645. * Does this action manager has pointer triggers
  37646. * @return {boolean} whether or not it has pointer triggers
  37647. */
  37648. get: function () {
  37649. for (var index = 0; index < this.actions.length; index++) {
  37650. var action = this.actions[index];
  37651. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  37652. return true;
  37653. }
  37654. }
  37655. return false;
  37656. },
  37657. enumerable: true,
  37658. configurable: true
  37659. });
  37660. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  37661. /**
  37662. * Does this action manager has pick triggers
  37663. * @return {boolean} whether or not it has pick triggers
  37664. */
  37665. get: function () {
  37666. for (var index = 0; index < this.actions.length; index++) {
  37667. var action = this.actions[index];
  37668. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  37669. return true;
  37670. }
  37671. }
  37672. return false;
  37673. },
  37674. enumerable: true,
  37675. configurable: true
  37676. });
  37677. Object.defineProperty(ActionManager, "HasTriggers", {
  37678. /**
  37679. * Does exist one action manager with at least one trigger
  37680. * @return {boolean} whether or not it exists one action manager with one trigger
  37681. **/
  37682. get: function () {
  37683. for (var t in ActionManager.Triggers) {
  37684. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37685. return true;
  37686. }
  37687. }
  37688. return false;
  37689. },
  37690. enumerable: true,
  37691. configurable: true
  37692. });
  37693. Object.defineProperty(ActionManager, "HasPickTriggers", {
  37694. /**
  37695. * Does exist one action manager with at least one pick trigger
  37696. * @return {boolean} whether or not it exists one action manager with one pick trigger
  37697. **/
  37698. get: function () {
  37699. for (var t in ActionManager.Triggers) {
  37700. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37701. var t_int = parseInt(t);
  37702. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  37703. return true;
  37704. }
  37705. }
  37706. }
  37707. return false;
  37708. },
  37709. enumerable: true,
  37710. configurable: true
  37711. });
  37712. /**
  37713. * Does exist one action manager that handles actions of a given trigger
  37714. * @param {number} trigger - the trigger to be tested
  37715. * @return {boolean} whether the trigger is handeled by at least one action manager
  37716. **/
  37717. ActionManager.HasSpecificTrigger = function (trigger) {
  37718. for (var t in ActionManager.Triggers) {
  37719. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37720. var t_int = parseInt(t);
  37721. if (t_int === trigger) {
  37722. return true;
  37723. }
  37724. }
  37725. }
  37726. return false;
  37727. };
  37728. /**
  37729. * Registers an action to this action manager
  37730. * @param {BABYLON.Action} action - the action to be registered
  37731. * @return {BABYLON.Action} the action amended (prepared) after registration
  37732. */
  37733. ActionManager.prototype.registerAction = function (action) {
  37734. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  37735. if (this.getScene().actionManager !== this) {
  37736. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  37737. return null;
  37738. }
  37739. }
  37740. this.actions.push(action);
  37741. if (ActionManager.Triggers[action.trigger]) {
  37742. ActionManager.Triggers[action.trigger]++;
  37743. }
  37744. else {
  37745. ActionManager.Triggers[action.trigger] = 1;
  37746. }
  37747. action._actionManager = this;
  37748. action._prepare();
  37749. return action;
  37750. };
  37751. /**
  37752. * Process a specific trigger
  37753. * @param {number} trigger - the trigger to process
  37754. * @param evt {BABYLON.ActionEvent} the event details to be processed
  37755. */
  37756. ActionManager.prototype.processTrigger = function (trigger, evt) {
  37757. for (var index = 0; index < this.actions.length; index++) {
  37758. var action = this.actions[index];
  37759. if (action.trigger === trigger) {
  37760. if (trigger === ActionManager.OnKeyUpTrigger
  37761. || trigger === ActionManager.OnKeyDownTrigger) {
  37762. var parameter = action.getTriggerParameter();
  37763. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  37764. if (!parameter.toLowerCase) {
  37765. continue;
  37766. }
  37767. var lowerCase = parameter.toLowerCase();
  37768. if (lowerCase !== evt.sourceEvent.key) {
  37769. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  37770. var actualkey = String.fromCharCode(unicode).toLowerCase();
  37771. if (actualkey !== lowerCase) {
  37772. continue;
  37773. }
  37774. }
  37775. }
  37776. }
  37777. action._executeCurrent(evt);
  37778. }
  37779. }
  37780. };
  37781. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  37782. var properties = propertyPath.split(".");
  37783. for (var index = 0; index < properties.length - 1; index++) {
  37784. target = target[properties[index]];
  37785. }
  37786. return target;
  37787. };
  37788. ActionManager.prototype._getProperty = function (propertyPath) {
  37789. var properties = propertyPath.split(".");
  37790. return properties[properties.length - 1];
  37791. };
  37792. ActionManager.prototype.serialize = function (name) {
  37793. var root = {
  37794. children: [],
  37795. name: name,
  37796. type: 3,
  37797. properties: [] // Empty for root but required
  37798. };
  37799. for (var i = 0; i < this.actions.length; i++) {
  37800. var triggerObject = {
  37801. type: 0,
  37802. children: [],
  37803. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  37804. properties: []
  37805. };
  37806. var triggerOptions = this.actions[i].triggerOptions;
  37807. if (triggerOptions && typeof triggerOptions !== "number") {
  37808. if (triggerOptions.parameter instanceof BABYLON.Node) {
  37809. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  37810. }
  37811. else {
  37812. var parameter = {};
  37813. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  37814. if (triggerOptions.parameter.mesh) {
  37815. parameter._meshId = triggerOptions.parameter.mesh.id;
  37816. }
  37817. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  37818. }
  37819. }
  37820. // Serialize child action, recursively
  37821. this.actions[i].serialize(triggerObject);
  37822. // Add serialized trigger
  37823. root.children.push(triggerObject);
  37824. }
  37825. return root;
  37826. };
  37827. ActionManager.Parse = function (parsedActions, object, scene) {
  37828. var actionManager = new BABYLON.ActionManager(scene);
  37829. if (object === null)
  37830. scene.actionManager = actionManager;
  37831. else
  37832. object.actionManager = actionManager;
  37833. // instanciate a new object
  37834. var instanciate = function (name, params) {
  37835. var newInstance = Object.create(BABYLON[name].prototype);
  37836. newInstance.constructor.apply(newInstance, params);
  37837. return newInstance;
  37838. };
  37839. var parseParameter = function (name, value, target, propertyPath) {
  37840. if (propertyPath === null) {
  37841. // String, boolean or float
  37842. var floatValue = parseFloat(value);
  37843. if (value === "true" || value === "false")
  37844. return value === "true";
  37845. else
  37846. return isNaN(floatValue) ? value : floatValue;
  37847. }
  37848. var effectiveTarget = propertyPath.split(".");
  37849. var values = value.split(",");
  37850. // Get effective Target
  37851. for (var i = 0; i < effectiveTarget.length; i++) {
  37852. target = target[effectiveTarget[i]];
  37853. }
  37854. // Return appropriate value with its type
  37855. if (typeof (target) === "boolean")
  37856. return values[0] === "true";
  37857. if (typeof (target) === "string")
  37858. return values[0];
  37859. // Parameters with multiple values such as Vector3 etc.
  37860. var split = new Array();
  37861. for (var i = 0; i < values.length; i++)
  37862. split.push(parseFloat(values[i]));
  37863. if (target instanceof BABYLON.Vector3)
  37864. return BABYLON.Vector3.FromArray(split);
  37865. if (target instanceof BABYLON.Vector4)
  37866. return BABYLON.Vector4.FromArray(split);
  37867. if (target instanceof BABYLON.Color3)
  37868. return BABYLON.Color3.FromArray(split);
  37869. if (target instanceof BABYLON.Color4)
  37870. return BABYLON.Color4.FromArray(split);
  37871. return parseFloat(values[0]);
  37872. };
  37873. // traverse graph per trigger
  37874. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  37875. if (combineArray === void 0) { combineArray = null; }
  37876. if (parsedAction.detached)
  37877. return;
  37878. var parameters = new Array();
  37879. var target = null;
  37880. var propertyPath = null;
  37881. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  37882. // Parameters
  37883. if (parsedAction.type === 2)
  37884. parameters.push(actionManager);
  37885. else
  37886. parameters.push(trigger);
  37887. if (combine) {
  37888. var actions = new Array();
  37889. for (var j = 0; j < parsedAction.combine.length; j++) {
  37890. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  37891. }
  37892. parameters.push(actions);
  37893. }
  37894. else {
  37895. for (var i = 0; i < parsedAction.properties.length; i++) {
  37896. var value = parsedAction.properties[i].value;
  37897. var name = parsedAction.properties[i].name;
  37898. var targetType = parsedAction.properties[i].targetType;
  37899. if (name === "target")
  37900. if (targetType !== null && targetType === "SceneProperties")
  37901. value = target = scene;
  37902. else
  37903. value = target = scene.getNodeByName(value);
  37904. else if (name === "parent")
  37905. value = scene.getNodeByName(value);
  37906. else if (name === "sound")
  37907. value = scene.getSoundByName(value);
  37908. else if (name !== "propertyPath") {
  37909. if (parsedAction.type === 2 && name === "operator")
  37910. value = BABYLON.ValueCondition[value];
  37911. else
  37912. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  37913. }
  37914. else {
  37915. propertyPath = value;
  37916. }
  37917. parameters.push(value);
  37918. }
  37919. }
  37920. if (combineArray === null) {
  37921. parameters.push(condition);
  37922. }
  37923. else {
  37924. parameters.push(null);
  37925. }
  37926. // If interpolate value action
  37927. if (parsedAction.name === "InterpolateValueAction") {
  37928. var param = parameters[parameters.length - 2];
  37929. parameters[parameters.length - 1] = param;
  37930. parameters[parameters.length - 2] = condition;
  37931. }
  37932. // Action or condition(s) and not CombineAction
  37933. var newAction = instanciate(parsedAction.name, parameters);
  37934. if (newAction instanceof BABYLON.Condition && condition !== null) {
  37935. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  37936. if (action)
  37937. action.then(nothing);
  37938. else
  37939. actionManager.registerAction(nothing);
  37940. action = nothing;
  37941. }
  37942. if (combineArray === null) {
  37943. if (newAction instanceof BABYLON.Condition) {
  37944. condition = newAction;
  37945. newAction = action;
  37946. }
  37947. else {
  37948. condition = null;
  37949. if (action)
  37950. action.then(newAction);
  37951. else
  37952. actionManager.registerAction(newAction);
  37953. }
  37954. }
  37955. else {
  37956. combineArray.push(newAction);
  37957. }
  37958. for (var i = 0; i < parsedAction.children.length; i++)
  37959. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  37960. };
  37961. // triggers
  37962. for (var i = 0; i < parsedActions.children.length; i++) {
  37963. var triggerParams;
  37964. var trigger = parsedActions.children[i];
  37965. if (trigger.properties.length > 0) {
  37966. var param = trigger.properties[0].value;
  37967. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  37968. if (value._meshId) {
  37969. value.mesh = scene.getMeshByID(value._meshId);
  37970. }
  37971. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  37972. }
  37973. else
  37974. triggerParams = BABYLON.ActionManager[trigger.name];
  37975. for (var j = 0; j < trigger.children.length; j++) {
  37976. if (!trigger.detached)
  37977. traverse(trigger.children[j], triggerParams, null, null);
  37978. }
  37979. }
  37980. };
  37981. ActionManager.GetTriggerName = function (trigger) {
  37982. switch (trigger) {
  37983. case 0: return "NothingTrigger";
  37984. case 1: return "OnPickTrigger";
  37985. case 2: return "OnLeftPickTrigger";
  37986. case 3: return "OnRightPickTrigger";
  37987. case 4: return "OnCenterPickTrigger";
  37988. case 5: return "OnPickDownTrigger";
  37989. case 6: return "OnPickUpTrigger";
  37990. case 7: return "OnLongPressTrigger";
  37991. case 8: return "OnPointerOverTrigger";
  37992. case 9: return "OnPointerOutTrigger";
  37993. case 10: return "OnEveryFrameTrigger";
  37994. case 11: return "OnIntersectionEnterTrigger";
  37995. case 12: return "OnIntersectionExitTrigger";
  37996. case 13: return "OnKeyDownTrigger";
  37997. case 14: return "OnKeyUpTrigger";
  37998. case 15: return "OnPickOutTrigger";
  37999. default: return "";
  38000. }
  38001. };
  38002. // Statics
  38003. ActionManager._NothingTrigger = 0;
  38004. ActionManager._OnPickTrigger = 1;
  38005. ActionManager._OnLeftPickTrigger = 2;
  38006. ActionManager._OnRightPickTrigger = 3;
  38007. ActionManager._OnCenterPickTrigger = 4;
  38008. ActionManager._OnPickDownTrigger = 5;
  38009. ActionManager._OnDoublePickTrigger = 6;
  38010. ActionManager._OnPickUpTrigger = 7;
  38011. ActionManager._OnLongPressTrigger = 8;
  38012. ActionManager._OnPointerOverTrigger = 9;
  38013. ActionManager._OnPointerOutTrigger = 10;
  38014. ActionManager._OnEveryFrameTrigger = 11;
  38015. ActionManager._OnIntersectionEnterTrigger = 12;
  38016. ActionManager._OnIntersectionExitTrigger = 13;
  38017. ActionManager._OnKeyDownTrigger = 14;
  38018. ActionManager._OnKeyUpTrigger = 15;
  38019. ActionManager._OnPickOutTrigger = 16;
  38020. ActionManager.Triggers = {};
  38021. return ActionManager;
  38022. }());
  38023. BABYLON.ActionManager = ActionManager;
  38024. })(BABYLON || (BABYLON = {}));
  38025. //# sourceMappingURL=babylon.actionManager.js.map
  38026. var BABYLON;
  38027. (function (BABYLON) {
  38028. var InterpolateValueAction = (function (_super) {
  38029. __extends(InterpolateValueAction, _super);
  38030. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  38031. if (duration === void 0) { duration = 1000; }
  38032. var _this = _super.call(this, triggerOptions, condition) || this;
  38033. _this.propertyPath = propertyPath;
  38034. _this.value = value;
  38035. _this.duration = duration;
  38036. _this.stopOtherAnimations = stopOtherAnimations;
  38037. _this.onInterpolationDone = onInterpolationDone;
  38038. _this._target = _this._effectiveTarget = target;
  38039. return _this;
  38040. }
  38041. InterpolateValueAction.prototype._prepare = function () {
  38042. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38043. this._property = this._getProperty(this.propertyPath);
  38044. };
  38045. InterpolateValueAction.prototype.execute = function () {
  38046. var scene = this._actionManager.getScene();
  38047. var keys = [
  38048. {
  38049. frame: 0,
  38050. value: this._effectiveTarget[this._property]
  38051. }, {
  38052. frame: 100,
  38053. value: this.value
  38054. }
  38055. ];
  38056. var dataType;
  38057. if (typeof this.value === "number") {
  38058. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  38059. }
  38060. else if (this.value instanceof BABYLON.Color3) {
  38061. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  38062. }
  38063. else if (this.value instanceof BABYLON.Vector3) {
  38064. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  38065. }
  38066. else if (this.value instanceof BABYLON.Matrix) {
  38067. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  38068. }
  38069. else if (this.value instanceof BABYLON.Quaternion) {
  38070. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  38071. }
  38072. else {
  38073. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  38074. return;
  38075. }
  38076. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38077. animation.setKeys(keys);
  38078. if (this.stopOtherAnimations) {
  38079. scene.stopAnimation(this._effectiveTarget);
  38080. }
  38081. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  38082. };
  38083. InterpolateValueAction.prototype.serialize = function (parent) {
  38084. return _super.prototype._serialize.call(this, {
  38085. name: "InterpolateValueAction",
  38086. properties: [
  38087. BABYLON.Action._GetTargetProperty(this._target),
  38088. { name: "propertyPath", value: this.propertyPath },
  38089. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38090. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  38091. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  38092. ]
  38093. }, parent);
  38094. };
  38095. return InterpolateValueAction;
  38096. }(BABYLON.Action));
  38097. BABYLON.InterpolateValueAction = InterpolateValueAction;
  38098. })(BABYLON || (BABYLON = {}));
  38099. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  38100. var BABYLON;
  38101. (function (BABYLON) {
  38102. var SwitchBooleanAction = (function (_super) {
  38103. __extends(SwitchBooleanAction, _super);
  38104. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  38105. var _this = _super.call(this, triggerOptions, condition) || this;
  38106. _this.propertyPath = propertyPath;
  38107. _this._target = _this._effectiveTarget = target;
  38108. return _this;
  38109. }
  38110. SwitchBooleanAction.prototype._prepare = function () {
  38111. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38112. this._property = this._getProperty(this.propertyPath);
  38113. };
  38114. SwitchBooleanAction.prototype.execute = function () {
  38115. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  38116. };
  38117. SwitchBooleanAction.prototype.serialize = function (parent) {
  38118. return _super.prototype._serialize.call(this, {
  38119. name: "SwitchBooleanAction",
  38120. properties: [
  38121. BABYLON.Action._GetTargetProperty(this._target),
  38122. { name: "propertyPath", value: this.propertyPath }
  38123. ]
  38124. }, parent);
  38125. };
  38126. return SwitchBooleanAction;
  38127. }(BABYLON.Action));
  38128. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  38129. var SetStateAction = (function (_super) {
  38130. __extends(SetStateAction, _super);
  38131. function SetStateAction(triggerOptions, target, value, condition) {
  38132. var _this = _super.call(this, triggerOptions, condition) || this;
  38133. _this.value = value;
  38134. _this._target = target;
  38135. return _this;
  38136. }
  38137. SetStateAction.prototype.execute = function () {
  38138. this._target.state = this.value;
  38139. };
  38140. SetStateAction.prototype.serialize = function (parent) {
  38141. return _super.prototype._serialize.call(this, {
  38142. name: "SetStateAction",
  38143. properties: [
  38144. BABYLON.Action._GetTargetProperty(this._target),
  38145. { name: "value", value: this.value }
  38146. ]
  38147. }, parent);
  38148. };
  38149. return SetStateAction;
  38150. }(BABYLON.Action));
  38151. BABYLON.SetStateAction = SetStateAction;
  38152. var SetValueAction = (function (_super) {
  38153. __extends(SetValueAction, _super);
  38154. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  38155. var _this = _super.call(this, triggerOptions, condition) || this;
  38156. _this.propertyPath = propertyPath;
  38157. _this.value = value;
  38158. _this._target = _this._effectiveTarget = target;
  38159. return _this;
  38160. }
  38161. SetValueAction.prototype._prepare = function () {
  38162. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38163. this._property = this._getProperty(this.propertyPath);
  38164. };
  38165. SetValueAction.prototype.execute = function () {
  38166. this._effectiveTarget[this._property] = this.value;
  38167. if (this._target.markAsDirty) {
  38168. this._target.markAsDirty(this._property);
  38169. }
  38170. };
  38171. SetValueAction.prototype.serialize = function (parent) {
  38172. return _super.prototype._serialize.call(this, {
  38173. name: "SetValueAction",
  38174. properties: [
  38175. BABYLON.Action._GetTargetProperty(this._target),
  38176. { name: "propertyPath", value: this.propertyPath },
  38177. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  38178. ]
  38179. }, parent);
  38180. };
  38181. return SetValueAction;
  38182. }(BABYLON.Action));
  38183. BABYLON.SetValueAction = SetValueAction;
  38184. var IncrementValueAction = (function (_super) {
  38185. __extends(IncrementValueAction, _super);
  38186. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  38187. var _this = _super.call(this, triggerOptions, condition) || this;
  38188. _this.propertyPath = propertyPath;
  38189. _this.value = value;
  38190. _this._target = _this._effectiveTarget = target;
  38191. return _this;
  38192. }
  38193. IncrementValueAction.prototype._prepare = function () {
  38194. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38195. this._property = this._getProperty(this.propertyPath);
  38196. if (typeof this._effectiveTarget[this._property] !== "number") {
  38197. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  38198. }
  38199. };
  38200. IncrementValueAction.prototype.execute = function () {
  38201. this._effectiveTarget[this._property] += this.value;
  38202. if (this._target.markAsDirty) {
  38203. this._target.markAsDirty(this._property);
  38204. }
  38205. };
  38206. IncrementValueAction.prototype.serialize = function (parent) {
  38207. return _super.prototype._serialize.call(this, {
  38208. name: "IncrementValueAction",
  38209. properties: [
  38210. BABYLON.Action._GetTargetProperty(this._target),
  38211. { name: "propertyPath", value: this.propertyPath },
  38212. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  38213. ]
  38214. }, parent);
  38215. };
  38216. return IncrementValueAction;
  38217. }(BABYLON.Action));
  38218. BABYLON.IncrementValueAction = IncrementValueAction;
  38219. var PlayAnimationAction = (function (_super) {
  38220. __extends(PlayAnimationAction, _super);
  38221. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  38222. var _this = _super.call(this, triggerOptions, condition) || this;
  38223. _this.from = from;
  38224. _this.to = to;
  38225. _this.loop = loop;
  38226. _this._target = target;
  38227. return _this;
  38228. }
  38229. PlayAnimationAction.prototype._prepare = function () {
  38230. };
  38231. PlayAnimationAction.prototype.execute = function () {
  38232. var scene = this._actionManager.getScene();
  38233. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  38234. };
  38235. PlayAnimationAction.prototype.serialize = function (parent) {
  38236. return _super.prototype._serialize.call(this, {
  38237. name: "PlayAnimationAction",
  38238. properties: [
  38239. BABYLON.Action._GetTargetProperty(this._target),
  38240. { name: "from", value: String(this.from) },
  38241. { name: "to", value: String(this.to) },
  38242. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  38243. ]
  38244. }, parent);
  38245. };
  38246. return PlayAnimationAction;
  38247. }(BABYLON.Action));
  38248. BABYLON.PlayAnimationAction = PlayAnimationAction;
  38249. var StopAnimationAction = (function (_super) {
  38250. __extends(StopAnimationAction, _super);
  38251. function StopAnimationAction(triggerOptions, target, condition) {
  38252. var _this = _super.call(this, triggerOptions, condition) || this;
  38253. _this._target = target;
  38254. return _this;
  38255. }
  38256. StopAnimationAction.prototype._prepare = function () {
  38257. };
  38258. StopAnimationAction.prototype.execute = function () {
  38259. var scene = this._actionManager.getScene();
  38260. scene.stopAnimation(this._target);
  38261. };
  38262. StopAnimationAction.prototype.serialize = function (parent) {
  38263. return _super.prototype._serialize.call(this, {
  38264. name: "StopAnimationAction",
  38265. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  38266. }, parent);
  38267. };
  38268. return StopAnimationAction;
  38269. }(BABYLON.Action));
  38270. BABYLON.StopAnimationAction = StopAnimationAction;
  38271. var DoNothingAction = (function (_super) {
  38272. __extends(DoNothingAction, _super);
  38273. function DoNothingAction(triggerOptions, condition) {
  38274. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  38275. return _super.call(this, triggerOptions, condition) || this;
  38276. }
  38277. DoNothingAction.prototype.execute = function () {
  38278. };
  38279. DoNothingAction.prototype.serialize = function (parent) {
  38280. return _super.prototype._serialize.call(this, {
  38281. name: "DoNothingAction",
  38282. properties: []
  38283. }, parent);
  38284. };
  38285. return DoNothingAction;
  38286. }(BABYLON.Action));
  38287. BABYLON.DoNothingAction = DoNothingAction;
  38288. var CombineAction = (function (_super) {
  38289. __extends(CombineAction, _super);
  38290. function CombineAction(triggerOptions, children, condition) {
  38291. var _this = _super.call(this, triggerOptions, condition) || this;
  38292. _this.children = children;
  38293. return _this;
  38294. }
  38295. CombineAction.prototype._prepare = function () {
  38296. for (var index = 0; index < this.children.length; index++) {
  38297. this.children[index]._actionManager = this._actionManager;
  38298. this.children[index]._prepare();
  38299. }
  38300. };
  38301. CombineAction.prototype.execute = function (evt) {
  38302. for (var index = 0; index < this.children.length; index++) {
  38303. this.children[index].execute(evt);
  38304. }
  38305. };
  38306. CombineAction.prototype.serialize = function (parent) {
  38307. var serializationObject = _super.prototype._serialize.call(this, {
  38308. name: "CombineAction",
  38309. properties: [],
  38310. combine: []
  38311. }, parent);
  38312. for (var i = 0; i < this.children.length; i++) {
  38313. serializationObject.combine.push(this.children[i].serialize(null));
  38314. }
  38315. return serializationObject;
  38316. };
  38317. return CombineAction;
  38318. }(BABYLON.Action));
  38319. BABYLON.CombineAction = CombineAction;
  38320. var ExecuteCodeAction = (function (_super) {
  38321. __extends(ExecuteCodeAction, _super);
  38322. function ExecuteCodeAction(triggerOptions, func, condition) {
  38323. var _this = _super.call(this, triggerOptions, condition) || this;
  38324. _this.func = func;
  38325. return _this;
  38326. }
  38327. ExecuteCodeAction.prototype.execute = function (evt) {
  38328. this.func(evt);
  38329. };
  38330. return ExecuteCodeAction;
  38331. }(BABYLON.Action));
  38332. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  38333. var SetParentAction = (function (_super) {
  38334. __extends(SetParentAction, _super);
  38335. function SetParentAction(triggerOptions, target, parent, condition) {
  38336. var _this = _super.call(this, triggerOptions, condition) || this;
  38337. _this._target = target;
  38338. _this._parent = parent;
  38339. return _this;
  38340. }
  38341. SetParentAction.prototype._prepare = function () {
  38342. };
  38343. SetParentAction.prototype.execute = function () {
  38344. if (this._target.parent === this._parent) {
  38345. return;
  38346. }
  38347. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  38348. invertParentWorldMatrix.invert();
  38349. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  38350. this._target.parent = this._parent;
  38351. };
  38352. SetParentAction.prototype.serialize = function (parent) {
  38353. return _super.prototype._serialize.call(this, {
  38354. name: "SetParentAction",
  38355. properties: [
  38356. BABYLON.Action._GetTargetProperty(this._target),
  38357. BABYLON.Action._GetTargetProperty(this._parent),
  38358. ]
  38359. }, parent);
  38360. };
  38361. return SetParentAction;
  38362. }(BABYLON.Action));
  38363. BABYLON.SetParentAction = SetParentAction;
  38364. var PlaySoundAction = (function (_super) {
  38365. __extends(PlaySoundAction, _super);
  38366. function PlaySoundAction(triggerOptions, sound, condition) {
  38367. var _this = _super.call(this, triggerOptions, condition) || this;
  38368. _this._sound = sound;
  38369. return _this;
  38370. }
  38371. PlaySoundAction.prototype._prepare = function () {
  38372. };
  38373. PlaySoundAction.prototype.execute = function () {
  38374. if (this._sound !== undefined)
  38375. this._sound.play();
  38376. };
  38377. PlaySoundAction.prototype.serialize = function (parent) {
  38378. return _super.prototype._serialize.call(this, {
  38379. name: "PlaySoundAction",
  38380. properties: [{ name: "sound", value: this._sound.name }]
  38381. }, parent);
  38382. };
  38383. return PlaySoundAction;
  38384. }(BABYLON.Action));
  38385. BABYLON.PlaySoundAction = PlaySoundAction;
  38386. var StopSoundAction = (function (_super) {
  38387. __extends(StopSoundAction, _super);
  38388. function StopSoundAction(triggerOptions, sound, condition) {
  38389. var _this = _super.call(this, triggerOptions, condition) || this;
  38390. _this._sound = sound;
  38391. return _this;
  38392. }
  38393. StopSoundAction.prototype._prepare = function () {
  38394. };
  38395. StopSoundAction.prototype.execute = function () {
  38396. if (this._sound !== undefined)
  38397. this._sound.stop();
  38398. };
  38399. StopSoundAction.prototype.serialize = function (parent) {
  38400. return _super.prototype._serialize.call(this, {
  38401. name: "StopSoundAction",
  38402. properties: [{ name: "sound", value: this._sound.name }]
  38403. }, parent);
  38404. };
  38405. return StopSoundAction;
  38406. }(BABYLON.Action));
  38407. BABYLON.StopSoundAction = StopSoundAction;
  38408. })(BABYLON || (BABYLON = {}));
  38409. //# sourceMappingURL=babylon.directActions.js.map
  38410. var BABYLON;
  38411. (function (BABYLON) {
  38412. var SpriteManager = (function () {
  38413. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  38414. if (epsilon === void 0) { epsilon = 0.01; }
  38415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38416. this.name = name;
  38417. this.sprites = new Array();
  38418. this.renderingGroupId = 0;
  38419. this.layerMask = 0x0FFFFFFF;
  38420. this.fogEnabled = true;
  38421. this.isPickable = false;
  38422. /**
  38423. * An event triggered when the manager is disposed.
  38424. * @type {BABYLON.Observable}
  38425. */
  38426. this.onDisposeObservable = new BABYLON.Observable();
  38427. this._vertexBuffers = {};
  38428. this._capacity = capacity;
  38429. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  38430. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38431. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38432. if (cellSize.width && cellSize.height) {
  38433. this.cellWidth = cellSize.width;
  38434. this.cellHeight = cellSize.height;
  38435. }
  38436. else if (cellSize !== undefined) {
  38437. this.cellWidth = cellSize;
  38438. this.cellHeight = cellSize;
  38439. }
  38440. else {
  38441. return;
  38442. }
  38443. this._epsilon = epsilon;
  38444. this._scene = scene;
  38445. this._scene.spriteManagers.push(this);
  38446. var indices = [];
  38447. var index = 0;
  38448. for (var count = 0; count < capacity; count++) {
  38449. indices.push(index);
  38450. indices.push(index + 1);
  38451. indices.push(index + 2);
  38452. indices.push(index);
  38453. indices.push(index + 2);
  38454. indices.push(index + 3);
  38455. index += 4;
  38456. }
  38457. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38458. // VBO
  38459. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  38460. this._vertexData = new Float32Array(capacity * 16 * 4);
  38461. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  38462. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  38463. var options = this._buffer.createVertexBuffer("options", 4, 4);
  38464. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  38465. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  38466. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  38467. this._vertexBuffers["options"] = options;
  38468. this._vertexBuffers["cellInfo"] = cellInfo;
  38469. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  38470. // Effects
  38471. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  38472. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  38473. }
  38474. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  38475. set: function (callback) {
  38476. if (this._onDisposeObserver) {
  38477. this.onDisposeObservable.remove(this._onDisposeObserver);
  38478. }
  38479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38480. },
  38481. enumerable: true,
  38482. configurable: true
  38483. });
  38484. Object.defineProperty(SpriteManager.prototype, "texture", {
  38485. get: function () {
  38486. return this._spriteTexture;
  38487. },
  38488. set: function (value) {
  38489. this._spriteTexture = value;
  38490. },
  38491. enumerable: true,
  38492. configurable: true
  38493. });
  38494. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  38495. var arrayOffset = index * 16;
  38496. if (offsetX === 0)
  38497. offsetX = this._epsilon;
  38498. else if (offsetX === 1)
  38499. offsetX = 1 - this._epsilon;
  38500. if (offsetY === 0)
  38501. offsetY = this._epsilon;
  38502. else if (offsetY === 1)
  38503. offsetY = 1 - this._epsilon;
  38504. this._vertexData[arrayOffset] = sprite.position.x;
  38505. this._vertexData[arrayOffset + 1] = sprite.position.y;
  38506. this._vertexData[arrayOffset + 2] = sprite.position.z;
  38507. this._vertexData[arrayOffset + 3] = sprite.angle;
  38508. this._vertexData[arrayOffset + 4] = sprite.width;
  38509. this._vertexData[arrayOffset + 5] = sprite.height;
  38510. this._vertexData[arrayOffset + 6] = offsetX;
  38511. this._vertexData[arrayOffset + 7] = offsetY;
  38512. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  38513. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  38514. var offset = (sprite.cellIndex / rowSize) >> 0;
  38515. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  38516. this._vertexData[arrayOffset + 11] = offset;
  38517. // Color
  38518. this._vertexData[arrayOffset + 12] = sprite.color.r;
  38519. this._vertexData[arrayOffset + 13] = sprite.color.g;
  38520. this._vertexData[arrayOffset + 14] = sprite.color.b;
  38521. this._vertexData[arrayOffset + 15] = sprite.color.a;
  38522. };
  38523. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  38524. var count = Math.min(this._capacity, this.sprites.length);
  38525. var min = BABYLON.Vector3.Zero();
  38526. var max = BABYLON.Vector3.Zero();
  38527. var distance = Number.MAX_VALUE;
  38528. var currentSprite;
  38529. var cameraSpacePosition = BABYLON.Vector3.Zero();
  38530. var cameraView = camera.getViewMatrix();
  38531. for (var index = 0; index < count; index++) {
  38532. var sprite = this.sprites[index];
  38533. if (!sprite) {
  38534. continue;
  38535. }
  38536. if (predicate) {
  38537. if (!predicate(sprite)) {
  38538. continue;
  38539. }
  38540. }
  38541. else if (!sprite.isPickable) {
  38542. continue;
  38543. }
  38544. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  38545. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  38546. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  38547. if (ray.intersectsBoxMinMax(min, max)) {
  38548. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  38549. if (distance > currentDistance) {
  38550. distance = currentDistance;
  38551. currentSprite = sprite;
  38552. if (fastCheck) {
  38553. break;
  38554. }
  38555. }
  38556. }
  38557. }
  38558. if (currentSprite) {
  38559. var result = new BABYLON.PickingInfo();
  38560. result.hit = true;
  38561. result.pickedSprite = currentSprite;
  38562. result.distance = distance;
  38563. return result;
  38564. }
  38565. return null;
  38566. };
  38567. SpriteManager.prototype.render = function () {
  38568. // Check
  38569. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  38570. return;
  38571. var engine = this._scene.getEngine();
  38572. var baseSize = this._spriteTexture.getBaseSize();
  38573. // Sprites
  38574. var deltaTime = engine.getDeltaTime();
  38575. var max = Math.min(this._capacity, this.sprites.length);
  38576. var rowSize = baseSize.width / this.cellWidth;
  38577. var offset = 0;
  38578. for (var index = 0; index < max; index++) {
  38579. var sprite = this.sprites[index];
  38580. if (!sprite) {
  38581. continue;
  38582. }
  38583. sprite._animate(deltaTime);
  38584. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  38585. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  38586. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  38587. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  38588. }
  38589. this._buffer.update(this._vertexData);
  38590. // Render
  38591. var effect = this._effectBase;
  38592. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38593. effect = this._effectFog;
  38594. }
  38595. engine.enableEffect(effect);
  38596. var viewMatrix = this._scene.getViewMatrix();
  38597. effect.setTexture("diffuseSampler", this._spriteTexture);
  38598. effect.setMatrix("view", viewMatrix);
  38599. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  38600. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  38601. // Fog
  38602. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38603. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  38604. effect.setColor3("vFogColor", this._scene.fogColor);
  38605. }
  38606. // VBOs
  38607. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38608. // Draw order
  38609. engine.setDepthFunctionToLessOrEqual();
  38610. effect.setBool("alphaTest", true);
  38611. engine.setColorWrite(false);
  38612. engine.draw(true, 0, max * 6);
  38613. engine.setColorWrite(true);
  38614. effect.setBool("alphaTest", false);
  38615. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38616. engine.draw(true, 0, max * 6);
  38617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38618. };
  38619. SpriteManager.prototype.dispose = function () {
  38620. if (this._buffer) {
  38621. this._buffer.dispose();
  38622. this._buffer = null;
  38623. }
  38624. if (this._indexBuffer) {
  38625. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38626. this._indexBuffer = null;
  38627. }
  38628. if (this._spriteTexture) {
  38629. this._spriteTexture.dispose();
  38630. this._spriteTexture = null;
  38631. }
  38632. // Remove from scene
  38633. var index = this._scene.spriteManagers.indexOf(this);
  38634. this._scene.spriteManagers.splice(index, 1);
  38635. // Callback
  38636. this.onDisposeObservable.notifyObservers(this);
  38637. this.onDisposeObservable.clear();
  38638. };
  38639. return SpriteManager;
  38640. }());
  38641. BABYLON.SpriteManager = SpriteManager;
  38642. })(BABYLON || (BABYLON = {}));
  38643. //# sourceMappingURL=babylon.spriteManager.js.map
  38644. var BABYLON;
  38645. (function (BABYLON) {
  38646. var Sprite = (function () {
  38647. function Sprite(name, manager) {
  38648. this.name = name;
  38649. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  38650. this.width = 1.0;
  38651. this.height = 1.0;
  38652. this.angle = 0;
  38653. this.cellIndex = 0;
  38654. this.invertU = 0;
  38655. this.invertV = 0;
  38656. this.animations = new Array();
  38657. this.isPickable = false;
  38658. this._animationStarted = false;
  38659. this._loopAnimation = false;
  38660. this._fromIndex = 0;
  38661. this._toIndex = 0;
  38662. this._delay = 0;
  38663. this._direction = 1;
  38664. this._frameCount = 0;
  38665. this._time = 0;
  38666. this._manager = manager;
  38667. this._manager.sprites.push(this);
  38668. this.position = BABYLON.Vector3.Zero();
  38669. }
  38670. Object.defineProperty(Sprite.prototype, "size", {
  38671. get: function () {
  38672. return this.width;
  38673. },
  38674. set: function (value) {
  38675. this.width = value;
  38676. this.height = value;
  38677. },
  38678. enumerable: true,
  38679. configurable: true
  38680. });
  38681. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  38682. this._fromIndex = from;
  38683. this._toIndex = to;
  38684. this._loopAnimation = loop;
  38685. this._delay = delay;
  38686. this._animationStarted = true;
  38687. this._direction = from < to ? 1 : -1;
  38688. this.cellIndex = from;
  38689. this._time = 0;
  38690. this._onAnimationEnd = onAnimationEnd;
  38691. };
  38692. Sprite.prototype.stopAnimation = function () {
  38693. this._animationStarted = false;
  38694. };
  38695. Sprite.prototype._animate = function (deltaTime) {
  38696. if (!this._animationStarted)
  38697. return;
  38698. this._time += deltaTime;
  38699. if (this._time > this._delay) {
  38700. this._time = this._time % this._delay;
  38701. this.cellIndex += this._direction;
  38702. if (this.cellIndex === this._toIndex) {
  38703. if (this._loopAnimation) {
  38704. this.cellIndex = this._fromIndex;
  38705. }
  38706. else {
  38707. this._animationStarted = false;
  38708. if (this._onAnimationEnd) {
  38709. this._onAnimationEnd();
  38710. }
  38711. if (this.disposeWhenFinishedAnimating) {
  38712. this.dispose();
  38713. }
  38714. }
  38715. }
  38716. }
  38717. };
  38718. Sprite.prototype.dispose = function () {
  38719. for (var i = 0; i < this._manager.sprites.length; i++) {
  38720. if (this._manager.sprites[i] == this) {
  38721. this._manager.sprites.splice(i, 1);
  38722. }
  38723. }
  38724. };
  38725. return Sprite;
  38726. }());
  38727. BABYLON.Sprite = Sprite;
  38728. })(BABYLON || (BABYLON = {}));
  38729. //# sourceMappingURL=babylon.sprite.js.map
  38730. var BABYLON;
  38731. (function (BABYLON) {
  38732. var IntersectionInfo = (function () {
  38733. function IntersectionInfo(bu, bv, distance) {
  38734. this.bu = bu;
  38735. this.bv = bv;
  38736. this.distance = distance;
  38737. this.faceId = 0;
  38738. this.subMeshId = 0;
  38739. }
  38740. return IntersectionInfo;
  38741. }());
  38742. BABYLON.IntersectionInfo = IntersectionInfo;
  38743. var PickingInfo = (function () {
  38744. function PickingInfo() {
  38745. this.hit = false;
  38746. this.distance = 0;
  38747. this.pickedPoint = null;
  38748. this.pickedMesh = null;
  38749. this.bu = 0;
  38750. this.bv = 0;
  38751. this.faceId = -1;
  38752. this.subMeshId = 0;
  38753. this.pickedSprite = null;
  38754. }
  38755. // Methods
  38756. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  38757. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  38758. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  38759. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38760. return null;
  38761. }
  38762. var indices = this.pickedMesh.getIndices();
  38763. var result;
  38764. if (useVerticesNormals) {
  38765. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38766. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  38767. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  38768. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  38769. normal0 = normal0.scale(this.bu);
  38770. normal1 = normal1.scale(this.bv);
  38771. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  38772. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  38773. }
  38774. else {
  38775. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38776. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  38777. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  38778. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  38779. var p1p2 = vertex1.subtract(vertex2);
  38780. var p3p2 = vertex3.subtract(vertex2);
  38781. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  38782. }
  38783. if (useWorldCoordinates) {
  38784. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  38785. }
  38786. return BABYLON.Vector3.Normalize(result);
  38787. };
  38788. PickingInfo.prototype.getTextureCoordinates = function () {
  38789. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38790. return null;
  38791. }
  38792. var indices = this.pickedMesh.getIndices();
  38793. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38794. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  38795. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  38796. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  38797. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  38798. uv1 = uv1.scale(this.bu);
  38799. uv2 = uv2.scale(this.bv);
  38800. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  38801. };
  38802. return PickingInfo;
  38803. }());
  38804. BABYLON.PickingInfo = PickingInfo;
  38805. })(BABYLON || (BABYLON = {}));
  38806. //# sourceMappingURL=babylon.pickingInfo.js.map
  38807. var BABYLON;
  38808. (function (BABYLON) {
  38809. var Ray = (function () {
  38810. function Ray(origin, direction, length) {
  38811. if (length === void 0) { length = Number.MAX_VALUE; }
  38812. this.origin = origin;
  38813. this.direction = direction;
  38814. this.length = length;
  38815. }
  38816. // Methods
  38817. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  38818. var d = 0.0;
  38819. var maxValue = Number.MAX_VALUE;
  38820. var inv;
  38821. var min;
  38822. var max;
  38823. var temp;
  38824. if (Math.abs(this.direction.x) < 0.0000001) {
  38825. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  38826. return false;
  38827. }
  38828. }
  38829. else {
  38830. inv = 1.0 / this.direction.x;
  38831. min = (minimum.x - this.origin.x) * inv;
  38832. max = (maximum.x - this.origin.x) * inv;
  38833. if (max === -Infinity) {
  38834. max = Infinity;
  38835. }
  38836. if (min > max) {
  38837. temp = min;
  38838. min = max;
  38839. max = temp;
  38840. }
  38841. d = Math.max(min, d);
  38842. maxValue = Math.min(max, maxValue);
  38843. if (d > maxValue) {
  38844. return false;
  38845. }
  38846. }
  38847. if (Math.abs(this.direction.y) < 0.0000001) {
  38848. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  38849. return false;
  38850. }
  38851. }
  38852. else {
  38853. inv = 1.0 / this.direction.y;
  38854. min = (minimum.y - this.origin.y) * inv;
  38855. max = (maximum.y - this.origin.y) * inv;
  38856. if (max === -Infinity) {
  38857. max = Infinity;
  38858. }
  38859. if (min > max) {
  38860. temp = min;
  38861. min = max;
  38862. max = temp;
  38863. }
  38864. d = Math.max(min, d);
  38865. maxValue = Math.min(max, maxValue);
  38866. if (d > maxValue) {
  38867. return false;
  38868. }
  38869. }
  38870. if (Math.abs(this.direction.z) < 0.0000001) {
  38871. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  38872. return false;
  38873. }
  38874. }
  38875. else {
  38876. inv = 1.0 / this.direction.z;
  38877. min = (minimum.z - this.origin.z) * inv;
  38878. max = (maximum.z - this.origin.z) * inv;
  38879. if (max === -Infinity) {
  38880. max = Infinity;
  38881. }
  38882. if (min > max) {
  38883. temp = min;
  38884. min = max;
  38885. max = temp;
  38886. }
  38887. d = Math.max(min, d);
  38888. maxValue = Math.min(max, maxValue);
  38889. if (d > maxValue) {
  38890. return false;
  38891. }
  38892. }
  38893. return true;
  38894. };
  38895. Ray.prototype.intersectsBox = function (box) {
  38896. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  38897. };
  38898. Ray.prototype.intersectsSphere = function (sphere) {
  38899. var x = sphere.center.x - this.origin.x;
  38900. var y = sphere.center.y - this.origin.y;
  38901. var z = sphere.center.z - this.origin.z;
  38902. var pyth = (x * x) + (y * y) + (z * z);
  38903. var rr = sphere.radius * sphere.radius;
  38904. if (pyth <= rr) {
  38905. return true;
  38906. }
  38907. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  38908. if (dot < 0.0) {
  38909. return false;
  38910. }
  38911. var temp = pyth - (dot * dot);
  38912. return temp <= rr;
  38913. };
  38914. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  38915. if (!this._edge1) {
  38916. this._edge1 = BABYLON.Vector3.Zero();
  38917. this._edge2 = BABYLON.Vector3.Zero();
  38918. this._pvec = BABYLON.Vector3.Zero();
  38919. this._tvec = BABYLON.Vector3.Zero();
  38920. this._qvec = BABYLON.Vector3.Zero();
  38921. }
  38922. vertex1.subtractToRef(vertex0, this._edge1);
  38923. vertex2.subtractToRef(vertex0, this._edge2);
  38924. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  38925. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  38926. if (det === 0) {
  38927. return null;
  38928. }
  38929. var invdet = 1 / det;
  38930. this.origin.subtractToRef(vertex0, this._tvec);
  38931. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  38932. if (bu < 0 || bu > 1.0) {
  38933. return null;
  38934. }
  38935. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  38936. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  38937. if (bv < 0 || bu + bv > 1.0) {
  38938. return null;
  38939. }
  38940. //check if the distance is longer than the predefined length.
  38941. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  38942. if (distance > this.length) {
  38943. return null;
  38944. }
  38945. return new BABYLON.IntersectionInfo(bu, bv, distance);
  38946. };
  38947. Ray.prototype.intersectsPlane = function (plane) {
  38948. var distance;
  38949. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  38950. if (Math.abs(result1) < 9.99999997475243E-07) {
  38951. return null;
  38952. }
  38953. else {
  38954. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  38955. distance = (-plane.d - result2) / result1;
  38956. if (distance < 0.0) {
  38957. if (distance < -9.99999997475243E-07) {
  38958. return null;
  38959. }
  38960. else {
  38961. return 0;
  38962. }
  38963. }
  38964. return distance;
  38965. }
  38966. };
  38967. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  38968. var tm = BABYLON.Tmp.Matrix[0];
  38969. mesh.getWorldMatrix().invertToRef(tm);
  38970. if (this._tmpRay) {
  38971. Ray.TransformToRef(this, tm, this._tmpRay);
  38972. }
  38973. else {
  38974. this._tmpRay = Ray.Transform(this, tm);
  38975. }
  38976. return mesh.intersects(this._tmpRay, fastCheck);
  38977. };
  38978. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  38979. if (results) {
  38980. results.length = 0;
  38981. }
  38982. else {
  38983. results = [];
  38984. }
  38985. for (var i = 0; i < meshes.length; i++) {
  38986. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  38987. if (pickInfo.hit) {
  38988. results.push(pickInfo);
  38989. }
  38990. }
  38991. results.sort(this._comparePickingInfo);
  38992. return results;
  38993. };
  38994. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  38995. if (pickingInfoA.distance < pickingInfoB.distance) {
  38996. return -1;
  38997. }
  38998. else if (pickingInfoA.distance > pickingInfoB.distance) {
  38999. return 1;
  39000. }
  39001. else {
  39002. return 0;
  39003. }
  39004. };
  39005. /**
  39006. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  39007. * @param sega the first point of the segment to test the intersection against
  39008. * @param segb the second point of the segment to test the intersection against
  39009. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  39010. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  39011. */
  39012. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  39013. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  39014. var u = segb.subtract(sega);
  39015. var v = rsegb.subtract(this.origin);
  39016. var w = sega.subtract(this.origin);
  39017. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  39018. var b = BABYLON.Vector3.Dot(u, v);
  39019. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  39020. var d = BABYLON.Vector3.Dot(u, w);
  39021. var e = BABYLON.Vector3.Dot(v, w);
  39022. var D = a * c - b * b; // always >= 0
  39023. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  39024. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  39025. // compute the line parameters of the two closest points
  39026. if (D < Ray.smallnum) {
  39027. sN = 0.0; // force using point P0 on segment S1
  39028. sD = 1.0; // to prevent possible division by 0.0 later
  39029. tN = e;
  39030. tD = c;
  39031. }
  39032. else {
  39033. sN = (b * e - c * d);
  39034. tN = (a * e - b * d);
  39035. if (sN < 0.0) {
  39036. sN = 0.0;
  39037. tN = e;
  39038. tD = c;
  39039. }
  39040. else if (sN > sD) {
  39041. sN = sD;
  39042. tN = e + b;
  39043. tD = c;
  39044. }
  39045. }
  39046. if (tN < 0.0) {
  39047. tN = 0.0;
  39048. // recompute sc for this edge
  39049. if (-d < 0.0) {
  39050. sN = 0.0;
  39051. }
  39052. else if (-d > a)
  39053. sN = sD;
  39054. else {
  39055. sN = -d;
  39056. sD = a;
  39057. }
  39058. }
  39059. else if (tN > tD) {
  39060. tN = tD;
  39061. // recompute sc for this edge
  39062. if ((-d + b) < 0.0) {
  39063. sN = 0;
  39064. }
  39065. else if ((-d + b) > a) {
  39066. sN = sD;
  39067. }
  39068. else {
  39069. sN = (-d + b);
  39070. sD = a;
  39071. }
  39072. }
  39073. // finally do the division to get sc and tc
  39074. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  39075. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  39076. // get the difference of the two closest points
  39077. var qtc = v.multiplyByFloats(tc, tc, tc);
  39078. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  39079. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  39080. if (isIntersected) {
  39081. return qtc.length();
  39082. }
  39083. return -1;
  39084. };
  39085. // Statics
  39086. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  39087. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  39088. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  39089. var direction = end.subtract(start);
  39090. direction.normalize();
  39091. return new Ray(start, direction);
  39092. };
  39093. /**
  39094. * 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
  39095. * transformed to the given world matrix.
  39096. * @param origin The origin point
  39097. * @param end The end point
  39098. * @param world a matrix to transform the ray to. Default is the identity matrix.
  39099. */
  39100. Ray.CreateNewFromTo = function (origin, end, world) {
  39101. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  39102. var direction = end.subtract(origin);
  39103. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  39104. direction.normalize();
  39105. return Ray.Transform(new Ray(origin, direction, length), world);
  39106. };
  39107. Ray.Transform = function (ray, matrix) {
  39108. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  39109. Ray.TransformToRef(ray, matrix, result);
  39110. return result;
  39111. };
  39112. Ray.TransformToRef = function (ray, matrix, result) {
  39113. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  39114. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  39115. result.length = ray.length;
  39116. var dir = result.direction;
  39117. var len = dir.length();
  39118. if (!(len === 0 || len === 1)) {
  39119. var num = 1.0 / len;
  39120. dir.x *= num;
  39121. dir.y *= num;
  39122. dir.z *= num;
  39123. result.length *= len;
  39124. }
  39125. };
  39126. Ray.smallnum = 0.00000001;
  39127. Ray.rayl = 10e8;
  39128. return Ray;
  39129. }());
  39130. BABYLON.Ray = Ray;
  39131. })(BABYLON || (BABYLON = {}));
  39132. //# sourceMappingURL=babylon.ray.js.map
  39133. var BABYLON;
  39134. (function (BABYLON) {
  39135. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  39136. if (boxMin.x > sphereCenter.x + sphereRadius)
  39137. return false;
  39138. if (sphereCenter.x - sphereRadius > boxMax.x)
  39139. return false;
  39140. if (boxMin.y > sphereCenter.y + sphereRadius)
  39141. return false;
  39142. if (sphereCenter.y - sphereRadius > boxMax.y)
  39143. return false;
  39144. if (boxMin.z > sphereCenter.z + sphereRadius)
  39145. return false;
  39146. if (sphereCenter.z - sphereRadius > boxMax.z)
  39147. return false;
  39148. return true;
  39149. };
  39150. var getLowestRoot = (function () {
  39151. var result = { root: 0, found: false };
  39152. return function (a, b, c, maxR) {
  39153. result.root = 0;
  39154. result.found = false;
  39155. var determinant = b * b - 4.0 * a * c;
  39156. if (determinant < 0)
  39157. return result;
  39158. var sqrtD = Math.sqrt(determinant);
  39159. var r1 = (-b - sqrtD) / (2.0 * a);
  39160. var r2 = (-b + sqrtD) / (2.0 * a);
  39161. if (r1 > r2) {
  39162. var temp = r2;
  39163. r2 = r1;
  39164. r1 = temp;
  39165. }
  39166. if (r1 > 0 && r1 < maxR) {
  39167. result.root = r1;
  39168. result.found = true;
  39169. return result;
  39170. }
  39171. if (r2 > 0 && r2 < maxR) {
  39172. result.root = r2;
  39173. result.found = true;
  39174. return result;
  39175. }
  39176. return result;
  39177. };
  39178. })();
  39179. var Collider = (function () {
  39180. function Collider() {
  39181. this.radius = BABYLON.Vector3.One();
  39182. this.retry = 0;
  39183. this.basePointWorld = BABYLON.Vector3.Zero();
  39184. this.velocityWorld = BABYLON.Vector3.Zero();
  39185. this.normalizedVelocity = BABYLON.Vector3.Zero();
  39186. this._collisionPoint = BABYLON.Vector3.Zero();
  39187. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  39188. this._tempVector = BABYLON.Vector3.Zero();
  39189. this._tempVector2 = BABYLON.Vector3.Zero();
  39190. this._tempVector3 = BABYLON.Vector3.Zero();
  39191. this._tempVector4 = BABYLON.Vector3.Zero();
  39192. this._edge = BABYLON.Vector3.Zero();
  39193. this._baseToVertex = BABYLON.Vector3.Zero();
  39194. this._destinationPoint = BABYLON.Vector3.Zero();
  39195. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  39196. this._displacementVector = BABYLON.Vector3.Zero();
  39197. this._collisionMask = -1;
  39198. }
  39199. Object.defineProperty(Collider.prototype, "collisionMask", {
  39200. get: function () {
  39201. return this._collisionMask;
  39202. },
  39203. set: function (mask) {
  39204. this._collisionMask = !isNaN(mask) ? mask : -1;
  39205. },
  39206. enumerable: true,
  39207. configurable: true
  39208. });
  39209. // Methods
  39210. Collider.prototype._initialize = function (source, dir, e) {
  39211. this.velocity = dir;
  39212. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  39213. this.basePoint = source;
  39214. source.multiplyToRef(this.radius, this.basePointWorld);
  39215. dir.multiplyToRef(this.radius, this.velocityWorld);
  39216. this.velocityWorldLength = this.velocityWorld.length();
  39217. this.epsilon = e;
  39218. this.collisionFound = false;
  39219. };
  39220. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  39221. pa.subtractToRef(point, this._tempVector);
  39222. pb.subtractToRef(point, this._tempVector2);
  39223. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  39224. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39225. if (d < 0)
  39226. return false;
  39227. pc.subtractToRef(point, this._tempVector3);
  39228. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  39229. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39230. if (d < 0)
  39231. return false;
  39232. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  39233. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39234. return d >= 0;
  39235. };
  39236. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  39237. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  39238. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  39239. if (distance > this.velocityWorldLength + max + sphereRadius) {
  39240. return false;
  39241. }
  39242. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  39243. return false;
  39244. return true;
  39245. };
  39246. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  39247. var t0;
  39248. var embeddedInPlane = false;
  39249. //defensive programming, actually not needed.
  39250. if (!trianglePlaneArray) {
  39251. trianglePlaneArray = [];
  39252. }
  39253. if (!trianglePlaneArray[faceIndex]) {
  39254. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  39255. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  39256. }
  39257. var trianglePlane = trianglePlaneArray[faceIndex];
  39258. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  39259. return;
  39260. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  39261. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  39262. if (normalDotVelocity == 0) {
  39263. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  39264. return;
  39265. embeddedInPlane = true;
  39266. t0 = 0;
  39267. }
  39268. else {
  39269. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39270. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39271. if (t0 > t1) {
  39272. var temp = t1;
  39273. t1 = t0;
  39274. t0 = temp;
  39275. }
  39276. if (t0 > 1.0 || t1 < 0.0)
  39277. return;
  39278. if (t0 < 0)
  39279. t0 = 0;
  39280. if (t0 > 1.0)
  39281. t0 = 1.0;
  39282. }
  39283. this._collisionPoint.copyFromFloats(0, 0, 0);
  39284. var found = false;
  39285. var t = 1.0;
  39286. if (!embeddedInPlane) {
  39287. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  39288. this.velocity.scaleToRef(t0, this._tempVector);
  39289. this._planeIntersectionPoint.addInPlace(this._tempVector);
  39290. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  39291. found = true;
  39292. t = t0;
  39293. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  39294. }
  39295. }
  39296. if (!found) {
  39297. var velocitySquaredLength = this.velocity.lengthSquared();
  39298. var a = velocitySquaredLength;
  39299. this.basePoint.subtractToRef(p1, this._tempVector);
  39300. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39301. var c = this._tempVector.lengthSquared() - 1.0;
  39302. var lowestRoot = getLowestRoot(a, b, c, t);
  39303. if (lowestRoot.found) {
  39304. t = lowestRoot.root;
  39305. found = true;
  39306. this._collisionPoint.copyFrom(p1);
  39307. }
  39308. this.basePoint.subtractToRef(p2, this._tempVector);
  39309. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39310. c = this._tempVector.lengthSquared() - 1.0;
  39311. lowestRoot = getLowestRoot(a, b, c, t);
  39312. if (lowestRoot.found) {
  39313. t = lowestRoot.root;
  39314. found = true;
  39315. this._collisionPoint.copyFrom(p2);
  39316. }
  39317. this.basePoint.subtractToRef(p3, this._tempVector);
  39318. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39319. c = this._tempVector.lengthSquared() - 1.0;
  39320. lowestRoot = getLowestRoot(a, b, c, t);
  39321. if (lowestRoot.found) {
  39322. t = lowestRoot.root;
  39323. found = true;
  39324. this._collisionPoint.copyFrom(p3);
  39325. }
  39326. p2.subtractToRef(p1, this._edge);
  39327. p1.subtractToRef(this.basePoint, this._baseToVertex);
  39328. var edgeSquaredLength = this._edge.lengthSquared();
  39329. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39330. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39331. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39332. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39333. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39334. lowestRoot = getLowestRoot(a, b, c, t);
  39335. if (lowestRoot.found) {
  39336. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39337. if (f >= 0.0 && f <= 1.0) {
  39338. t = lowestRoot.root;
  39339. found = true;
  39340. this._edge.scaleInPlace(f);
  39341. p1.addToRef(this._edge, this._collisionPoint);
  39342. }
  39343. }
  39344. p3.subtractToRef(p2, this._edge);
  39345. p2.subtractToRef(this.basePoint, this._baseToVertex);
  39346. edgeSquaredLength = this._edge.lengthSquared();
  39347. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39348. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39349. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39350. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39351. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39352. lowestRoot = getLowestRoot(a, b, c, t);
  39353. if (lowestRoot.found) {
  39354. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39355. if (f >= 0.0 && f <= 1.0) {
  39356. t = lowestRoot.root;
  39357. found = true;
  39358. this._edge.scaleInPlace(f);
  39359. p2.addToRef(this._edge, this._collisionPoint);
  39360. }
  39361. }
  39362. p1.subtractToRef(p3, this._edge);
  39363. p3.subtractToRef(this.basePoint, this._baseToVertex);
  39364. edgeSquaredLength = this._edge.lengthSquared();
  39365. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39366. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39367. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39368. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39369. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39370. lowestRoot = getLowestRoot(a, b, c, t);
  39371. if (lowestRoot.found) {
  39372. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39373. if (f >= 0.0 && f <= 1.0) {
  39374. t = lowestRoot.root;
  39375. found = true;
  39376. this._edge.scaleInPlace(f);
  39377. p3.addToRef(this._edge, this._collisionPoint);
  39378. }
  39379. }
  39380. }
  39381. if (found) {
  39382. var distToCollision = t * this.velocity.length();
  39383. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  39384. if (!this.intersectionPoint) {
  39385. this.intersectionPoint = this._collisionPoint.clone();
  39386. }
  39387. else {
  39388. this.intersectionPoint.copyFrom(this._collisionPoint);
  39389. }
  39390. this.nearestDistance = distToCollision;
  39391. this.collisionFound = true;
  39392. }
  39393. }
  39394. };
  39395. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  39396. for (var i = indexStart; i < indexEnd; i += 3) {
  39397. var p1 = pts[indices[i] - decal];
  39398. var p2 = pts[indices[i + 1] - decal];
  39399. var p3 = pts[indices[i + 2] - decal];
  39400. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  39401. }
  39402. };
  39403. Collider.prototype._getResponse = function (pos, vel) {
  39404. pos.addToRef(vel, this._destinationPoint);
  39405. vel.scaleInPlace((this.nearestDistance / vel.length()));
  39406. this.basePoint.addToRef(vel, pos);
  39407. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  39408. this._slidePlaneNormal.normalize();
  39409. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  39410. pos.addInPlace(this._displacementVector);
  39411. this.intersectionPoint.addInPlace(this._displacementVector);
  39412. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  39413. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  39414. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  39415. };
  39416. return Collider;
  39417. }());
  39418. BABYLON.Collider = Collider;
  39419. })(BABYLON || (BABYLON = {}));
  39420. //# sourceMappingURL=babylon.collider.js.map
  39421. var BABYLON;
  39422. (function (BABYLON) {
  39423. //WebWorker code will be inserted to this variable.
  39424. BABYLON.CollisionWorker = "";
  39425. var WorkerTaskType;
  39426. (function (WorkerTaskType) {
  39427. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  39428. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  39429. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  39430. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  39431. var WorkerReplyType;
  39432. (function (WorkerReplyType) {
  39433. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  39434. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  39435. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  39436. var CollisionCoordinatorWorker = (function () {
  39437. function CollisionCoordinatorWorker() {
  39438. var _this = this;
  39439. this._scaledPosition = BABYLON.Vector3.Zero();
  39440. this._scaledVelocity = BABYLON.Vector3.Zero();
  39441. this.onMeshUpdated = function (mesh) {
  39442. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  39443. };
  39444. this.onGeometryUpdated = function (geometry) {
  39445. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  39446. };
  39447. this._afterRender = function () {
  39448. if (!_this._init)
  39449. return;
  39450. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  39451. return;
  39452. }
  39453. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  39454. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  39455. if (_this._runningUpdated > 4) {
  39456. return;
  39457. }
  39458. ++_this._runningUpdated;
  39459. var payload = {
  39460. updatedMeshes: _this._addUpdateMeshesList,
  39461. updatedGeometries: _this._addUpdateGeometriesList,
  39462. removedGeometries: _this._toRemoveGeometryArray,
  39463. removedMeshes: _this._toRemoveMeshesArray
  39464. };
  39465. var message = {
  39466. payload: payload,
  39467. taskType: WorkerTaskType.UPDATE
  39468. };
  39469. var serializable = [];
  39470. for (var id in payload.updatedGeometries) {
  39471. if (payload.updatedGeometries.hasOwnProperty(id)) {
  39472. //prepare transferables
  39473. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  39474. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  39475. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  39476. }
  39477. }
  39478. _this._worker.postMessage(message, serializable);
  39479. _this._addUpdateMeshesList = {};
  39480. _this._addUpdateGeometriesList = {};
  39481. _this._toRemoveGeometryArray = [];
  39482. _this._toRemoveMeshesArray = [];
  39483. };
  39484. this._onMessageFromWorker = function (e) {
  39485. var returnData = e.data;
  39486. if (returnData.error != WorkerReplyType.SUCCESS) {
  39487. //TODO what errors can be returned from the worker?
  39488. BABYLON.Tools.Warn("error returned from worker!");
  39489. return;
  39490. }
  39491. switch (returnData.taskType) {
  39492. case WorkerTaskType.INIT:
  39493. _this._init = true;
  39494. //Update the worked with ALL of the scene's current state
  39495. _this._scene.meshes.forEach(function (mesh) {
  39496. _this.onMeshAdded(mesh);
  39497. });
  39498. _this._scene.getGeometries().forEach(function (geometry) {
  39499. _this.onGeometryAdded(geometry);
  39500. });
  39501. break;
  39502. case WorkerTaskType.UPDATE:
  39503. _this._runningUpdated--;
  39504. break;
  39505. case WorkerTaskType.COLLIDE:
  39506. _this._runningCollisionTask = false;
  39507. var returnPayload = returnData.payload;
  39508. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  39509. return;
  39510. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  39511. //cleanup
  39512. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  39513. break;
  39514. }
  39515. };
  39516. this._collisionsCallbackArray = [];
  39517. this._init = false;
  39518. this._runningUpdated = 0;
  39519. this._runningCollisionTask = false;
  39520. this._addUpdateMeshesList = {};
  39521. this._addUpdateGeometriesList = {};
  39522. this._toRemoveGeometryArray = [];
  39523. this._toRemoveMeshesArray = [];
  39524. }
  39525. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  39526. if (!this._init)
  39527. return;
  39528. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  39529. return;
  39530. position.divideToRef(collider.radius, this._scaledPosition);
  39531. velocity.divideToRef(collider.radius, this._scaledVelocity);
  39532. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  39533. var payload = {
  39534. collider: {
  39535. position: this._scaledPosition.asArray(),
  39536. velocity: this._scaledVelocity.asArray(),
  39537. radius: collider.radius.asArray()
  39538. },
  39539. collisionId: collisionIndex,
  39540. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  39541. maximumRetry: maximumRetry
  39542. };
  39543. var message = {
  39544. payload: payload,
  39545. taskType: WorkerTaskType.COLLIDE
  39546. };
  39547. this._worker.postMessage(message);
  39548. };
  39549. CollisionCoordinatorWorker.prototype.init = function (scene) {
  39550. this._scene = scene;
  39551. this._scene.registerAfterRender(this._afterRender);
  39552. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  39553. this._worker = new Worker(workerUrl);
  39554. this._worker.onmessage = this._onMessageFromWorker;
  39555. var message = {
  39556. payload: {},
  39557. taskType: WorkerTaskType.INIT
  39558. };
  39559. this._worker.postMessage(message);
  39560. };
  39561. CollisionCoordinatorWorker.prototype.destroy = function () {
  39562. this._scene.unregisterAfterRender(this._afterRender);
  39563. this._worker.terminate();
  39564. };
  39565. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  39566. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  39567. this.onMeshUpdated(mesh);
  39568. };
  39569. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  39570. this._toRemoveMeshesArray.push(mesh.uniqueId);
  39571. };
  39572. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  39573. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  39574. geometry.onGeometryUpdated = this.onGeometryUpdated;
  39575. this.onGeometryUpdated(geometry);
  39576. };
  39577. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  39578. this._toRemoveGeometryArray.push(geometry.id);
  39579. };
  39580. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  39581. var submeshes = [];
  39582. if (mesh.subMeshes) {
  39583. submeshes = mesh.subMeshes.map(function (sm, idx) {
  39584. return {
  39585. position: idx,
  39586. verticesStart: sm.verticesStart,
  39587. verticesCount: sm.verticesCount,
  39588. indexStart: sm.indexStart,
  39589. indexCount: sm.indexCount,
  39590. hasMaterial: !!sm.getMaterial(),
  39591. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  39592. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  39593. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  39594. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  39595. };
  39596. });
  39597. }
  39598. var geometryId = null;
  39599. if (mesh instanceof BABYLON.Mesh) {
  39600. geometryId = mesh.geometry ? mesh.geometry.id : null;
  39601. }
  39602. else if (mesh instanceof BABYLON.InstancedMesh) {
  39603. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  39604. }
  39605. return {
  39606. uniqueId: mesh.uniqueId,
  39607. id: mesh.id,
  39608. name: mesh.name,
  39609. geometryId: geometryId,
  39610. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  39611. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  39612. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  39613. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  39614. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  39615. subMeshes: submeshes,
  39616. checkCollisions: mesh.checkCollisions
  39617. };
  39618. };
  39619. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  39620. return {
  39621. id: geometry.id,
  39622. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  39623. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  39624. indices: new Uint32Array(geometry.getIndices() || []),
  39625. };
  39626. };
  39627. return CollisionCoordinatorWorker;
  39628. }());
  39629. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  39630. var CollisionCoordinatorLegacy = (function () {
  39631. function CollisionCoordinatorLegacy() {
  39632. this._scaledPosition = BABYLON.Vector3.Zero();
  39633. this._scaledVelocity = BABYLON.Vector3.Zero();
  39634. this._finalPosition = BABYLON.Vector3.Zero();
  39635. }
  39636. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  39637. position.divideToRef(collider.radius, this._scaledPosition);
  39638. velocity.divideToRef(collider.radius, this._scaledVelocity);
  39639. collider.collidedMesh = null;
  39640. collider.retry = 0;
  39641. collider.initialVelocity = this._scaledVelocity;
  39642. collider.initialPosition = this._scaledPosition;
  39643. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  39644. this._finalPosition.multiplyInPlace(collider.radius);
  39645. //run the callback
  39646. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  39647. };
  39648. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  39649. this._scene = scene;
  39650. };
  39651. CollisionCoordinatorLegacy.prototype.destroy = function () {
  39652. //Legacy need no destruction method.
  39653. };
  39654. //No update in legacy mode
  39655. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  39656. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  39657. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  39658. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  39659. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  39660. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  39661. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  39662. if (excludedMesh === void 0) { excludedMesh = null; }
  39663. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  39664. if (collider.retry >= maximumRetry) {
  39665. finalPosition.copyFrom(position);
  39666. return;
  39667. }
  39668. // Check if this is a mesh else camera or -1
  39669. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  39670. collider._initialize(position, velocity, closeDistance);
  39671. // Check all meshes
  39672. for (var index = 0; index < this._scene.meshes.length; index++) {
  39673. var mesh = this._scene.meshes[index];
  39674. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  39675. mesh._checkCollision(collider);
  39676. }
  39677. }
  39678. if (!collider.collisionFound) {
  39679. position.addToRef(velocity, finalPosition);
  39680. return;
  39681. }
  39682. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  39683. collider._getResponse(position, velocity);
  39684. }
  39685. if (velocity.length() <= closeDistance) {
  39686. finalPosition.copyFrom(position);
  39687. return;
  39688. }
  39689. collider.retry++;
  39690. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  39691. };
  39692. return CollisionCoordinatorLegacy;
  39693. }());
  39694. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  39695. })(BABYLON || (BABYLON = {}));
  39696. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  39697. var BABYLON;
  39698. (function (BABYLON) {
  39699. var Particle = (function () {
  39700. function Particle() {
  39701. this.position = BABYLON.Vector3.Zero();
  39702. this.direction = BABYLON.Vector3.Zero();
  39703. this.color = new BABYLON.Color4(0, 0, 0, 0);
  39704. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  39705. this.lifeTime = 1.0;
  39706. this.age = 0;
  39707. this.size = 0;
  39708. this.angle = 0;
  39709. this.angularSpeed = 0;
  39710. }
  39711. Particle.prototype.copyTo = function (other) {
  39712. other.position.copyFrom(this.position);
  39713. other.direction.copyFrom(this.direction);
  39714. other.color.copyFrom(this.color);
  39715. other.colorStep.copyFrom(this.colorStep);
  39716. other.lifeTime = this.lifeTime;
  39717. other.age = this.age;
  39718. other.size = this.size;
  39719. other.angle = this.angle;
  39720. other.angularSpeed = this.angularSpeed;
  39721. };
  39722. return Particle;
  39723. }());
  39724. BABYLON.Particle = Particle;
  39725. })(BABYLON || (BABYLON = {}));
  39726. //# sourceMappingURL=babylon.particle.js.map
  39727. var BABYLON;
  39728. (function (BABYLON) {
  39729. var randomNumber = function (min, max) {
  39730. if (min === max) {
  39731. return (min);
  39732. }
  39733. var random = Math.random();
  39734. return ((random * (max - min)) + min);
  39735. };
  39736. var ParticleSystem = (function () {
  39737. function ParticleSystem(name, capacity, scene, customEffect) {
  39738. var _this = this;
  39739. this.name = name;
  39740. // Members
  39741. this.animations = [];
  39742. this.renderingGroupId = 0;
  39743. this.emitter = null;
  39744. this.emitRate = 10;
  39745. this.manualEmitCount = -1;
  39746. this.updateSpeed = 0.01;
  39747. this.targetStopDuration = 0;
  39748. this.disposeOnStop = false;
  39749. this.minEmitPower = 1;
  39750. this.maxEmitPower = 1;
  39751. this.minLifeTime = 1;
  39752. this.maxLifeTime = 1;
  39753. this.minSize = 1;
  39754. this.maxSize = 1;
  39755. this.minAngularSpeed = 0;
  39756. this.maxAngularSpeed = 0;
  39757. this.layerMask = 0x0FFFFFFF;
  39758. this.customShader = null;
  39759. this.preventAutoStart = false;
  39760. /**
  39761. * An event triggered when the system is disposed.
  39762. * @type {BABYLON.Observable}
  39763. */
  39764. this.onDisposeObservable = new BABYLON.Observable();
  39765. this.onAnimationEnd = null;
  39766. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  39767. this.forceDepthWrite = false;
  39768. this.gravity = BABYLON.Vector3.Zero();
  39769. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  39770. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  39771. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  39772. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39773. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39774. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39775. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  39776. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39777. this.particles = new Array();
  39778. this._stockParticles = new Array();
  39779. this._newPartsExcess = 0;
  39780. this._vertexBuffers = {};
  39781. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  39782. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  39783. this._scaledDirection = BABYLON.Vector3.Zero();
  39784. this._scaledGravity = BABYLON.Vector3.Zero();
  39785. this._currentRenderId = -1;
  39786. this._started = false;
  39787. this._stopped = false;
  39788. this._actualFrame = 0;
  39789. this.id = name;
  39790. this._capacity = capacity;
  39791. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  39792. this._customEffect = customEffect;
  39793. scene.particleSystems.push(this);
  39794. var indices = [];
  39795. var index = 0;
  39796. for (var count = 0; count < capacity; count++) {
  39797. indices.push(index);
  39798. indices.push(index + 1);
  39799. indices.push(index + 2);
  39800. indices.push(index);
  39801. indices.push(index + 2);
  39802. indices.push(index + 3);
  39803. index += 4;
  39804. }
  39805. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39806. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  39807. this._vertexData = new Float32Array(capacity * 11 * 4);
  39808. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  39809. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  39810. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  39811. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  39812. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39813. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39814. this._vertexBuffers["options"] = options;
  39815. // Default behaviors
  39816. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  39817. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  39818. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  39819. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  39820. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  39821. };
  39822. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  39823. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  39824. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  39825. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  39826. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  39827. };
  39828. this.updateFunction = function (particles) {
  39829. for (var index = 0; index < particles.length; index++) {
  39830. var particle = particles[index];
  39831. particle.age += _this._scaledUpdateSpeed;
  39832. if (particle.age >= particle.lifeTime) {
  39833. _this.recycleParticle(particle);
  39834. index--;
  39835. continue;
  39836. }
  39837. else {
  39838. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  39839. particle.color.addInPlace(_this._scaledColorStep);
  39840. if (particle.color.a < 0)
  39841. particle.color.a = 0;
  39842. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  39843. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  39844. particle.position.addInPlace(_this._scaledDirection);
  39845. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  39846. particle.direction.addInPlace(_this._scaledGravity);
  39847. }
  39848. }
  39849. };
  39850. }
  39851. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  39852. set: function (callback) {
  39853. if (this._onDisposeObserver) {
  39854. this.onDisposeObservable.remove(this._onDisposeObserver);
  39855. }
  39856. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39857. },
  39858. enumerable: true,
  39859. configurable: true
  39860. });
  39861. ParticleSystem.prototype.recycleParticle = function (particle) {
  39862. var lastParticle = this.particles.pop();
  39863. if (lastParticle !== particle) {
  39864. lastParticle.copyTo(particle);
  39865. this._stockParticles.push(lastParticle);
  39866. }
  39867. };
  39868. ParticleSystem.prototype.getCapacity = function () {
  39869. return this._capacity;
  39870. };
  39871. ParticleSystem.prototype.isAlive = function () {
  39872. return this._alive;
  39873. };
  39874. ParticleSystem.prototype.isStarted = function () {
  39875. return this._started;
  39876. };
  39877. ParticleSystem.prototype.start = function () {
  39878. this._started = true;
  39879. this._stopped = false;
  39880. this._actualFrame = 0;
  39881. };
  39882. ParticleSystem.prototype.stop = function () {
  39883. this._stopped = true;
  39884. };
  39885. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  39886. var offset = index * 11;
  39887. this._vertexData[offset] = particle.position.x;
  39888. this._vertexData[offset + 1] = particle.position.y;
  39889. this._vertexData[offset + 2] = particle.position.z;
  39890. this._vertexData[offset + 3] = particle.color.r;
  39891. this._vertexData[offset + 4] = particle.color.g;
  39892. this._vertexData[offset + 5] = particle.color.b;
  39893. this._vertexData[offset + 6] = particle.color.a;
  39894. this._vertexData[offset + 7] = particle.angle;
  39895. this._vertexData[offset + 8] = particle.size;
  39896. this._vertexData[offset + 9] = offsetX;
  39897. this._vertexData[offset + 10] = offsetY;
  39898. };
  39899. ParticleSystem.prototype._update = function (newParticles) {
  39900. // Update current
  39901. this._alive = this.particles.length > 0;
  39902. this.updateFunction(this.particles);
  39903. // Add new ones
  39904. var worldMatrix;
  39905. if (this.emitter.position) {
  39906. var emitterMesh = this.emitter;
  39907. worldMatrix = emitterMesh.getWorldMatrix();
  39908. }
  39909. else {
  39910. var emitterPosition = this.emitter;
  39911. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  39912. }
  39913. var particle;
  39914. for (var index = 0; index < newParticles; index++) {
  39915. if (this.particles.length === this._capacity) {
  39916. break;
  39917. }
  39918. if (this._stockParticles.length !== 0) {
  39919. particle = this._stockParticles.pop();
  39920. particle.age = 0;
  39921. }
  39922. else {
  39923. particle = new BABYLON.Particle();
  39924. }
  39925. this.particles.push(particle);
  39926. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  39927. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  39928. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  39929. particle.size = randomNumber(this.minSize, this.maxSize);
  39930. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  39931. this.startPositionFunction(worldMatrix, particle.position, particle);
  39932. var step = randomNumber(0, 1.0);
  39933. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  39934. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  39935. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  39936. }
  39937. };
  39938. ParticleSystem.prototype._getEffect = function () {
  39939. if (this._customEffect) {
  39940. return this._customEffect;
  39941. }
  39942. ;
  39943. var defines = [];
  39944. if (this._scene.clipPlane) {
  39945. defines.push("#define CLIPPLANE");
  39946. }
  39947. // Effect
  39948. var join = defines.join("\n");
  39949. if (this._cachedDefines !== join) {
  39950. this._cachedDefines = join;
  39951. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  39952. }
  39953. return this._effect;
  39954. };
  39955. ParticleSystem.prototype.animate = function () {
  39956. if (!this._started)
  39957. return;
  39958. var effect = this._getEffect();
  39959. // Check
  39960. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  39961. return;
  39962. if (this._currentRenderId === this._scene.getRenderId()) {
  39963. return;
  39964. }
  39965. this._currentRenderId = this._scene.getRenderId();
  39966. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  39967. // determine the number of particles we need to create
  39968. var newParticles;
  39969. if (this.manualEmitCount > -1) {
  39970. newParticles = this.manualEmitCount;
  39971. this._newPartsExcess = 0;
  39972. this.manualEmitCount = 0;
  39973. }
  39974. else {
  39975. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  39976. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  39977. }
  39978. if (this._newPartsExcess > 1.0) {
  39979. newParticles += this._newPartsExcess >> 0;
  39980. this._newPartsExcess -= this._newPartsExcess >> 0;
  39981. }
  39982. this._alive = false;
  39983. if (!this._stopped) {
  39984. this._actualFrame += this._scaledUpdateSpeed;
  39985. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  39986. this.stop();
  39987. }
  39988. else {
  39989. newParticles = 0;
  39990. }
  39991. this._update(newParticles);
  39992. // Stopped?
  39993. if (this._stopped) {
  39994. if (!this._alive) {
  39995. this._started = false;
  39996. if (this.onAnimationEnd) {
  39997. this.onAnimationEnd();
  39998. }
  39999. if (this.disposeOnStop) {
  40000. this._scene._toBeDisposed.push(this);
  40001. }
  40002. }
  40003. }
  40004. // Update VBO
  40005. var offset = 0;
  40006. for (var index = 0; index < this.particles.length; index++) {
  40007. var particle = this.particles[index];
  40008. this._appendParticleVertex(offset++, particle, 0, 0);
  40009. this._appendParticleVertex(offset++, particle, 1, 0);
  40010. this._appendParticleVertex(offset++, particle, 1, 1);
  40011. this._appendParticleVertex(offset++, particle, 0, 1);
  40012. }
  40013. this._vertexBuffer.update(this._vertexData);
  40014. };
  40015. ParticleSystem.prototype.render = function () {
  40016. var effect = this._getEffect();
  40017. // Check
  40018. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  40019. return 0;
  40020. var engine = this._scene.getEngine();
  40021. // Render
  40022. engine.enableEffect(effect);
  40023. engine.setState(false);
  40024. var viewMatrix = this._scene.getViewMatrix();
  40025. effect.setTexture("diffuseSampler", this.particleTexture);
  40026. effect.setMatrix("view", viewMatrix);
  40027. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  40028. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  40029. if (this._scene.clipPlane) {
  40030. var clipPlane = this._scene.clipPlane;
  40031. var invView = viewMatrix.clone();
  40032. invView.invert();
  40033. effect.setMatrix("invView", invView);
  40034. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  40035. }
  40036. // VBOs
  40037. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40038. // Draw order
  40039. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  40040. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  40041. }
  40042. else {
  40043. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40044. }
  40045. if (this.forceDepthWrite) {
  40046. engine.setDepthWrite(true);
  40047. }
  40048. engine.draw(true, 0, this.particles.length * 6);
  40049. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40050. return this.particles.length;
  40051. };
  40052. ParticleSystem.prototype.dispose = function () {
  40053. if (this._vertexBuffer) {
  40054. this._vertexBuffer.dispose();
  40055. this._vertexBuffer = null;
  40056. }
  40057. if (this._indexBuffer) {
  40058. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40059. this._indexBuffer = null;
  40060. }
  40061. if (this.particleTexture) {
  40062. this.particleTexture.dispose();
  40063. this.particleTexture = null;
  40064. }
  40065. // Remove from scene
  40066. var index = this._scene.particleSystems.indexOf(this);
  40067. if (index > -1) {
  40068. this._scene.particleSystems.splice(index, 1);
  40069. }
  40070. // Callback
  40071. this.onDisposeObservable.notifyObservers(this);
  40072. this.onDisposeObservable.clear();
  40073. };
  40074. // Clone
  40075. ParticleSystem.prototype.clone = function (name, newEmitter) {
  40076. var custom = null;
  40077. var program = null;
  40078. if (this.customShader != null) {
  40079. program = this.customShader;
  40080. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40081. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40082. }
  40083. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  40084. result.customShader = program;
  40085. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  40086. if (newEmitter === undefined) {
  40087. newEmitter = this.emitter;
  40088. }
  40089. result.emitter = newEmitter;
  40090. if (this.particleTexture) {
  40091. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  40092. }
  40093. if (!this.preventAutoStart) {
  40094. result.start();
  40095. }
  40096. return result;
  40097. };
  40098. ParticleSystem.prototype.serialize = function () {
  40099. var serializationObject = {};
  40100. serializationObject.name = this.name;
  40101. serializationObject.id = this.id;
  40102. // Emitter
  40103. if (this.emitter.position) {
  40104. var emitterMesh = this.emitter;
  40105. serializationObject.emitterId = emitterMesh.id;
  40106. }
  40107. else {
  40108. var emitterPosition = this.emitter;
  40109. serializationObject.emitter = emitterPosition.asArray();
  40110. }
  40111. serializationObject.capacity = this.getCapacity();
  40112. if (this.particleTexture) {
  40113. serializationObject.textureName = this.particleTexture.name;
  40114. }
  40115. // Animations
  40116. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  40117. // Particle system
  40118. serializationObject.minAngularSpeed = this.minAngularSpeed;
  40119. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  40120. serializationObject.minSize = this.minSize;
  40121. serializationObject.maxSize = this.maxSize;
  40122. serializationObject.minEmitPower = this.minEmitPower;
  40123. serializationObject.maxEmitPower = this.maxEmitPower;
  40124. serializationObject.minLifeTime = this.minLifeTime;
  40125. serializationObject.maxLifeTime = this.maxLifeTime;
  40126. serializationObject.emitRate = this.emitRate;
  40127. serializationObject.minEmitBox = this.minEmitBox.asArray();
  40128. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  40129. serializationObject.gravity = this.gravity.asArray();
  40130. serializationObject.direction1 = this.direction1.asArray();
  40131. serializationObject.direction2 = this.direction2.asArray();
  40132. serializationObject.color1 = this.color1.asArray();
  40133. serializationObject.color2 = this.color2.asArray();
  40134. serializationObject.colorDead = this.colorDead.asArray();
  40135. serializationObject.updateSpeed = this.updateSpeed;
  40136. serializationObject.targetStopDuration = this.targetStopDuration;
  40137. serializationObject.textureMask = this.textureMask.asArray();
  40138. serializationObject.blendMode = this.blendMode;
  40139. serializationObject.customShader = this.customShader;
  40140. serializationObject.preventAutoStart = this.preventAutoStart;
  40141. return serializationObject;
  40142. };
  40143. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  40144. var name = parsedParticleSystem.name;
  40145. var custom = null;
  40146. var program = null;
  40147. if (parsedParticleSystem.customShader) {
  40148. program = parsedParticleSystem.customShader;
  40149. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40150. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40151. }
  40152. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  40153. particleSystem.customShader = program;
  40154. if (parsedParticleSystem.id) {
  40155. particleSystem.id = parsedParticleSystem.id;
  40156. }
  40157. // Auto start
  40158. if (parsedParticleSystem.preventAutoStart) {
  40159. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  40160. }
  40161. // Texture
  40162. if (parsedParticleSystem.textureName) {
  40163. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  40164. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  40165. }
  40166. // Emitter
  40167. if (parsedParticleSystem.emitterId) {
  40168. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  40169. }
  40170. else {
  40171. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  40172. }
  40173. // Animations
  40174. if (parsedParticleSystem.animations) {
  40175. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  40176. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  40177. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40178. }
  40179. }
  40180. if (parsedParticleSystem.autoAnimate) {
  40181. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  40182. }
  40183. // Particle system
  40184. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  40185. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  40186. particleSystem.minSize = parsedParticleSystem.minSize;
  40187. particleSystem.maxSize = parsedParticleSystem.maxSize;
  40188. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  40189. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  40190. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  40191. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  40192. particleSystem.emitRate = parsedParticleSystem.emitRate;
  40193. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  40194. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  40195. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  40196. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  40197. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  40198. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  40199. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  40200. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  40201. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  40202. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  40203. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  40204. particleSystem.blendMode = parsedParticleSystem.blendMode;
  40205. if (!particleSystem.preventAutoStart) {
  40206. particleSystem.start();
  40207. }
  40208. return particleSystem;
  40209. };
  40210. // Statics
  40211. ParticleSystem.BLENDMODE_ONEONE = 0;
  40212. ParticleSystem.BLENDMODE_STANDARD = 1;
  40213. return ParticleSystem;
  40214. }());
  40215. BABYLON.ParticleSystem = ParticleSystem;
  40216. })(BABYLON || (BABYLON = {}));
  40217. //# sourceMappingURL=babylon.particleSystem.js.map
  40218. var BABYLON;
  40219. (function (BABYLON) {
  40220. var SolidParticle = (function () {
  40221. /**
  40222. * Creates a Solid Particle object.
  40223. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  40224. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  40225. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  40226. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  40227. * `shapeId` (integer) is the model shape identifier in the SPS.
  40228. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  40229. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  40230. */
  40231. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  40232. this.idx = 0; // particle global index
  40233. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  40234. this.position = BABYLON.Vector3.Zero(); // position
  40235. this.rotation = BABYLON.Vector3.Zero(); // rotation
  40236. this.scaling = BABYLON.Vector3.One(); // scaling
  40237. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  40238. this.velocity = BABYLON.Vector3.Zero(); // velocity
  40239. this.alive = true; // alive
  40240. this.isVisible = true; // visibility
  40241. this._pos = 0; // index of this particle in the global "positions" array
  40242. this.shapeId = 0; // model shape id
  40243. this.idxInShape = 0; // index of the particle in its shape id
  40244. this.idx = particleIndex;
  40245. this._pos = positionIndex;
  40246. this._model = model;
  40247. this.shapeId = shapeId;
  40248. this.idxInShape = idxInShape;
  40249. this._sps = sps;
  40250. if (modelBoundingInfo) {
  40251. this._modelBoundingInfo = modelBoundingInfo;
  40252. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  40253. }
  40254. }
  40255. Object.defineProperty(SolidParticle.prototype, "scale", {
  40256. /**
  40257. * legacy support, changed scale to scaling
  40258. */
  40259. get: function () {
  40260. return this.scaling;
  40261. },
  40262. set: function (scale) {
  40263. this.scaling = scale;
  40264. },
  40265. enumerable: true,
  40266. configurable: true
  40267. });
  40268. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  40269. /**
  40270. * legacy support, changed quaternion to rotationQuaternion
  40271. */
  40272. get: function () {
  40273. return this.rotationQuaternion;
  40274. },
  40275. set: function (q) {
  40276. this.rotationQuaternion = q;
  40277. },
  40278. enumerable: true,
  40279. configurable: true
  40280. });
  40281. /**
  40282. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  40283. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  40284. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  40285. */
  40286. SolidParticle.prototype.intersectsMesh = function (target) {
  40287. if (!this._boundingInfo || !target._boundingInfo) {
  40288. return false;
  40289. }
  40290. if (this._sps._bSphereOnly) {
  40291. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  40292. }
  40293. return this._boundingInfo.intersects(target._boundingInfo, false);
  40294. };
  40295. return SolidParticle;
  40296. }());
  40297. BABYLON.SolidParticle = SolidParticle;
  40298. var ModelShape = (function () {
  40299. /**
  40300. * 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.
  40301. * SPS internal tool, don't use it manually.
  40302. */
  40303. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  40304. this.shapeID = id;
  40305. this._shape = shape;
  40306. this._shapeUV = shapeUV;
  40307. this._positionFunction = posFunction;
  40308. this._vertexFunction = vtxFunction;
  40309. }
  40310. return ModelShape;
  40311. }());
  40312. BABYLON.ModelShape = ModelShape;
  40313. })(BABYLON || (BABYLON = {}));
  40314. //# sourceMappingURL=babylon.solidParticle.js.map
  40315. var BABYLON;
  40316. (function (BABYLON) {
  40317. /**
  40318. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  40319. */
  40320. var SolidParticleSystem = (function () {
  40321. /**
  40322. * Creates a SPS (Solid Particle System) object.
  40323. * `name` (String) is the SPS name, this will be the underlying mesh name.
  40324. * `scene` (Scene) is the scene in which the SPS is added.
  40325. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  40326. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  40327. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  40328. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  40329. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  40330. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  40331. */
  40332. function SolidParticleSystem(name, scene, options) {
  40333. // public members
  40334. /**
  40335. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  40336. * Example : var p = SPS.particles[i];
  40337. */
  40338. this.particles = new Array();
  40339. /**
  40340. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  40341. */
  40342. this.nbParticles = 0;
  40343. /**
  40344. * If the particles must ever face the camera (default false). Useful for planar particles.
  40345. */
  40346. this.billboard = false;
  40347. /**
  40348. * Recompute normals when adding a shape
  40349. */
  40350. this.recomputeNormals = true;
  40351. /**
  40352. * This a counter ofr your own usage. It's not set by any SPS functions.
  40353. */
  40354. this.counter = 0;
  40355. /**
  40356. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  40357. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  40358. */
  40359. this.vars = {};
  40360. this._positions = new Array();
  40361. this._indices = new Array();
  40362. this._normals = new Array();
  40363. this._colors = new Array();
  40364. this._uvs = new Array();
  40365. this._index = 0; // indices index
  40366. this._updatable = true;
  40367. this._pickable = false;
  40368. this._isVisibilityBoxLocked = false;
  40369. this._alwaysVisible = false;
  40370. this._shapeCounter = 0;
  40371. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  40372. this._color = new BABYLON.Color4(0, 0, 0, 0);
  40373. this._computeParticleColor = true;
  40374. this._computeParticleTexture = true;
  40375. this._computeParticleRotation = true;
  40376. this._computeParticleVertex = false;
  40377. this._computeBoundingBox = false;
  40378. this._cam_axisZ = BABYLON.Vector3.Zero();
  40379. this._cam_axisY = BABYLON.Vector3.Zero();
  40380. this._cam_axisX = BABYLON.Vector3.Zero();
  40381. this._axisX = BABYLON.Axis.X;
  40382. this._axisY = BABYLON.Axis.Y;
  40383. this._axisZ = BABYLON.Axis.Z;
  40384. this._camDir = BABYLON.Vector3.Zero();
  40385. this._rotMatrix = new BABYLON.Matrix();
  40386. this._invertMatrix = new BABYLON.Matrix();
  40387. this._rotated = BABYLON.Vector3.Zero();
  40388. this._quaternion = new BABYLON.Quaternion();
  40389. this._vertex = BABYLON.Vector3.Zero();
  40390. this._normal = BABYLON.Vector3.Zero();
  40391. this._yaw = 0.0;
  40392. this._pitch = 0.0;
  40393. this._roll = 0.0;
  40394. this._halfroll = 0.0;
  40395. this._halfpitch = 0.0;
  40396. this._halfyaw = 0.0;
  40397. this._sinRoll = 0.0;
  40398. this._cosRoll = 0.0;
  40399. this._sinPitch = 0.0;
  40400. this._cosPitch = 0.0;
  40401. this._sinYaw = 0.0;
  40402. this._cosYaw = 0.0;
  40403. this._w = 0.0;
  40404. this._mustUnrotateFixedNormals = false;
  40405. this._minimum = BABYLON.Tmp.Vector3[0];
  40406. this._maximum = BABYLON.Tmp.Vector3[1];
  40407. this._scale = BABYLON.Tmp.Vector3[2];
  40408. this._translation = BABYLON.Tmp.Vector3[3];
  40409. this._minBbox = BABYLON.Tmp.Vector3[4];
  40410. this._maxBbox = BABYLON.Tmp.Vector3[5];
  40411. this._particlesIntersect = false;
  40412. this._bSphereOnly = false;
  40413. this._bSphereRadiusFactor = 1.0;
  40414. this.name = name;
  40415. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40416. this._camera = scene.activeCamera;
  40417. this._pickable = options ? options.isPickable : false;
  40418. this._particlesIntersect = options ? options.particleIntersection : false;
  40419. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  40420. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  40421. if (options && options.updatable) {
  40422. this._updatable = options.updatable;
  40423. }
  40424. else {
  40425. this._updatable = true;
  40426. }
  40427. if (this._pickable) {
  40428. this.pickedParticles = [];
  40429. }
  40430. }
  40431. /**
  40432. * Builds the SPS underlying mesh. Returns a standard Mesh.
  40433. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  40434. */
  40435. SolidParticleSystem.prototype.buildMesh = function () {
  40436. if (this.nbParticles === 0) {
  40437. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  40438. this.addShape(triangle, 1);
  40439. triangle.dispose();
  40440. }
  40441. this._positions32 = new Float32Array(this._positions);
  40442. this._uvs32 = new Float32Array(this._uvs);
  40443. this._colors32 = new Float32Array(this._colors);
  40444. if (this.recomputeNormals) {
  40445. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  40446. }
  40447. this._normals32 = new Float32Array(this._normals);
  40448. this._fixedNormal32 = new Float32Array(this._normals);
  40449. if (this._mustUnrotateFixedNormals) {
  40450. this._unrotateFixedNormals();
  40451. }
  40452. var vertexData = new BABYLON.VertexData();
  40453. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40454. vertexData.indices = this._indices;
  40455. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40456. if (this._uvs32) {
  40457. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  40458. ;
  40459. }
  40460. if (this._colors32) {
  40461. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  40462. }
  40463. var mesh = new BABYLON.Mesh(this.name, this._scene);
  40464. vertexData.applyToMesh(mesh, this._updatable);
  40465. this.mesh = mesh;
  40466. this.mesh.isPickable = this._pickable;
  40467. // free memory
  40468. this._positions = null;
  40469. this._normals = null;
  40470. this._uvs = null;
  40471. this._colors = null;
  40472. if (!this._updatable) {
  40473. this.particles.length = 0;
  40474. }
  40475. return mesh;
  40476. };
  40477. /**
  40478. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  40479. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  40480. * Thus the particles generated from `digest()` have their property `position` set yet.
  40481. * `mesh` ( Mesh ) is the mesh to be digested
  40482. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  40483. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  40484. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  40485. */
  40486. SolidParticleSystem.prototype.digest = function (mesh, options) {
  40487. var size = (options && options.facetNb) || 1;
  40488. var number = (options && options.number);
  40489. var delta = (options && options.delta) || 0;
  40490. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40491. var meshInd = mesh.getIndices();
  40492. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40493. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40494. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40495. var f = 0; // facet counter
  40496. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  40497. // compute size from number
  40498. if (number) {
  40499. number = (number > totalFacets) ? totalFacets : number;
  40500. size = Math.round(totalFacets / number);
  40501. delta = 0;
  40502. }
  40503. else {
  40504. size = (size > totalFacets) ? totalFacets : size;
  40505. }
  40506. var facetPos = []; // submesh positions
  40507. var facetInd = []; // submesh indices
  40508. var facetUV = []; // submesh UV
  40509. var facetCol = []; // submesh colors
  40510. var barycenter = BABYLON.Tmp.Vector3[0];
  40511. var rand;
  40512. var sizeO = size;
  40513. while (f < totalFacets) {
  40514. size = sizeO + Math.floor((1 + delta) * Math.random());
  40515. if (f > totalFacets - size) {
  40516. size = totalFacets - f;
  40517. }
  40518. // reset temp arrays
  40519. facetPos.length = 0;
  40520. facetInd.length = 0;
  40521. facetUV.length = 0;
  40522. facetCol.length = 0;
  40523. // iterate over "size" facets
  40524. var fi = 0;
  40525. for (var j = f * 3; j < (f + size) * 3; j++) {
  40526. facetInd.push(fi);
  40527. var i = meshInd[j];
  40528. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  40529. if (meshUV) {
  40530. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  40531. }
  40532. if (meshCol) {
  40533. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  40534. }
  40535. fi++;
  40536. }
  40537. // create a model shape for each single particle
  40538. var idx = this.nbParticles;
  40539. var shape = this._posToShape(facetPos);
  40540. var shapeUV = this._uvsToShapeUV(facetUV);
  40541. // compute the barycenter of the shape
  40542. var v;
  40543. for (v = 0; v < shape.length; v++) {
  40544. barycenter.addInPlace(shape[v]);
  40545. }
  40546. barycenter.scaleInPlace(1 / shape.length);
  40547. // shift the shape from its barycenter to the origin
  40548. for (v = 0; v < shape.length; v++) {
  40549. shape[v].subtractInPlace(barycenter);
  40550. }
  40551. var bInfo;
  40552. if (this._particlesIntersect) {
  40553. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  40554. }
  40555. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  40556. // add the particle in the SPS
  40557. var currentPos = this._positions.length;
  40558. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  40559. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  40560. // initialize the particle position
  40561. this.particles[this.nbParticles].position.addInPlace(barycenter);
  40562. this._index += shape.length;
  40563. idx++;
  40564. this.nbParticles++;
  40565. this._shapeCounter++;
  40566. f += size;
  40567. }
  40568. return this;
  40569. };
  40570. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  40571. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  40572. var index = 0;
  40573. var idx = 0;
  40574. for (var p = 0; p < this.particles.length; p++) {
  40575. this._particle = this.particles[p];
  40576. this._shape = this._particle._model._shape;
  40577. if (this._particle.rotationQuaternion) {
  40578. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40579. }
  40580. else {
  40581. this._yaw = this._particle.rotation.y;
  40582. this._pitch = this._particle.rotation.x;
  40583. this._roll = this._particle.rotation.z;
  40584. this._quaternionRotationYPR();
  40585. }
  40586. this._quaternionToRotationMatrix();
  40587. this._rotMatrix.invertToRef(this._invertMatrix);
  40588. for (var pt = 0; pt < this._shape.length; pt++) {
  40589. idx = index + pt * 3;
  40590. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  40591. this._fixedNormal32[idx] = this._normal.x;
  40592. this._fixedNormal32[idx + 1] = this._normal.y;
  40593. this._fixedNormal32[idx + 2] = this._normal.z;
  40594. }
  40595. index = idx + 3;
  40596. }
  40597. };
  40598. //reset copy
  40599. SolidParticleSystem.prototype._resetCopy = function () {
  40600. this._copy.position.x = 0;
  40601. this._copy.position.y = 0;
  40602. this._copy.position.z = 0;
  40603. this._copy.rotation.x = 0;
  40604. this._copy.rotation.y = 0;
  40605. this._copy.rotation.z = 0;
  40606. this._copy.rotationQuaternion = null;
  40607. this._copy.scaling.x = 1;
  40608. this._copy.scaling.y = 1;
  40609. this._copy.scaling.z = 1;
  40610. this._copy.uvs.x = 0;
  40611. this._copy.uvs.y = 0;
  40612. this._copy.uvs.z = 1;
  40613. this._copy.uvs.w = 1;
  40614. this._copy.color = null;
  40615. };
  40616. // _meshBuilder : inserts the shape model in the global SPS mesh
  40617. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  40618. var i;
  40619. var u = 0;
  40620. var c = 0;
  40621. var n = 0;
  40622. this._resetCopy();
  40623. if (options && options.positionFunction) {
  40624. options.positionFunction(this._copy, idx, idxInShape);
  40625. this._mustUnrotateFixedNormals = true;
  40626. }
  40627. if (this._copy.rotationQuaternion) {
  40628. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  40629. }
  40630. else {
  40631. this._yaw = this._copy.rotation.y;
  40632. this._pitch = this._copy.rotation.x;
  40633. this._roll = this._copy.rotation.z;
  40634. this._quaternionRotationYPR();
  40635. }
  40636. this._quaternionToRotationMatrix();
  40637. for (i = 0; i < shape.length; i++) {
  40638. this._vertex.x = shape[i].x;
  40639. this._vertex.y = shape[i].y;
  40640. this._vertex.z = shape[i].z;
  40641. if (options && options.vertexFunction) {
  40642. options.vertexFunction(this._copy, this._vertex, i);
  40643. }
  40644. this._vertex.x *= this._copy.scaling.x;
  40645. this._vertex.y *= this._copy.scaling.y;
  40646. this._vertex.z *= this._copy.scaling.z;
  40647. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40648. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  40649. if (meshUV) {
  40650. 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);
  40651. u += 2;
  40652. }
  40653. if (this._copy.color) {
  40654. this._color = this._copy.color;
  40655. }
  40656. else if (meshCol && meshCol[c] !== undefined) {
  40657. this._color.r = meshCol[c];
  40658. this._color.g = meshCol[c + 1];
  40659. this._color.b = meshCol[c + 2];
  40660. this._color.a = meshCol[c + 3];
  40661. }
  40662. else {
  40663. this._color.r = 1;
  40664. this._color.g = 1;
  40665. this._color.b = 1;
  40666. this._color.a = 1;
  40667. }
  40668. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  40669. c += 4;
  40670. if (!this.recomputeNormals && meshNor) {
  40671. this._normal.x = meshNor[n];
  40672. this._normal.y = meshNor[n + 1];
  40673. this._normal.z = meshNor[n + 2];
  40674. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  40675. normals.push(this._normal.x, this._normal.y, this._normal.z);
  40676. n += 3;
  40677. }
  40678. }
  40679. for (i = 0; i < meshInd.length; i++) {
  40680. indices.push(p + meshInd[i]);
  40681. }
  40682. if (this._pickable) {
  40683. var nbfaces = meshInd.length / 3;
  40684. for (i = 0; i < nbfaces; i++) {
  40685. this.pickedParticles.push({ idx: idx, faceId: i });
  40686. }
  40687. }
  40688. return this._copy;
  40689. };
  40690. // returns a shape array from positions array
  40691. SolidParticleSystem.prototype._posToShape = function (positions) {
  40692. var shape = [];
  40693. for (var i = 0; i < positions.length; i += 3) {
  40694. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  40695. }
  40696. return shape;
  40697. };
  40698. // returns a shapeUV array from a Vector4 uvs
  40699. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  40700. var shapeUV = [];
  40701. if (uvs) {
  40702. for (var i = 0; i < uvs.length; i++)
  40703. shapeUV.push(uvs[i]);
  40704. }
  40705. return shapeUV;
  40706. };
  40707. // adds a new particle object in the particles array
  40708. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  40709. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  40710. this.particles.push(sp);
  40711. return sp;
  40712. };
  40713. /**
  40714. * Adds some particles to the SPS from the model shape. Returns the shape id.
  40715. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  40716. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  40717. * `nb` (positive integer) the number of particles to be created from this model
  40718. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  40719. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  40720. */
  40721. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  40722. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40723. var meshInd = mesh.getIndices();
  40724. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40725. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40726. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40727. var bbInfo;
  40728. if (this._particlesIntersect) {
  40729. bbInfo = mesh.getBoundingInfo();
  40730. }
  40731. var shape = this._posToShape(meshPos);
  40732. var shapeUV = this._uvsToShapeUV(meshUV);
  40733. var posfunc = options ? options.positionFunction : null;
  40734. var vtxfunc = options ? options.vertexFunction : null;
  40735. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  40736. // particles
  40737. var sp;
  40738. var currentCopy;
  40739. var idx = this.nbParticles;
  40740. for (var i = 0; i < nb; i++) {
  40741. var currentPos = this._positions.length;
  40742. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  40743. if (this._updatable) {
  40744. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  40745. sp.position.copyFrom(currentCopy.position);
  40746. sp.rotation.copyFrom(currentCopy.rotation);
  40747. if (currentCopy.rotationQuaternion) {
  40748. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  40749. }
  40750. if (currentCopy.color) {
  40751. sp.color.copyFrom(currentCopy.color);
  40752. }
  40753. sp.scaling.copyFrom(currentCopy.scaling);
  40754. sp.uvs.copyFrom(currentCopy.uvs);
  40755. }
  40756. this._index += shape.length;
  40757. idx++;
  40758. }
  40759. this.nbParticles += nb;
  40760. this._shapeCounter++;
  40761. return this._shapeCounter - 1;
  40762. };
  40763. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  40764. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  40765. this._resetCopy();
  40766. if (particle._model._positionFunction) {
  40767. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  40768. }
  40769. if (this._copy.rotationQuaternion) {
  40770. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  40771. }
  40772. else {
  40773. this._yaw = this._copy.rotation.y;
  40774. this._pitch = this._copy.rotation.x;
  40775. this._roll = this._copy.rotation.z;
  40776. this._quaternionRotationYPR();
  40777. }
  40778. this._quaternionToRotationMatrix();
  40779. this._shape = particle._model._shape;
  40780. for (var pt = 0; pt < this._shape.length; pt++) {
  40781. this._vertex.x = this._shape[pt].x;
  40782. this._vertex.y = this._shape[pt].y;
  40783. this._vertex.z = this._shape[pt].z;
  40784. if (particle._model._vertexFunction) {
  40785. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  40786. }
  40787. this._vertex.x *= this._copy.scaling.x;
  40788. this._vertex.y *= this._copy.scaling.y;
  40789. this._vertex.z *= this._copy.scaling.z;
  40790. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  40791. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  40792. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  40793. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  40794. }
  40795. particle.position.x = 0.0;
  40796. particle.position.y = 0.0;
  40797. particle.position.z = 0.0;
  40798. particle.rotation.x = 0.0;
  40799. particle.rotation.y = 0.0;
  40800. particle.rotation.z = 0.0;
  40801. particle.rotationQuaternion = null;
  40802. particle.scaling.x = 1.0;
  40803. particle.scaling.y = 1.0;
  40804. particle.scaling.z = 1.0;
  40805. };
  40806. /**
  40807. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  40808. * Returns the SPS.
  40809. */
  40810. SolidParticleSystem.prototype.rebuildMesh = function () {
  40811. for (var p = 0; p < this.particles.length; p++) {
  40812. this._rebuildParticle(this.particles[p]);
  40813. }
  40814. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  40815. return this;
  40816. };
  40817. /**
  40818. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  40819. * This method calls `updateParticle()` for each particle of the SPS.
  40820. * For an animated SPS, it is usually called within the render loop.
  40821. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  40822. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  40823. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  40824. * Returns the SPS.
  40825. */
  40826. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  40827. if (start === void 0) { start = 0; }
  40828. if (end === void 0) { end = this.nbParticles - 1; }
  40829. if (update === void 0) { update = true; }
  40830. if (!this._updatable) {
  40831. return;
  40832. }
  40833. // custom beforeUpdate
  40834. this.beforeUpdateParticles(start, end, update);
  40835. this._cam_axisX.x = 1.0;
  40836. this._cam_axisX.y = 0.0;
  40837. this._cam_axisX.z = 0.0;
  40838. this._cam_axisY.x = 0.0;
  40839. this._cam_axisY.y = 1.0;
  40840. this._cam_axisY.z = 0.0;
  40841. this._cam_axisZ.x = 0.0;
  40842. this._cam_axisZ.y = 0.0;
  40843. this._cam_axisZ.z = 1.0;
  40844. // if the particles will always face the camera
  40845. if (this.billboard) {
  40846. this.mesh.computeWorldMatrix(true);
  40847. // compute the camera position and un-rotate it by the current mesh rotation
  40848. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  40849. this._quaternionToRotationMatrix();
  40850. this._rotMatrix.invertToRef(this._invertMatrix);
  40851. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  40852. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  40853. this._cam_axisZ.normalize();
  40854. // same for camera up vector extracted from the cam view matrix
  40855. var view = this._camera.getViewMatrix(true);
  40856. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  40857. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  40858. this._cam_axisY.normalize();
  40859. this._cam_axisX.normalize();
  40860. }
  40861. }
  40862. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  40863. var idx = 0; // current position index in the global array positions32
  40864. var index = 0; // position start index in the global array positions32 of the current particle
  40865. var colidx = 0; // current color index in the global array colors32
  40866. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  40867. var uvidx = 0; // current uv index in the global array uvs32
  40868. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  40869. var pt = 0; // current index in the particle model shape
  40870. if (this.mesh.isFacetDataEnabled) {
  40871. this._computeBoundingBox = true;
  40872. }
  40873. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  40874. if (this._computeBoundingBox) {
  40875. if (start == 0 && end == this.nbParticles - 1) {
  40876. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  40877. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  40878. }
  40879. else {
  40880. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  40881. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  40882. }
  40883. }
  40884. // particle loop
  40885. index = this.particles[start]._pos;
  40886. var vpos = (index / 3) | 0;
  40887. colorIndex = vpos * 4;
  40888. uvIndex = vpos * 2;
  40889. for (var p = start; p <= end; p++) {
  40890. this._particle = this.particles[p];
  40891. this._shape = this._particle._model._shape;
  40892. this._shapeUV = this._particle._model._shapeUV;
  40893. // call to custom user function to update the particle properties
  40894. this.updateParticle(this._particle);
  40895. if (this._particle.isVisible) {
  40896. // particle rotation matrix
  40897. if (this.billboard) {
  40898. this._particle.rotation.x = 0.0;
  40899. this._particle.rotation.y = 0.0;
  40900. }
  40901. if (this._computeParticleRotation || this.billboard) {
  40902. if (this._particle.rotationQuaternion) {
  40903. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40904. }
  40905. else {
  40906. this._yaw = this._particle.rotation.y;
  40907. this._pitch = this._particle.rotation.x;
  40908. this._roll = this._particle.rotation.z;
  40909. this._quaternionRotationYPR();
  40910. }
  40911. this._quaternionToRotationMatrix();
  40912. }
  40913. // particle vertex loop
  40914. for (pt = 0; pt < this._shape.length; pt++) {
  40915. idx = index + pt * 3;
  40916. colidx = colorIndex + pt * 4;
  40917. uvidx = uvIndex + pt * 2;
  40918. this._vertex.x = this._shape[pt].x;
  40919. this._vertex.y = this._shape[pt].y;
  40920. this._vertex.z = this._shape[pt].z;
  40921. if (this._computeParticleVertex) {
  40922. this.updateParticleVertex(this._particle, this._vertex, pt);
  40923. }
  40924. // positions
  40925. this._vertex.x *= this._particle.scaling.x;
  40926. this._vertex.y *= this._particle.scaling.y;
  40927. this._vertex.z *= this._particle.scaling.z;
  40928. 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];
  40929. 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;
  40930. 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;
  40931. 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;
  40932. 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;
  40933. 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;
  40934. 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;
  40935. if (this._computeBoundingBox) {
  40936. if (this._positions32[idx] < this._minimum.x) {
  40937. this._minimum.x = this._positions32[idx];
  40938. }
  40939. if (this._positions32[idx] > this._maximum.x) {
  40940. this._maximum.x = this._positions32[idx];
  40941. }
  40942. if (this._positions32[idx + 1] < this._minimum.y) {
  40943. this._minimum.y = this._positions32[idx + 1];
  40944. }
  40945. if (this._positions32[idx + 1] > this._maximum.y) {
  40946. this._maximum.y = this._positions32[idx + 1];
  40947. }
  40948. if (this._positions32[idx + 2] < this._minimum.z) {
  40949. this._minimum.z = this._positions32[idx + 2];
  40950. }
  40951. if (this._positions32[idx + 2] > this._maximum.z) {
  40952. this._maximum.z = this._positions32[idx + 2];
  40953. }
  40954. }
  40955. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  40956. if (!this._computeParticleVertex) {
  40957. this._normal.x = this._fixedNormal32[idx];
  40958. this._normal.y = this._fixedNormal32[idx + 1];
  40959. this._normal.z = this._fixedNormal32[idx + 2];
  40960. 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]);
  40961. 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]);
  40962. 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]);
  40963. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  40964. 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;
  40965. 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;
  40966. }
  40967. if (this._computeParticleColor) {
  40968. this._colors32[colidx] = this._particle.color.r;
  40969. this._colors32[colidx + 1] = this._particle.color.g;
  40970. this._colors32[colidx + 2] = this._particle.color.b;
  40971. this._colors32[colidx + 3] = this._particle.color.a;
  40972. }
  40973. if (this._computeParticleTexture) {
  40974. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40975. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40976. }
  40977. }
  40978. }
  40979. else {
  40980. for (pt = 0; pt < this._shape.length; pt++) {
  40981. idx = index + pt * 3;
  40982. colidx = colorIndex + pt * 4;
  40983. uvidx = uvIndex + pt * 2;
  40984. this._positions32[idx] = this._camera.globalPosition.x;
  40985. this._positions32[idx + 1] = this._camera.globalPosition.y;
  40986. this._positions32[idx + 2] = this._camera.globalPosition.z;
  40987. this._normals32[idx] = 0.0;
  40988. this._normals32[idx + 1] = 0.0;
  40989. this._normals32[idx + 2] = 0.0;
  40990. if (this._computeParticleColor) {
  40991. this._colors32[colidx] = this._particle.color.r;
  40992. this._colors32[colidx + 1] = this._particle.color.g;
  40993. this._colors32[colidx + 2] = this._particle.color.b;
  40994. this._colors32[colidx + 3] = this._particle.color.a;
  40995. }
  40996. if (this._computeParticleTexture) {
  40997. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  40998. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  40999. }
  41000. }
  41001. }
  41002. // if the particle intersections must be computed : update the bbInfo
  41003. if (this._particlesIntersect) {
  41004. var bInfo = this._particle._boundingInfo;
  41005. var bBox = bInfo.boundingBox;
  41006. var bSphere = bInfo.boundingSphere;
  41007. if (!this._bSphereOnly) {
  41008. // place, scale and rotate the particle bbox within the SPS local system, then update it
  41009. for (var b = 0; b < bBox.vectors.length; b++) {
  41010. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  41011. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  41012. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  41013. 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];
  41014. 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;
  41015. 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;
  41016. 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;
  41017. 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;
  41018. 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;
  41019. 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;
  41020. }
  41021. bBox._update(this.mesh._worldMatrix);
  41022. }
  41023. // place and scale the particle bouding sphere in the SPS local system, then update it
  41024. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  41025. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  41026. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  41027. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  41028. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  41029. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  41030. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  41031. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  41032. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  41033. 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));
  41034. bSphere._update(this.mesh._worldMatrix);
  41035. }
  41036. // increment indexes for the next particle
  41037. index = idx + 3;
  41038. colorIndex = colidx + 4;
  41039. uvIndex = uvidx + 2;
  41040. }
  41041. // if the VBO must be updated
  41042. if (update) {
  41043. if (this._computeParticleColor) {
  41044. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41045. }
  41046. if (this._computeParticleTexture) {
  41047. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41048. }
  41049. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41050. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  41051. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  41052. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  41053. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  41054. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  41055. for (var i = 0; i < this._normals32.length; i++) {
  41056. this._fixedNormal32[i] = this._normals32[i];
  41057. }
  41058. }
  41059. if (!this.mesh.areNormalsFrozen) {
  41060. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41061. }
  41062. }
  41063. }
  41064. if (this._computeBoundingBox) {
  41065. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41066. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41067. }
  41068. this.afterUpdateParticles(start, end, update);
  41069. return this;
  41070. };
  41071. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  41072. this._halfroll = this._roll * 0.5;
  41073. this._halfpitch = this._pitch * 0.5;
  41074. this._halfyaw = this._yaw * 0.5;
  41075. this._sinRoll = Math.sin(this._halfroll);
  41076. this._cosRoll = Math.cos(this._halfroll);
  41077. this._sinPitch = Math.sin(this._halfpitch);
  41078. this._cosPitch = Math.cos(this._halfpitch);
  41079. this._sinYaw = Math.sin(this._halfyaw);
  41080. this._cosYaw = Math.cos(this._halfyaw);
  41081. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  41082. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  41083. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  41084. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  41085. };
  41086. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  41087. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  41088. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  41089. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  41090. this._rotMatrix.m[3] = 0;
  41091. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  41092. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  41093. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  41094. this._rotMatrix.m[7] = 0;
  41095. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  41096. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  41097. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  41098. this._rotMatrix.m[11] = 0;
  41099. this._rotMatrix.m[12] = 0;
  41100. this._rotMatrix.m[13] = 0;
  41101. this._rotMatrix.m[14] = 0;
  41102. this._rotMatrix.m[15] = 1.0;
  41103. };
  41104. /**
  41105. * Disposes the SPS.
  41106. * Returns nothing.
  41107. */
  41108. SolidParticleSystem.prototype.dispose = function () {
  41109. this.mesh.dispose();
  41110. this.vars = null;
  41111. // drop references to internal big arrays for the GC
  41112. this._positions = null;
  41113. this._indices = null;
  41114. this._normals = null;
  41115. this._uvs = null;
  41116. this._colors = null;
  41117. this._positions32 = null;
  41118. this._normals32 = null;
  41119. this._fixedNormal32 = null;
  41120. this._uvs32 = null;
  41121. this._colors32 = null;
  41122. this.pickedParticles = null;
  41123. };
  41124. /**
  41125. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  41126. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41127. * Returns the SPS.
  41128. */
  41129. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  41130. if (!this._isVisibilityBoxLocked) {
  41131. this.mesh.refreshBoundingInfo();
  41132. }
  41133. return this;
  41134. };
  41135. /**
  41136. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  41137. * @param size the size (float) of the visibility box
  41138. * note : this doesn't lock the SPS mesh bounding box.
  41139. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41140. */
  41141. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  41142. var vis = size / 2;
  41143. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  41144. };
  41145. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  41146. // getter and setter
  41147. get: function () {
  41148. return this._alwaysVisible;
  41149. },
  41150. /**
  41151. * Sets the SPS as always visible or not
  41152. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41153. */
  41154. set: function (val) {
  41155. this._alwaysVisible = val;
  41156. this.mesh.alwaysSelectAsActiveMesh = val;
  41157. },
  41158. enumerable: true,
  41159. configurable: true
  41160. });
  41161. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  41162. get: function () {
  41163. return this._isVisibilityBoxLocked;
  41164. },
  41165. /**
  41166. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  41167. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41168. */
  41169. set: function (val) {
  41170. this._isVisibilityBoxLocked = val;
  41171. this.mesh.getBoundingInfo().isLocked = val;
  41172. },
  41173. enumerable: true,
  41174. configurable: true
  41175. });
  41176. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  41177. // getters
  41178. get: function () {
  41179. return this._computeParticleRotation;
  41180. },
  41181. // Optimizer setters
  41182. /**
  41183. * Tells to `setParticles()` to compute the particle rotations or not.
  41184. * Default value : true. The SPS is faster when it's set to false.
  41185. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  41186. */
  41187. set: function (val) {
  41188. this._computeParticleRotation = val;
  41189. },
  41190. enumerable: true,
  41191. configurable: true
  41192. });
  41193. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  41194. get: function () {
  41195. return this._computeParticleColor;
  41196. },
  41197. /**
  41198. * Tells to `setParticles()` to compute the particle colors or not.
  41199. * Default value : true. The SPS is faster when it's set to false.
  41200. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  41201. */
  41202. set: function (val) {
  41203. this._computeParticleColor = val;
  41204. },
  41205. enumerable: true,
  41206. configurable: true
  41207. });
  41208. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  41209. get: function () {
  41210. return this._computeParticleTexture;
  41211. },
  41212. /**
  41213. * Tells to `setParticles()` to compute the particle textures or not.
  41214. * Default value : true. The SPS is faster when it's set to false.
  41215. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  41216. */
  41217. set: function (val) {
  41218. this._computeParticleTexture = val;
  41219. },
  41220. enumerable: true,
  41221. configurable: true
  41222. });
  41223. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  41224. get: function () {
  41225. return this._computeParticleVertex;
  41226. },
  41227. /**
  41228. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  41229. * Default value : false. The SPS is faster when it's set to false.
  41230. * Note : the particle custom vertex positions aren't stored values.
  41231. */
  41232. set: function (val) {
  41233. this._computeParticleVertex = val;
  41234. },
  41235. enumerable: true,
  41236. configurable: true
  41237. });
  41238. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  41239. get: function () {
  41240. return this._computeBoundingBox;
  41241. },
  41242. /**
  41243. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  41244. */
  41245. set: function (val) {
  41246. this._computeBoundingBox = val;
  41247. },
  41248. enumerable: true,
  41249. configurable: true
  41250. });
  41251. // =======================================================================
  41252. // Particle behavior logic
  41253. // these following methods may be overwritten by the user to fit his needs
  41254. /**
  41255. * This function does nothing. It may be overwritten to set all the particle first values.
  41256. * The SPS doesn't call this function, you may have to call it by your own.
  41257. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41258. */
  41259. SolidParticleSystem.prototype.initParticles = function () {
  41260. };
  41261. /**
  41262. * This function does nothing. It may be overwritten to recycle a particle.
  41263. * The SPS doesn't call this function, you may have to call it by your own.
  41264. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41265. */
  41266. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  41267. return particle;
  41268. };
  41269. /**
  41270. * Updates a particle : this function should be overwritten by the user.
  41271. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  41272. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41273. * ex : just set a particle position or velocity and recycle conditions
  41274. */
  41275. SolidParticleSystem.prototype.updateParticle = function (particle) {
  41276. return particle;
  41277. };
  41278. /**
  41279. * Updates a vertex of a particle : it can be overwritten by the user.
  41280. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  41281. * @param particle the current particle
  41282. * @param vertex the current index of the current particle
  41283. * @param pt the index of the current vertex in the particle shape
  41284. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  41285. * ex : just set a vertex particle position
  41286. */
  41287. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  41288. return vertex;
  41289. };
  41290. /**
  41291. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  41292. * This does nothing and may be overwritten by the user.
  41293. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41294. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41295. * @param update the boolean update value actually passed to setParticles()
  41296. */
  41297. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  41298. };
  41299. /**
  41300. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  41301. * This will be passed three parameters.
  41302. * This does nothing and may be overwritten by the user.
  41303. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41304. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41305. * @param update the boolean update value actually passed to setParticles()
  41306. */
  41307. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  41308. };
  41309. return SolidParticleSystem;
  41310. }());
  41311. BABYLON.SolidParticleSystem = SolidParticleSystem;
  41312. })(BABYLON || (BABYLON = {}));
  41313. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  41314. /// <reference path="babylon.mesh.ts" />
  41315. var BABYLON;
  41316. (function (BABYLON) {
  41317. var GroundMesh = (function (_super) {
  41318. __extends(GroundMesh, _super);
  41319. function GroundMesh(name, scene) {
  41320. var _this = _super.call(this, name, scene) || this;
  41321. _this.generateOctree = false;
  41322. _this._worldInverse = new BABYLON.Matrix();
  41323. return _this;
  41324. }
  41325. GroundMesh.prototype.getClassName = function () {
  41326. return "GroundMesh";
  41327. };
  41328. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41329. get: function () {
  41330. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41331. },
  41332. enumerable: true,
  41333. configurable: true
  41334. });
  41335. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41336. get: function () {
  41337. return this._subdivisionsX;
  41338. },
  41339. enumerable: true,
  41340. configurable: true
  41341. });
  41342. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41343. get: function () {
  41344. return this._subdivisionsY;
  41345. },
  41346. enumerable: true,
  41347. configurable: true
  41348. });
  41349. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41350. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41351. this._subdivisionsX = chunksCount;
  41352. this._subdivisionsY = chunksCount;
  41353. this.subdivide(chunksCount);
  41354. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41355. };
  41356. /**
  41357. * Returns a height (y) value in the Worl system :
  41358. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41359. * Returns the ground y position if (x, z) are outside the ground surface.
  41360. */
  41361. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41362. var world = this.getWorldMatrix();
  41363. var invMat = BABYLON.Tmp.Matrix[5];
  41364. world.invertToRef(invMat);
  41365. var tmpVect = BABYLON.Tmp.Vector3[8];
  41366. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41367. x = tmpVect.x;
  41368. z = tmpVect.z;
  41369. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41370. return this.position.y;
  41371. }
  41372. if (!this._heightQuads || this._heightQuads.length == 0) {
  41373. this._initHeightQuads();
  41374. this._computeHeightQuads();
  41375. }
  41376. var facet = this._getFacetAt(x, z);
  41377. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41378. // return y in the World system
  41379. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41380. return tmpVect.y;
  41381. };
  41382. /**
  41383. * Returns a normalized vector (Vector3) orthogonal to the ground
  41384. * at the ground coordinates (x, z) expressed in the World system.
  41385. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41386. */
  41387. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41388. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41389. this.getNormalAtCoordinatesToRef(x, z, normal);
  41390. return normal;
  41391. };
  41392. /**
  41393. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41394. * at the ground coordinates (x, z) expressed in the World system.
  41395. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41396. * Returns the GroundMesh.
  41397. */
  41398. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41399. var world = this.getWorldMatrix();
  41400. var tmpMat = BABYLON.Tmp.Matrix[5];
  41401. world.invertToRef(tmpMat);
  41402. var tmpVect = BABYLON.Tmp.Vector3[8];
  41403. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41404. x = tmpVect.x;
  41405. z = tmpVect.z;
  41406. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41407. return this;
  41408. }
  41409. if (!this._heightQuads || this._heightQuads.length == 0) {
  41410. this._initHeightQuads();
  41411. this._computeHeightQuads();
  41412. }
  41413. var facet = this._getFacetAt(x, z);
  41414. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41415. return this;
  41416. };
  41417. /**
  41418. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41419. * if the ground has been updated.
  41420. * This can be used in the render loop.
  41421. * Returns the GroundMesh.
  41422. */
  41423. GroundMesh.prototype.updateCoordinateHeights = function () {
  41424. if (!this._heightQuads || this._heightQuads.length == 0) {
  41425. this._initHeightQuads();
  41426. }
  41427. this._computeHeightQuads();
  41428. return this;
  41429. };
  41430. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41431. GroundMesh.prototype._getFacetAt = function (x, z) {
  41432. // retrieve col and row from x, z coordinates in the ground local system
  41433. var subdivisionsX = this._subdivisionsX;
  41434. var subdivisionsY = this._subdivisionsY;
  41435. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41436. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41437. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41438. var facet;
  41439. if (z < quad.slope.x * x + quad.slope.y) {
  41440. facet = quad.facet1;
  41441. }
  41442. else {
  41443. facet = quad.facet2;
  41444. }
  41445. return facet;
  41446. };
  41447. // Creates and populates the heightMap array with "facet" elements :
  41448. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  41449. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41450. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41451. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41452. // Returns the GroundMesh.
  41453. GroundMesh.prototype._initHeightQuads = function () {
  41454. var subdivisionsX = this._subdivisionsX;
  41455. var subdivisionsY = this._subdivisionsY;
  41456. this._heightQuads = new Array();
  41457. for (var row = 0; row < subdivisionsY; row++) {
  41458. for (var col = 0; col < subdivisionsX; col++) {
  41459. 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) };
  41460. this._heightQuads[row * subdivisionsX + col] = quad;
  41461. }
  41462. }
  41463. return this;
  41464. };
  41465. // Compute each quad element values and update the the heightMap array :
  41466. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41467. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41468. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41469. // Returns the GroundMesh.
  41470. GroundMesh.prototype._computeHeightQuads = function () {
  41471. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41472. var v1 = BABYLON.Tmp.Vector3[3];
  41473. var v2 = BABYLON.Tmp.Vector3[2];
  41474. var v3 = BABYLON.Tmp.Vector3[1];
  41475. var v4 = BABYLON.Tmp.Vector3[0];
  41476. var v1v2 = BABYLON.Tmp.Vector3[4];
  41477. var v1v3 = BABYLON.Tmp.Vector3[5];
  41478. var v1v4 = BABYLON.Tmp.Vector3[6];
  41479. var norm1 = BABYLON.Tmp.Vector3[7];
  41480. var norm2 = BABYLON.Tmp.Vector3[8];
  41481. var i = 0;
  41482. var j = 0;
  41483. var k = 0;
  41484. var cd = 0; // 2D slope coefficient : z = cd * x + h
  41485. var h = 0;
  41486. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  41487. var d2 = 0;
  41488. var subdivisionsX = this._subdivisionsX;
  41489. var subdivisionsY = this._subdivisionsY;
  41490. for (var row = 0; row < subdivisionsY; row++) {
  41491. for (var col = 0; col < subdivisionsX; col++) {
  41492. i = col * 3;
  41493. j = row * (subdivisionsX + 1) * 3;
  41494. k = (row + 1) * (subdivisionsX + 1) * 3;
  41495. v1.x = positions[j + i];
  41496. v1.y = positions[j + i + 1];
  41497. v1.z = positions[j + i + 2];
  41498. v2.x = positions[j + i + 3];
  41499. v2.y = positions[j + i + 4];
  41500. v2.z = positions[j + i + 5];
  41501. v3.x = positions[k + i];
  41502. v3.y = positions[k + i + 1];
  41503. v3.z = positions[k + i + 2];
  41504. v4.x = positions[k + i + 3];
  41505. v4.y = positions[k + i + 4];
  41506. v4.z = positions[k + i + 5];
  41507. // 2D slope V1V4
  41508. cd = (v4.z - v1.z) / (v4.x - v1.x);
  41509. h = v1.z - cd * v1.x; // v1 belongs to the slope
  41510. // facet equations :
  41511. // we compute each facet normal vector
  41512. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  41513. // we compute the value d by applying the equation to v1 which belongs to the plane
  41514. // then we store the facet equation in a Vector4
  41515. v2.subtractToRef(v1, v1v2);
  41516. v3.subtractToRef(v1, v1v3);
  41517. v4.subtractToRef(v1, v1v4);
  41518. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  41519. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  41520. norm1.normalize();
  41521. norm2.normalize();
  41522. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  41523. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  41524. var quad = this._heightQuads[row * subdivisionsX + col];
  41525. quad.slope.copyFromFloats(cd, h);
  41526. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41527. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41528. }
  41529. }
  41530. return this;
  41531. };
  41532. GroundMesh.prototype.serialize = function (serializationObject) {
  41533. _super.prototype.serialize.call(this, serializationObject);
  41534. serializationObject.subdivisionsX = this._subdivisionsX;
  41535. serializationObject.subdivisionsY = this._subdivisionsY;
  41536. serializationObject.minX = this._minX;
  41537. serializationObject.maxX = this._maxX;
  41538. serializationObject.minZ = this._minZ;
  41539. serializationObject.maxZ = this._maxZ;
  41540. serializationObject.width = this._width;
  41541. serializationObject.height = this._height;
  41542. };
  41543. GroundMesh.Parse = function (parsedMesh, scene) {
  41544. var result = new GroundMesh(parsedMesh.name, scene);
  41545. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41546. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41547. result._minX = parsedMesh.minX;
  41548. result._maxX = parsedMesh.maxX;
  41549. result._minZ = parsedMesh.minZ;
  41550. result._maxZ = parsedMesh.maxZ;
  41551. result._width = parsedMesh.width;
  41552. result._height = parsedMesh.height;
  41553. return result;
  41554. };
  41555. return GroundMesh;
  41556. }(BABYLON.Mesh));
  41557. BABYLON.GroundMesh = GroundMesh;
  41558. })(BABYLON || (BABYLON = {}));
  41559. //# sourceMappingURL=babylon.groundMesh.js.map
  41560. var BABYLON;
  41561. (function (BABYLON) {
  41562. /**
  41563. * Creates an instance based on a source mesh.
  41564. */
  41565. var InstancedMesh = (function (_super) {
  41566. __extends(InstancedMesh, _super);
  41567. function InstancedMesh(name, source) {
  41568. var _this = _super.call(this, name, source.getScene()) || this;
  41569. source.instances.push(_this);
  41570. _this._sourceMesh = source;
  41571. _this.position.copyFrom(source.position);
  41572. _this.rotation.copyFrom(source.rotation);
  41573. _this.scaling.copyFrom(source.scaling);
  41574. if (source.rotationQuaternion) {
  41575. _this.rotationQuaternion = source.rotationQuaternion.clone();
  41576. }
  41577. _this.infiniteDistance = source.infiniteDistance;
  41578. _this.setPivotMatrix(source.getPivotMatrix());
  41579. _this.refreshBoundingInfo();
  41580. _this._syncSubMeshes();
  41581. return _this;
  41582. }
  41583. /**
  41584. * Returns the string "InstancedMesh".
  41585. */
  41586. InstancedMesh.prototype.getClassName = function () {
  41587. return "InstancedMesh";
  41588. };
  41589. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  41590. // Methods
  41591. get: function () {
  41592. return this._sourceMesh.receiveShadows;
  41593. },
  41594. enumerable: true,
  41595. configurable: true
  41596. });
  41597. Object.defineProperty(InstancedMesh.prototype, "material", {
  41598. get: function () {
  41599. return this._sourceMesh.material;
  41600. },
  41601. enumerable: true,
  41602. configurable: true
  41603. });
  41604. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  41605. get: function () {
  41606. return this._sourceMesh.visibility;
  41607. },
  41608. enumerable: true,
  41609. configurable: true
  41610. });
  41611. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  41612. get: function () {
  41613. return this._sourceMesh.skeleton;
  41614. },
  41615. enumerable: true,
  41616. configurable: true
  41617. });
  41618. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  41619. get: function () {
  41620. return this._sourceMesh.renderingGroupId;
  41621. },
  41622. enumerable: true,
  41623. configurable: true
  41624. });
  41625. /**
  41626. * Returns the total number of vertices (integer).
  41627. */
  41628. InstancedMesh.prototype.getTotalVertices = function () {
  41629. return this._sourceMesh.getTotalVertices();
  41630. };
  41631. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  41632. get: function () {
  41633. return this._sourceMesh;
  41634. },
  41635. enumerable: true,
  41636. configurable: true
  41637. });
  41638. /**
  41639. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  41640. */
  41641. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  41642. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  41643. };
  41644. /**
  41645. * Sets the vertex data of the mesh geometry for the requested `kind`.
  41646. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  41647. * The `data` are either a numeric array either a Float32Array.
  41648. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  41649. * 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).
  41650. * Note that a new underlying VertexBuffer object is created each call.
  41651. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  41652. *
  41653. * Possible `kind` values :
  41654. * - BABYLON.VertexBuffer.PositionKind
  41655. * - BABYLON.VertexBuffer.UVKind
  41656. * - BABYLON.VertexBuffer.UV2Kind
  41657. * - BABYLON.VertexBuffer.UV3Kind
  41658. * - BABYLON.VertexBuffer.UV4Kind
  41659. * - BABYLON.VertexBuffer.UV5Kind
  41660. * - BABYLON.VertexBuffer.UV6Kind
  41661. * - BABYLON.VertexBuffer.ColorKind
  41662. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41663. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41664. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41665. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41666. *
  41667. * Returns the Mesh.
  41668. */
  41669. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41670. if (this.sourceMesh) {
  41671. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  41672. }
  41673. return this.sourceMesh;
  41674. };
  41675. /**
  41676. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  41677. * If the mesh has no geometry, it is simply returned as it is.
  41678. * The `data` are either a numeric array either a Float32Array.
  41679. * No new underlying VertexBuffer object is created.
  41680. * 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.
  41681. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  41682. *
  41683. * Possible `kind` values :
  41684. * - BABYLON.VertexBuffer.PositionKind
  41685. * - BABYLON.VertexBuffer.UVKind
  41686. * - BABYLON.VertexBuffer.UV2Kind
  41687. * - BABYLON.VertexBuffer.UV3Kind
  41688. * - BABYLON.VertexBuffer.UV4Kind
  41689. * - BABYLON.VertexBuffer.UV5Kind
  41690. * - BABYLON.VertexBuffer.UV6Kind
  41691. * - BABYLON.VertexBuffer.ColorKind
  41692. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41693. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41694. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41695. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41696. *
  41697. * Returns the Mesh.
  41698. */
  41699. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  41700. if (this.sourceMesh) {
  41701. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  41702. }
  41703. return this.sourceMesh;
  41704. };
  41705. /**
  41706. * Sets the mesh indices.
  41707. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  41708. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  41709. * This method creates a new index buffer each call.
  41710. * Returns the Mesh.
  41711. */
  41712. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  41713. if (this.sourceMesh) {
  41714. this.sourceMesh.setIndices(indices, totalVertices);
  41715. }
  41716. return this.sourceMesh;
  41717. };
  41718. /**
  41719. * Boolean : True if the mesh owns the requested kind of data.
  41720. */
  41721. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  41722. return this._sourceMesh.isVerticesDataPresent(kind);
  41723. };
  41724. /**
  41725. * Returns an array of indices (IndicesArray).
  41726. */
  41727. InstancedMesh.prototype.getIndices = function () {
  41728. return this._sourceMesh.getIndices();
  41729. };
  41730. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  41731. get: function () {
  41732. return this._sourceMesh._positions;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. /**
  41738. * Sets a new updated BoundingInfo to the mesh.
  41739. * Returns the mesh.
  41740. */
  41741. InstancedMesh.prototype.refreshBoundingInfo = function () {
  41742. var meshBB = this._sourceMesh.getBoundingInfo();
  41743. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  41744. this._updateBoundingInfo();
  41745. return this;
  41746. };
  41747. InstancedMesh.prototype._preActivate = function () {
  41748. if (this._currentLOD) {
  41749. this._currentLOD._preActivate();
  41750. }
  41751. return this;
  41752. };
  41753. InstancedMesh.prototype._activate = function (renderId) {
  41754. if (this._currentLOD) {
  41755. this._currentLOD._registerInstanceForRenderId(this, renderId);
  41756. }
  41757. return this;
  41758. };
  41759. /**
  41760. * Returns the current associated LOD AbstractMesh.
  41761. */
  41762. InstancedMesh.prototype.getLOD = function (camera) {
  41763. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  41764. if (this._currentLOD === this.sourceMesh) {
  41765. return this;
  41766. }
  41767. return this._currentLOD;
  41768. };
  41769. InstancedMesh.prototype._syncSubMeshes = function () {
  41770. this.releaseSubMeshes();
  41771. if (this._sourceMesh.subMeshes) {
  41772. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  41773. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  41774. }
  41775. }
  41776. return this;
  41777. };
  41778. InstancedMesh.prototype._generatePointsArray = function () {
  41779. return this._sourceMesh._generatePointsArray();
  41780. };
  41781. /**
  41782. * Creates a new InstancedMesh from the current mesh.
  41783. * - name (string) : the cloned mesh name
  41784. * - newParent (optional Node) : the optional Node to parent the clone to.
  41785. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  41786. *
  41787. * Returns the clone.
  41788. */
  41789. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41790. var result = this._sourceMesh.createInstance(name);
  41791. // Deep copy
  41792. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  41793. // Bounding info
  41794. this.refreshBoundingInfo();
  41795. // Parent
  41796. if (newParent) {
  41797. result.parent = newParent;
  41798. }
  41799. if (!doNotCloneChildren) {
  41800. // Children
  41801. for (var index = 0; index < this.getScene().meshes.length; index++) {
  41802. var mesh = this.getScene().meshes[index];
  41803. if (mesh.parent === this) {
  41804. mesh.clone(mesh.name, result);
  41805. }
  41806. }
  41807. }
  41808. result.computeWorldMatrix(true);
  41809. return result;
  41810. };
  41811. /**
  41812. * Disposes the InstancedMesh.
  41813. * Returns nothing.
  41814. */
  41815. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  41816. // Remove from mesh
  41817. var index = this._sourceMesh.instances.indexOf(this);
  41818. this._sourceMesh.instances.splice(index, 1);
  41819. _super.prototype.dispose.call(this, doNotRecurse);
  41820. };
  41821. return InstancedMesh;
  41822. }(BABYLON.AbstractMesh));
  41823. BABYLON.InstancedMesh = InstancedMesh;
  41824. })(BABYLON || (BABYLON = {}));
  41825. //# sourceMappingURL=babylon.instancedMesh.js.map
  41826. /// <reference path="babylon.mesh.ts" />
  41827. var BABYLON;
  41828. (function (BABYLON) {
  41829. var LinesMesh = (function (_super) {
  41830. __extends(LinesMesh, _super);
  41831. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  41832. if (parent === void 0) { parent = null; }
  41833. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41834. _this.useVertexColor = useVertexColor;
  41835. _this.color = new BABYLON.Color3(1, 1, 1);
  41836. _this.alpha = 1;
  41837. if (source) {
  41838. _this.color = source.color.clone();
  41839. _this.alpha = source.alpha;
  41840. _this.useVertexColor = source.useVertexColor;
  41841. }
  41842. _this._intersectionThreshold = 0.1;
  41843. var options = {
  41844. attributes: [BABYLON.VertexBuffer.PositionKind],
  41845. uniforms: ["world", "viewProjection"],
  41846. needAlphaBlending: false,
  41847. };
  41848. if (!useVertexColor) {
  41849. options.uniforms.push("color");
  41850. options.needAlphaBlending = true;
  41851. }
  41852. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  41853. return _this;
  41854. }
  41855. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41856. /**
  41857. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41858. * This margin is expressed in world space coordinates, so its value may vary.
  41859. * Default value is 0.1
  41860. * @returns the intersection Threshold value.
  41861. */
  41862. get: function () {
  41863. return this._intersectionThreshold;
  41864. },
  41865. /**
  41866. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41867. * This margin is expressed in world space coordinates, so its value may vary.
  41868. * @param value the new threshold to apply
  41869. */
  41870. set: function (value) {
  41871. if (this._intersectionThreshold === value) {
  41872. return;
  41873. }
  41874. this._intersectionThreshold = value;
  41875. if (this.geometry) {
  41876. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  41877. }
  41878. },
  41879. enumerable: true,
  41880. configurable: true
  41881. });
  41882. /**
  41883. * Returns the string "LineMesh"
  41884. */
  41885. LinesMesh.prototype.getClassName = function () {
  41886. return "LinesMesh";
  41887. };
  41888. Object.defineProperty(LinesMesh.prototype, "material", {
  41889. get: function () {
  41890. return this._colorShader;
  41891. },
  41892. enumerable: true,
  41893. configurable: true
  41894. });
  41895. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  41896. get: function () {
  41897. return false;
  41898. },
  41899. enumerable: true,
  41900. configurable: true
  41901. });
  41902. LinesMesh.prototype.createInstance = function (name) {
  41903. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  41904. return null;
  41905. };
  41906. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  41907. // VBOs
  41908. this._geometry._bind(this._colorShader.getEffect());
  41909. // Color
  41910. if (!this.useVertexColor) {
  41911. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  41912. }
  41913. return this;
  41914. };
  41915. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  41916. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  41917. return this;
  41918. }
  41919. var engine = this.getScene().getEngine();
  41920. // Draw order
  41921. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  41922. return this;
  41923. };
  41924. LinesMesh.prototype.dispose = function (doNotRecurse) {
  41925. this._colorShader.dispose();
  41926. _super.prototype.dispose.call(this, doNotRecurse);
  41927. };
  41928. /**
  41929. * Returns a new LineMesh object cloned from the current one.
  41930. */
  41931. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41932. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  41933. };
  41934. return LinesMesh;
  41935. }(BABYLON.Mesh));
  41936. BABYLON.LinesMesh = LinesMesh;
  41937. })(BABYLON || (BABYLON = {}));
  41938. //# sourceMappingURL=babylon.linesMesh.js.map
  41939. var BABYLON;
  41940. (function (BABYLON) {
  41941. var ShaderMaterial = (function (_super) {
  41942. __extends(ShaderMaterial, _super);
  41943. function ShaderMaterial(name, scene, shaderPath, options) {
  41944. var _this = _super.call(this, name, scene) || this;
  41945. _this._textures = {};
  41946. _this._textureArrays = {};
  41947. _this._floats = {};
  41948. _this._floatsArrays = {};
  41949. _this._colors3 = {};
  41950. _this._colors3Arrays = {};
  41951. _this._colors4 = {};
  41952. _this._vectors2 = {};
  41953. _this._vectors3 = {};
  41954. _this._vectors4 = {};
  41955. _this._matrices = {};
  41956. _this._matrices3x3 = {};
  41957. _this._matrices2x2 = {};
  41958. _this._vectors3Arrays = {};
  41959. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41960. _this._shaderPath = shaderPath;
  41961. options.needAlphaBlending = options.needAlphaBlending || false;
  41962. options.needAlphaTesting = options.needAlphaTesting || false;
  41963. options.attributes = options.attributes || ["position", "normal", "uv"];
  41964. options.uniforms = options.uniforms || ["worldViewProjection"];
  41965. options.uniformBuffers = options.uniformBuffers || [];
  41966. options.samplers = options.samplers || [];
  41967. options.defines = options.defines || [];
  41968. _this._options = options;
  41969. return _this;
  41970. }
  41971. ShaderMaterial.prototype.getClassName = function () {
  41972. return "ShaderMaterial";
  41973. };
  41974. ShaderMaterial.prototype.needAlphaBlending = function () {
  41975. return this._options.needAlphaBlending;
  41976. };
  41977. ShaderMaterial.prototype.needAlphaTesting = function () {
  41978. return this._options.needAlphaTesting;
  41979. };
  41980. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41981. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41982. this._options.uniforms.push(uniformName);
  41983. }
  41984. };
  41985. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41986. if (this._options.samplers.indexOf(name) === -1) {
  41987. this._options.samplers.push(name);
  41988. }
  41989. this._textures[name] = texture;
  41990. return this;
  41991. };
  41992. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41993. if (this._options.samplers.indexOf(name) === -1) {
  41994. this._options.samplers.push(name);
  41995. }
  41996. this._checkUniform(name);
  41997. this._textureArrays[name] = textures;
  41998. return this;
  41999. };
  42000. ShaderMaterial.prototype.setFloat = function (name, value) {
  42001. this._checkUniform(name);
  42002. this._floats[name] = value;
  42003. return this;
  42004. };
  42005. ShaderMaterial.prototype.setFloats = function (name, value) {
  42006. this._checkUniform(name);
  42007. this._floatsArrays[name] = value;
  42008. return this;
  42009. };
  42010. ShaderMaterial.prototype.setColor3 = function (name, value) {
  42011. this._checkUniform(name);
  42012. this._colors3[name] = value;
  42013. return this;
  42014. };
  42015. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  42016. this._checkUniform(name);
  42017. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  42018. color.toArray(arr, arr.length);
  42019. return arr;
  42020. }, []);
  42021. return this;
  42022. };
  42023. ShaderMaterial.prototype.setColor4 = function (name, value) {
  42024. this._checkUniform(name);
  42025. this._colors4[name] = value;
  42026. return this;
  42027. };
  42028. ShaderMaterial.prototype.setVector2 = function (name, value) {
  42029. this._checkUniform(name);
  42030. this._vectors2[name] = value;
  42031. return this;
  42032. };
  42033. ShaderMaterial.prototype.setVector3 = function (name, value) {
  42034. this._checkUniform(name);
  42035. this._vectors3[name] = value;
  42036. return this;
  42037. };
  42038. ShaderMaterial.prototype.setVector4 = function (name, value) {
  42039. this._checkUniform(name);
  42040. this._vectors4[name] = value;
  42041. return this;
  42042. };
  42043. ShaderMaterial.prototype.setMatrix = function (name, value) {
  42044. this._checkUniform(name);
  42045. this._matrices[name] = value;
  42046. return this;
  42047. };
  42048. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  42049. this._checkUniform(name);
  42050. this._matrices3x3[name] = value;
  42051. return this;
  42052. };
  42053. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  42054. this._checkUniform(name);
  42055. this._matrices2x2[name] = value;
  42056. return this;
  42057. };
  42058. ShaderMaterial.prototype.setArray3 = function (name, value) {
  42059. this._checkUniform(name);
  42060. this._vectors3Arrays[name] = value;
  42061. return this;
  42062. };
  42063. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  42064. if (!mesh) {
  42065. return true;
  42066. }
  42067. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  42068. return false;
  42069. }
  42070. return false;
  42071. };
  42072. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  42073. var scene = this.getScene();
  42074. var engine = scene.getEngine();
  42075. if (!this.checkReadyOnEveryCall) {
  42076. if (this._renderId === scene.getRenderId()) {
  42077. if (this._checkCache(scene, mesh, useInstances)) {
  42078. return true;
  42079. }
  42080. }
  42081. }
  42082. // Instances
  42083. var defines = [];
  42084. var attribs = [];
  42085. var fallbacks = new BABYLON.EffectFallbacks();
  42086. if (useInstances) {
  42087. defines.push("#define INSTANCES");
  42088. }
  42089. for (var index = 0; index < this._options.defines.length; index++) {
  42090. defines.push(this._options.defines[index]);
  42091. }
  42092. for (var index = 0; index < this._options.attributes.length; index++) {
  42093. attribs.push(this._options.attributes[index]);
  42094. }
  42095. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42096. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42097. defines.push("#define VERTEXCOLOR");
  42098. }
  42099. // Bones
  42100. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  42101. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42102. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42103. if (mesh.numBoneInfluencers > 4) {
  42104. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42105. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42106. }
  42107. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42108. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42109. fallbacks.addCPUSkinningFallback(0, mesh);
  42110. if (this._options.uniforms.indexOf("mBones") === -1) {
  42111. this._options.uniforms.push("mBones");
  42112. }
  42113. }
  42114. else {
  42115. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42116. }
  42117. // Textures
  42118. for (var name in this._textures) {
  42119. if (!this._textures[name].isReady()) {
  42120. return false;
  42121. }
  42122. }
  42123. // Alpha test
  42124. if (engine.getAlphaTesting()) {
  42125. defines.push("#define ALPHATEST");
  42126. }
  42127. var previousEffect = this._effect;
  42128. var join = defines.join("\n");
  42129. this._effect = engine.createEffect(this._shaderPath, {
  42130. attributes: attribs,
  42131. uniformsNames: this._options.uniforms,
  42132. uniformBuffersNames: this._options.uniformBuffers,
  42133. samplers: this._options.samplers,
  42134. defines: join,
  42135. fallbacks: fallbacks,
  42136. onCompiled: this.onCompiled,
  42137. onError: this.onError
  42138. }, engine);
  42139. if (!this._effect.isReady()) {
  42140. return false;
  42141. }
  42142. if (previousEffect !== this._effect) {
  42143. scene.resetCachedMaterial();
  42144. }
  42145. this._renderId = scene.getRenderId();
  42146. return true;
  42147. };
  42148. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42149. var scene = this.getScene();
  42150. if (this._options.uniforms.indexOf("world") !== -1) {
  42151. this._effect.setMatrix("world", world);
  42152. }
  42153. if (this._options.uniforms.indexOf("worldView") !== -1) {
  42154. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  42155. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  42156. }
  42157. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  42158. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  42159. }
  42160. };
  42161. ShaderMaterial.prototype.bind = function (world, mesh) {
  42162. // Std values
  42163. this.bindOnlyWorldMatrix(world);
  42164. if (this.getScene().getCachedMaterial() !== this) {
  42165. if (this._options.uniforms.indexOf("view") !== -1) {
  42166. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  42167. }
  42168. if (this._options.uniforms.indexOf("projection") !== -1) {
  42169. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  42170. }
  42171. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  42172. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  42173. }
  42174. // Bones
  42175. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  42176. var name;
  42177. // Texture
  42178. for (name in this._textures) {
  42179. this._effect.setTexture(name, this._textures[name]);
  42180. }
  42181. // Texture arrays
  42182. for (name in this._textureArrays) {
  42183. this._effect.setTextureArray(name, this._textureArrays[name]);
  42184. }
  42185. // Float
  42186. for (name in this._floats) {
  42187. this._effect.setFloat(name, this._floats[name]);
  42188. }
  42189. // Float s
  42190. for (name in this._floatsArrays) {
  42191. this._effect.setArray(name, this._floatsArrays[name]);
  42192. }
  42193. // Color3
  42194. for (name in this._colors3) {
  42195. this._effect.setColor3(name, this._colors3[name]);
  42196. }
  42197. for (name in this._colors3Arrays) {
  42198. this._effect.setArray3(name, this._colors3Arrays[name]);
  42199. }
  42200. // Color4
  42201. for (name in this._colors4) {
  42202. var color = this._colors4[name];
  42203. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  42204. }
  42205. // Vector2
  42206. for (name in this._vectors2) {
  42207. this._effect.setVector2(name, this._vectors2[name]);
  42208. }
  42209. // Vector3
  42210. for (name in this._vectors3) {
  42211. this._effect.setVector3(name, this._vectors3[name]);
  42212. }
  42213. // Vector4
  42214. for (name in this._vectors4) {
  42215. this._effect.setVector4(name, this._vectors4[name]);
  42216. }
  42217. // Matrix
  42218. for (name in this._matrices) {
  42219. this._effect.setMatrix(name, this._matrices[name]);
  42220. }
  42221. // Matrix 3x3
  42222. for (name in this._matrices3x3) {
  42223. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  42224. }
  42225. // Matrix 2x2
  42226. for (name in this._matrices2x2) {
  42227. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  42228. }
  42229. // Vector3Array
  42230. for (name in this._vectors3Arrays) {
  42231. this._effect.setArray3(name, this._vectors3Arrays[name]);
  42232. }
  42233. }
  42234. this._afterBind(mesh);
  42235. };
  42236. ShaderMaterial.prototype.getActiveTextures = function () {
  42237. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42238. for (var name in this._textures) {
  42239. activeTextures.push(this._textures[name]);
  42240. }
  42241. for (var name in this._textureArrays) {
  42242. var array = this._textureArrays[name];
  42243. for (var index = 0; index < array.length; index++) {
  42244. activeTextures.push(array[index]);
  42245. }
  42246. }
  42247. return activeTextures;
  42248. };
  42249. ShaderMaterial.prototype.hasTexture = function (texture) {
  42250. if (_super.prototype.hasTexture.call(this, texture)) {
  42251. return true;
  42252. }
  42253. for (var name in this._textures) {
  42254. if (this._textures[name] === texture) {
  42255. return true;
  42256. }
  42257. }
  42258. for (var name in this._textureArrays) {
  42259. var array = this._textureArrays[name];
  42260. for (var index = 0; index < array.length; index++) {
  42261. if (array[index] === texture) {
  42262. return true;
  42263. }
  42264. }
  42265. }
  42266. return false;
  42267. };
  42268. ShaderMaterial.prototype.clone = function (name) {
  42269. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  42270. return newShaderMaterial;
  42271. };
  42272. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42273. if (forceDisposeTextures) {
  42274. var name;
  42275. for (name in this._textures) {
  42276. this._textures[name].dispose();
  42277. }
  42278. for (name in this._textureArrays) {
  42279. var array = this._textureArrays[name];
  42280. for (var index = 0; index < array.length; index++) {
  42281. array[index].dispose();
  42282. }
  42283. }
  42284. }
  42285. this._textures = {};
  42286. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42287. };
  42288. ShaderMaterial.prototype.serialize = function () {
  42289. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42290. serializationObject.customType = "BABYLON.ShaderMaterial";
  42291. serializationObject.options = this._options;
  42292. serializationObject.shaderPath = this._shaderPath;
  42293. var name;
  42294. // Texture
  42295. serializationObject.textures = {};
  42296. for (name in this._textures) {
  42297. serializationObject.textures[name] = this._textures[name].serialize();
  42298. }
  42299. // Texture arrays
  42300. serializationObject.textureArrays = {};
  42301. for (name in this._textureArrays) {
  42302. serializationObject.textureArrays[name] = [];
  42303. var array = this._textureArrays[name];
  42304. for (var index = 0; index < array.length; index++) {
  42305. serializationObject.textureArrays[name].push(array[index].serialize());
  42306. }
  42307. }
  42308. // Float
  42309. serializationObject.floats = {};
  42310. for (name in this._floats) {
  42311. serializationObject.floats[name] = this._floats[name];
  42312. }
  42313. // Float s
  42314. serializationObject.floatArrays = {};
  42315. for (name in this._floatsArrays) {
  42316. serializationObject.floatArrays[name] = this._floatsArrays[name];
  42317. }
  42318. // Color3
  42319. serializationObject.colors3 = {};
  42320. for (name in this._colors3) {
  42321. serializationObject.colors3[name] = this._colors3[name].asArray();
  42322. }
  42323. // Color3 array
  42324. serializationObject.colors3Arrays = {};
  42325. for (name in this._colors3Arrays) {
  42326. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  42327. }
  42328. // Color4
  42329. serializationObject.colors4 = {};
  42330. for (name in this._colors4) {
  42331. serializationObject.colors4[name] = this._colors4[name].asArray();
  42332. }
  42333. // Vector2
  42334. serializationObject.vectors2 = {};
  42335. for (name in this._vectors2) {
  42336. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  42337. }
  42338. // Vector3
  42339. serializationObject.vectors3 = {};
  42340. for (name in this._vectors3) {
  42341. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  42342. }
  42343. // Vector4
  42344. serializationObject.vectors4 = {};
  42345. for (name in this._vectors4) {
  42346. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  42347. }
  42348. // Matrix
  42349. serializationObject.matrices = {};
  42350. for (name in this._matrices) {
  42351. serializationObject.matrices[name] = this._matrices[name].asArray();
  42352. }
  42353. // Matrix 3x3
  42354. serializationObject.matrices3x3 = {};
  42355. for (name in this._matrices3x3) {
  42356. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  42357. }
  42358. // Matrix 2x2
  42359. serializationObject.matrices2x2 = {};
  42360. for (name in this._matrices2x2) {
  42361. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  42362. }
  42363. // Vector3Array
  42364. serializationObject.vectors3Arrays = {};
  42365. for (name in this._vectors3Arrays) {
  42366. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  42367. }
  42368. return serializationObject;
  42369. };
  42370. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  42371. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  42372. var name;
  42373. // Texture
  42374. for (name in source.textures) {
  42375. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  42376. }
  42377. // Texture arrays
  42378. for (name in source.textureArrays) {
  42379. var array = source.textureArrays[name];
  42380. var textureArray = new Array();
  42381. for (var index = 0; index < array.length; index++) {
  42382. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  42383. }
  42384. material.setTextureArray(name, textureArray);
  42385. }
  42386. // Float
  42387. for (name in source.floats) {
  42388. material.setFloat(name, source.floats[name]);
  42389. }
  42390. // Float s
  42391. for (name in source.floatsArrays) {
  42392. material.setFloats(name, source.floatsArrays[name]);
  42393. }
  42394. // Color3
  42395. for (name in source.colors3) {
  42396. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  42397. }
  42398. // Color3 arrays
  42399. for (name in source.colors3Arrays) {
  42400. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  42401. if (i % 3 === 0) {
  42402. arr.push([num]);
  42403. }
  42404. else {
  42405. arr[arr.length - 1].push(num);
  42406. }
  42407. return arr;
  42408. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  42409. material.setColor3Array(name, colors);
  42410. }
  42411. // Color4
  42412. for (name in source.colors4) {
  42413. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  42414. }
  42415. // Vector2
  42416. for (name in source.vectors2) {
  42417. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  42418. }
  42419. // Vector3
  42420. for (name in source.vectors3) {
  42421. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  42422. }
  42423. // Vector4
  42424. for (name in source.vectors4) {
  42425. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  42426. }
  42427. // Matrix
  42428. for (name in source.matrices) {
  42429. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  42430. }
  42431. // Matrix 3x3
  42432. for (name in source.matrices3x3) {
  42433. material.setMatrix3x3(name, source.matrices3x3[name]);
  42434. }
  42435. // Matrix 2x2
  42436. for (name in source.matrices2x2) {
  42437. material.setMatrix2x2(name, source.matrices2x2[name]);
  42438. }
  42439. // Vector3Array
  42440. for (name in source.vectors3Arrays) {
  42441. material.setArray3(name, source.vectors3Arrays[name]);
  42442. }
  42443. return material;
  42444. };
  42445. return ShaderMaterial;
  42446. }(BABYLON.Material));
  42447. BABYLON.ShaderMaterial = ShaderMaterial;
  42448. })(BABYLON || (BABYLON = {}));
  42449. //# sourceMappingURL=babylon.shaderMaterial.js.map
  42450. var BABYLON;
  42451. (function (BABYLON) {
  42452. var MeshBuilder = (function () {
  42453. function MeshBuilder() {
  42454. }
  42455. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  42456. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  42457. return BABYLON.Mesh.DOUBLESIDE;
  42458. }
  42459. if (orientation === undefined || orientation === null) {
  42460. return BABYLON.Mesh.FRONTSIDE;
  42461. }
  42462. return orientation;
  42463. };
  42464. /**
  42465. * Creates a box mesh.
  42466. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  42467. * The parameter `size` sets the size (float) of each box side (default 1).
  42468. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  42469. * 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).
  42470. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  42471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42472. * 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).
  42473. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42474. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42475. */
  42476. MeshBuilder.CreateBox = function (name, options, scene) {
  42477. var box = new BABYLON.Mesh(name, scene);
  42478. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42479. box.sideOrientation = options.sideOrientation;
  42480. var vertexData = BABYLON.VertexData.CreateBox(options);
  42481. vertexData.applyToMesh(box, options.updatable);
  42482. return box;
  42483. };
  42484. /**
  42485. * Creates a sphere mesh.
  42486. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  42487. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  42488. * 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`).
  42489. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  42490. * 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
  42491. * 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).
  42492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42493. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42496. */
  42497. MeshBuilder.CreateSphere = function (name, options, scene) {
  42498. var sphere = new BABYLON.Mesh(name, scene);
  42499. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42500. sphere.sideOrientation = options.sideOrientation;
  42501. var vertexData = BABYLON.VertexData.CreateSphere(options);
  42502. vertexData.applyToMesh(sphere, options.updatable);
  42503. return sphere;
  42504. };
  42505. /**
  42506. * Creates a plane polygonal mesh. By default, this is a disc.
  42507. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  42508. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  42509. * 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.
  42510. * 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
  42511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42512. * 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).
  42513. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42515. */
  42516. MeshBuilder.CreateDisc = function (name, options, scene) {
  42517. var disc = new BABYLON.Mesh(name, scene);
  42518. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42519. disc.sideOrientation = options.sideOrientation;
  42520. var vertexData = BABYLON.VertexData.CreateDisc(options);
  42521. vertexData.applyToMesh(disc, options.updatable);
  42522. return disc;
  42523. };
  42524. /**
  42525. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  42526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  42527. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  42528. * 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`).
  42529. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  42530. * 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.
  42531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42532. * 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).
  42533. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42535. */
  42536. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  42537. var sphere = new BABYLON.Mesh(name, scene);
  42538. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42539. sphere.sideOrientation = options.sideOrientation;
  42540. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  42541. vertexData.applyToMesh(sphere, options.updatable);
  42542. return sphere;
  42543. };
  42544. ;
  42545. /**
  42546. * Creates a ribbon mesh.
  42547. * 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.
  42548. *
  42549. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  42550. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  42551. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  42552. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  42553. * 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.
  42554. * 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.
  42555. * 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
  42556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42557. * 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).
  42558. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42559. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42560. * 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.
  42561. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  42562. * 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
  42563. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  42564. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  42565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42566. */
  42567. MeshBuilder.CreateRibbon = function (name, options, scene) {
  42568. var pathArray = options.pathArray;
  42569. var closeArray = options.closeArray;
  42570. var closePath = options.closePath;
  42571. var offset = options.offset;
  42572. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42573. var instance = options.instance;
  42574. var updatable = options.updatable;
  42575. if (instance) {
  42576. // positionFunction : ribbon case
  42577. // only pathArray and sideOrientation parameters are taken into account for positions update
  42578. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  42579. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  42580. var positionFunction = function (positions) {
  42581. var minlg = pathArray[0].length;
  42582. var i = 0;
  42583. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  42584. for (var si = 1; si <= ns; si++) {
  42585. for (var p = 0; p < pathArray.length; p++) {
  42586. var path = pathArray[p];
  42587. var l = path.length;
  42588. minlg = (minlg < l) ? minlg : l;
  42589. var j = 0;
  42590. while (j < minlg) {
  42591. positions[i] = path[j].x;
  42592. positions[i + 1] = path[j].y;
  42593. positions[i + 2] = path[j].z;
  42594. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  42595. BABYLON.Tmp.Vector3[0].x = path[j].x;
  42596. }
  42597. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  42598. BABYLON.Tmp.Vector3[1].x = path[j].x;
  42599. }
  42600. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  42601. BABYLON.Tmp.Vector3[0].y = path[j].y;
  42602. }
  42603. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  42604. BABYLON.Tmp.Vector3[1].y = path[j].y;
  42605. }
  42606. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  42607. BABYLON.Tmp.Vector3[0].z = path[j].z;
  42608. }
  42609. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  42610. BABYLON.Tmp.Vector3[1].z = path[j].z;
  42611. }
  42612. j++;
  42613. i += 3;
  42614. }
  42615. if (instance._closePath) {
  42616. positions[i] = path[0].x;
  42617. positions[i + 1] = path[0].y;
  42618. positions[i + 2] = path[0].z;
  42619. i += 3;
  42620. }
  42621. }
  42622. }
  42623. };
  42624. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42625. positionFunction(positions);
  42626. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  42627. instance._boundingInfo.update(instance._worldMatrix);
  42628. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  42629. if (options.colors) {
  42630. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42631. for (var c = 0; c < options.colors.length; c++) {
  42632. colors[c * 4] = options.colors[c].r;
  42633. colors[c * 4 + 1] = options.colors[c].g;
  42634. colors[c * 4 + 2] = options.colors[c].b;
  42635. colors[c * 4 + 3] = options.colors[c].a;
  42636. }
  42637. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  42638. }
  42639. if (options.uvs) {
  42640. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42641. for (var i = 0; i < options.uvs.length; i++) {
  42642. uvs[i * 2] = options.uvs[i].x;
  42643. uvs[i * 2 + 1] = options.uvs[i].y;
  42644. }
  42645. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  42646. }
  42647. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  42648. var indices = instance.getIndices();
  42649. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42650. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  42651. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  42652. if (instance._closePath) {
  42653. var indexFirst = 0;
  42654. var indexLast = 0;
  42655. for (var p = 0; p < pathArray.length; p++) {
  42656. indexFirst = instance._idx[p] * 3;
  42657. if (p + 1 < pathArray.length) {
  42658. indexLast = (instance._idx[p + 1] - 1) * 3;
  42659. }
  42660. else {
  42661. indexLast = normals.length - 3;
  42662. }
  42663. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  42664. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  42665. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  42666. normals[indexLast] = normals[indexFirst];
  42667. normals[indexLast + 1] = normals[indexFirst + 1];
  42668. normals[indexLast + 2] = normals[indexFirst + 2];
  42669. }
  42670. }
  42671. if (!(instance.areNormalsFrozen)) {
  42672. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  42673. }
  42674. }
  42675. return instance;
  42676. }
  42677. else {
  42678. var ribbon = new BABYLON.Mesh(name, scene);
  42679. ribbon.sideOrientation = sideOrientation;
  42680. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  42681. if (closePath) {
  42682. ribbon._idx = vertexData._idx;
  42683. }
  42684. ribbon._closePath = closePath;
  42685. ribbon._closeArray = closeArray;
  42686. vertexData.applyToMesh(ribbon, updatable);
  42687. return ribbon;
  42688. }
  42689. };
  42690. /**
  42691. * Creates a cylinder or a cone mesh.
  42692. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  42693. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  42694. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  42695. * 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.
  42696. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  42697. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  42698. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  42699. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  42700. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  42701. * 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).
  42702. * 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
  42703. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  42704. * 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
  42705. * 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.
  42706. * If `enclose` is false, a ring surface is one element.
  42707. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  42708. * 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
  42709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42710. * 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).
  42711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42713. */
  42714. MeshBuilder.CreateCylinder = function (name, options, scene) {
  42715. var cylinder = new BABYLON.Mesh(name, scene);
  42716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42717. cylinder.sideOrientation = options.sideOrientation;
  42718. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  42719. vertexData.applyToMesh(cylinder, options.updatable);
  42720. return cylinder;
  42721. };
  42722. /**
  42723. * Creates a torus mesh.
  42724. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  42725. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  42726. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  42727. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  42728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42729. * 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).
  42730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42732. */
  42733. MeshBuilder.CreateTorus = function (name, options, scene) {
  42734. var torus = new BABYLON.Mesh(name, scene);
  42735. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42736. torus.sideOrientation = options.sideOrientation;
  42737. var vertexData = BABYLON.VertexData.CreateTorus(options);
  42738. vertexData.applyToMesh(torus, options.updatable);
  42739. return torus;
  42740. };
  42741. /**
  42742. * Creates a torus knot mesh.
  42743. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  42744. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  42745. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  42746. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  42747. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  42748. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42749. * 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).
  42750. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42752. */
  42753. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  42754. var torusKnot = new BABYLON.Mesh(name, scene);
  42755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42756. torusKnot.sideOrientation = options.sideOrientation;
  42757. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  42758. vertexData.applyToMesh(torusKnot, options.updatable);
  42759. return torusKnot;
  42760. };
  42761. /**
  42762. * Creates a line system mesh.
  42763. * A line system is a pool of many lines gathered in a single mesh.
  42764. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  42765. * 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.
  42766. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  42767. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  42768. * 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
  42769. * 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
  42770. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  42771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42772. */
  42773. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  42774. var instance = options.instance;
  42775. var lines = options.lines;
  42776. if (instance) {
  42777. var positionFunction = function (positions) {
  42778. var i = 0;
  42779. for (var l = 0; l < lines.length; l++) {
  42780. var points = lines[l];
  42781. for (var p = 0; p < points.length; p++) {
  42782. positions[i] = points[p].x;
  42783. positions[i + 1] = points[p].y;
  42784. positions[i + 2] = points[p].z;
  42785. i += 3;
  42786. }
  42787. }
  42788. };
  42789. instance.updateMeshPositions(positionFunction, false);
  42790. return instance;
  42791. }
  42792. // line system creation
  42793. var lineSystem = new BABYLON.LinesMesh(name, scene);
  42794. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  42795. vertexData.applyToMesh(lineSystem, options.updatable);
  42796. return lineSystem;
  42797. };
  42798. /**
  42799. * Creates a line mesh.
  42800. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  42801. * 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.
  42802. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  42803. * The parameter `points` is an array successive Vector3.
  42804. * 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
  42805. * When updating an instance, remember that only point positions can change, not the number of points.
  42806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42807. */
  42808. MeshBuilder.CreateLines = function (name, options, scene) {
  42809. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  42810. return lines;
  42811. };
  42812. /**
  42813. * Creates a dashed line mesh.
  42814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  42815. * 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.
  42816. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  42817. * The parameter `points` is an array successive Vector3.
  42818. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  42819. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  42820. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  42821. * 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
  42822. * When updating an instance, remember that only point positions can change, not the number of points.
  42823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42824. */
  42825. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  42826. var points = options.points;
  42827. var instance = options.instance;
  42828. var gapSize = options.gapSize;
  42829. var dashNb = options.dashNb;
  42830. var dashSize = options.dashSize;
  42831. if (instance) {
  42832. var positionFunction = function (positions) {
  42833. var curvect = BABYLON.Vector3.Zero();
  42834. var nbSeg = positions.length / 6;
  42835. var lg = 0;
  42836. var nb = 0;
  42837. var shft = 0;
  42838. var dashshft = 0;
  42839. var curshft = 0;
  42840. var p = 0;
  42841. var i = 0;
  42842. var j = 0;
  42843. for (i = 0; i < points.length - 1; i++) {
  42844. points[i + 1].subtractToRef(points[i], curvect);
  42845. lg += curvect.length();
  42846. }
  42847. shft = lg / nbSeg;
  42848. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  42849. for (i = 0; i < points.length - 1; i++) {
  42850. points[i + 1].subtractToRef(points[i], curvect);
  42851. nb = Math.floor(curvect.length() / shft);
  42852. curvect.normalize();
  42853. j = 0;
  42854. while (j < nb && p < positions.length) {
  42855. curshft = shft * j;
  42856. positions[p] = points[i].x + curshft * curvect.x;
  42857. positions[p + 1] = points[i].y + curshft * curvect.y;
  42858. positions[p + 2] = points[i].z + curshft * curvect.z;
  42859. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  42860. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  42861. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  42862. p += 6;
  42863. j++;
  42864. }
  42865. }
  42866. while (p < positions.length) {
  42867. positions[p] = points[i].x;
  42868. positions[p + 1] = points[i].y;
  42869. positions[p + 2] = points[i].z;
  42870. p += 3;
  42871. }
  42872. };
  42873. instance.updateMeshPositions(positionFunction, false);
  42874. return instance;
  42875. }
  42876. // dashed lines creation
  42877. var dashedLines = new BABYLON.LinesMesh(name, scene);
  42878. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  42879. vertexData.applyToMesh(dashedLines, options.updatable);
  42880. dashedLines.dashSize = dashSize;
  42881. dashedLines.gapSize = gapSize;
  42882. return dashedLines;
  42883. };
  42884. /**
  42885. * Creates an extruded shape mesh.
  42886. * 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.
  42887. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  42888. *
  42889. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  42890. * 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
  42891. * extruded along the Z axis.
  42892. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  42893. * 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.
  42894. * The parameter `scale` (float, default 1) is the value to scale the shape.
  42895. * 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
  42896. * 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
  42897. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  42898. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42899. * 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).
  42900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42901. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42903. */
  42904. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  42905. var path = options.path;
  42906. var shape = options.shape;
  42907. var scale = options.scale || 1;
  42908. var rotation = options.rotation || 0;
  42909. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  42910. var updatable = options.updatable;
  42911. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42912. var instance = options.instance;
  42913. var invertUV = options.invertUV || false;
  42914. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  42915. };
  42916. /**
  42917. * Creates an custom extruded shape mesh.
  42918. * 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.
  42919. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  42920. *
  42921. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  42922. * 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
  42923. * extruded along the Z axis.
  42924. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  42925. * 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
  42926. * and the distance of this point from the begining of the path :
  42927. * ```javascript
  42928. * var rotationFunction = function(i, distance) {
  42929. * // do things
  42930. * return rotationValue; }
  42931. * ```
  42932. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  42933. * 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
  42934. * and the distance of this point from the begining of the path :
  42935. * ```javascript
  42936. * var scaleFunction = function(i, distance) {
  42937. * // do things
  42938. * return scaleValue;}
  42939. * ```
  42940. * It must returns a float value that will be the scale value applied to the shape on each path point.
  42941. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  42942. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  42943. * 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
  42944. * 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
  42945. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  42946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42947. * 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).
  42948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42949. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42950. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42951. */
  42952. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  42953. var path = options.path;
  42954. var shape = options.shape;
  42955. var scaleFunction = options.scaleFunction || (function () { return 1; });
  42956. var rotationFunction = options.rotationFunction || (function () { return 0; });
  42957. var ribbonCloseArray = options.ribbonCloseArray || false;
  42958. var ribbonClosePath = options.ribbonClosePath || false;
  42959. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  42960. var updatable = options.updatable;
  42961. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42962. var instance = options.instance;
  42963. var invertUV = options.invertUV || false;
  42964. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  42965. };
  42966. /**
  42967. * Creates lathe mesh.
  42968. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  42969. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  42970. *
  42971. * 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
  42972. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  42973. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  42974. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  42975. * 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.
  42976. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  42977. * 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
  42978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42979. * 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).
  42980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42981. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42983. */
  42984. MeshBuilder.CreateLathe = function (name, options, scene) {
  42985. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  42986. var closed = (options.closed === undefined) ? true : options.closed;
  42987. var shape = options.shape;
  42988. var radius = options.radius || 1;
  42989. var tessellation = options.tessellation || 64;
  42990. var updatable = options.updatable;
  42991. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42992. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  42993. var pi2 = Math.PI * 2;
  42994. var paths = new Array();
  42995. var invertUV = options.invertUV || false;
  42996. var i = 0;
  42997. var p = 0;
  42998. var step = pi2 / tessellation * arc;
  42999. var rotated;
  43000. var path = new Array();
  43001. ;
  43002. for (i = 0; i <= tessellation; i++) {
  43003. var path = [];
  43004. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  43005. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  43006. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  43007. }
  43008. for (p = 0; p < shape.length; p++) {
  43009. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  43010. path.push(rotated);
  43011. }
  43012. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  43013. 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));
  43014. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  43015. }
  43016. paths.push(path);
  43017. }
  43018. // lathe ribbon
  43019. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43020. return lathe;
  43021. };
  43022. /**
  43023. * Creates a plane mesh.
  43024. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43025. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  43026. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  43027. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  43028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43029. * 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).
  43030. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43032. */
  43033. MeshBuilder.CreatePlane = function (name, options, scene) {
  43034. var plane = new BABYLON.Mesh(name, scene);
  43035. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43036. plane.sideOrientation = options.sideOrientation;
  43037. var vertexData = BABYLON.VertexData.CreatePlane(options);
  43038. vertexData.applyToMesh(plane, options.updatable);
  43039. if (options.sourcePlane) {
  43040. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  43041. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  43042. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  43043. plane.rotate(vectorProduct, product);
  43044. }
  43045. return plane;
  43046. };
  43047. /**
  43048. * Creates a ground mesh.
  43049. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43050. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  43051. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  43052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43053. */
  43054. MeshBuilder.CreateGround = function (name, options, scene) {
  43055. var ground = new BABYLON.GroundMesh(name, scene);
  43056. ground._setReady(false);
  43057. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  43058. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  43059. ground._width = options.width || 1;
  43060. ground._height = options.height || 1;
  43061. ground._maxX = ground._width / 2;
  43062. ground._maxZ = ground._height / 2;
  43063. ground._minX = -ground._maxX;
  43064. ground._minZ = -ground._maxZ;
  43065. var vertexData = BABYLON.VertexData.CreateGround(options);
  43066. vertexData.applyToMesh(ground, options.updatable);
  43067. ground._setReady(true);
  43068. return ground;
  43069. };
  43070. /**
  43071. * Creates a tiled ground mesh.
  43072. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  43073. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  43074. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  43075. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  43076. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  43077. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  43078. * numbers of subdivisions on the ground width and height of each tile.
  43079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43080. */
  43081. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  43082. var tiledGround = new BABYLON.Mesh(name, scene);
  43083. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  43084. vertexData.applyToMesh(tiledGround, options.updatable);
  43085. return tiledGround;
  43086. };
  43087. /**
  43088. * Creates a ground mesh from a height map.
  43089. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  43090. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  43091. * The parameter `url` sets the URL of the height map image resource.
  43092. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  43093. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  43094. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  43095. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  43096. * 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.
  43097. * 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).
  43098. * This function is passed the newly built mesh :
  43099. * ```javascript
  43100. * function(mesh) { // do things
  43101. * return; }
  43102. * ```
  43103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43104. */
  43105. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  43106. var width = options.width || 10.0;
  43107. var height = options.height || 10.0;
  43108. var subdivisions = options.subdivisions || 1 | 0;
  43109. var minHeight = options.minHeight || 0.0;
  43110. var maxHeight = options.maxHeight || 10.0;
  43111. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  43112. var updatable = options.updatable;
  43113. var onReady = options.onReady;
  43114. var ground = new BABYLON.GroundMesh(name, scene);
  43115. ground._subdivisionsX = subdivisions;
  43116. ground._subdivisionsY = subdivisions;
  43117. ground._width = width;
  43118. ground._height = height;
  43119. ground._maxX = ground._width / 2.0;
  43120. ground._maxZ = ground._height / 2.0;
  43121. ground._minX = -ground._maxX;
  43122. ground._minZ = -ground._maxZ;
  43123. ground._setReady(false);
  43124. var onload = function (img) {
  43125. // Getting height map data
  43126. var canvas = document.createElement("canvas");
  43127. var context = canvas.getContext("2d");
  43128. var bufferWidth = img.width;
  43129. var bufferHeight = img.height;
  43130. canvas.width = bufferWidth;
  43131. canvas.height = bufferHeight;
  43132. context.drawImage(img, 0, 0);
  43133. // Create VertexData from map data
  43134. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  43135. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  43136. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  43137. width: width, height: height,
  43138. subdivisions: subdivisions,
  43139. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  43140. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  43141. });
  43142. vertexData.applyToMesh(ground, updatable);
  43143. ground._setReady(true);
  43144. //execute ready callback, if set
  43145. if (onReady) {
  43146. onReady(ground);
  43147. }
  43148. };
  43149. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  43150. return ground;
  43151. };
  43152. /**
  43153. * Creates a polygon mesh.
  43154. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  43155. * 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.
  43156. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43158. * 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).
  43159. * Remember you can only change the shape positions, not their number when updating a polygon.
  43160. */
  43161. MeshBuilder.CreatePolygon = function (name, options, scene) {
  43162. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43163. var shape = options.shape;
  43164. var holes = options.holes || [];
  43165. var depth = options.depth || 0;
  43166. var contours = [];
  43167. var hole = [];
  43168. for (var i = 0; i < shape.length; i++) {
  43169. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  43170. }
  43171. var epsilon = 0.00000001;
  43172. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  43173. contours.pop();
  43174. }
  43175. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  43176. for (var hNb = 0; hNb < holes.length; hNb++) {
  43177. hole = [];
  43178. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  43179. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  43180. }
  43181. polygonTriangulation.addHole(hole);
  43182. }
  43183. var polygon = polygonTriangulation.build(options.updatable, depth);
  43184. polygon.sideOrientation = options.sideOrientation;
  43185. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  43186. vertexData.applyToMesh(polygon, options.updatable);
  43187. return polygon;
  43188. };
  43189. ;
  43190. /**
  43191. * Creates an extruded polygon mesh, with depth in the Y direction.
  43192. * 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).
  43193. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43194. */
  43195. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  43196. return MeshBuilder.CreatePolygon(name, options, scene);
  43197. };
  43198. ;
  43199. /**
  43200. * Creates a tube mesh.
  43201. * 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.
  43202. *
  43203. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  43204. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  43205. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  43206. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  43207. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  43208. * 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.
  43209. * It must return a radius value (positive float) :
  43210. * ```javascript
  43211. * var radiusFunction = function(i, distance) {
  43212. * // do things
  43213. * return radius; }
  43214. * ```
  43215. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  43216. * 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
  43217. * 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
  43218. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43219. * 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).
  43220. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43221. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43222. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43223. */
  43224. MeshBuilder.CreateTube = function (name, options, scene) {
  43225. var path = options.path;
  43226. var radius = options.radius || 1.0;
  43227. var tessellation = options.tessellation || 64 | 0;
  43228. var radiusFunction = options.radiusFunction;
  43229. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  43230. var invertUV = options.invertUV || false;
  43231. var updatable = options.updatable;
  43232. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43233. var instance = options.instance;
  43234. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  43235. // tube geometry
  43236. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  43237. var tangents = path3D.getTangents();
  43238. var normals = path3D.getNormals();
  43239. var distances = path3D.getDistances();
  43240. var pi2 = Math.PI * 2;
  43241. var step = pi2 / tessellation * arc;
  43242. var returnRadius = function () { return radius; };
  43243. var radiusFunctionFinal = radiusFunction || returnRadius;
  43244. var circlePath;
  43245. var rad;
  43246. var normal;
  43247. var rotated;
  43248. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43249. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43250. for (var i = 0; i < path.length; i++) {
  43251. rad = radiusFunctionFinal(i, distances[i]); // current radius
  43252. circlePath = Array(); // current circle array
  43253. normal = normals[i]; // current normal
  43254. for (var t = 0; t < tessellation; t++) {
  43255. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  43256. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  43257. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  43258. rotated.scaleInPlace(rad).addInPlace(path[i]);
  43259. circlePath[t] = rotated;
  43260. }
  43261. circlePaths[index] = circlePath;
  43262. index++;
  43263. }
  43264. // cap
  43265. var capPath = function (nbPoints, pathIndex) {
  43266. var pointCap = Array();
  43267. for (var i = 0; i < nbPoints; i++) {
  43268. pointCap.push(path[pathIndex]);
  43269. }
  43270. return pointCap;
  43271. };
  43272. switch (cap) {
  43273. case BABYLON.Mesh.NO_CAP:
  43274. break;
  43275. case BABYLON.Mesh.CAP_START:
  43276. circlePaths[0] = capPath(tessellation, 0);
  43277. circlePaths[1] = circlePaths[2].slice(0);
  43278. break;
  43279. case BABYLON.Mesh.CAP_END:
  43280. circlePaths[index] = circlePaths[index - 1].slice(0);
  43281. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43282. break;
  43283. case BABYLON.Mesh.CAP_ALL:
  43284. circlePaths[0] = capPath(tessellation, 0);
  43285. circlePaths[1] = circlePaths[2].slice(0);
  43286. circlePaths[index] = circlePaths[index - 1].slice(0);
  43287. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43288. break;
  43289. default:
  43290. break;
  43291. }
  43292. return circlePaths;
  43293. };
  43294. var path3D;
  43295. var pathArray;
  43296. if (instance) {
  43297. var arc = options.arc || instance.arc;
  43298. path3D = (instance.path3D).update(path);
  43299. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  43300. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  43301. instance.path3D = path3D;
  43302. instance.pathArray = pathArray;
  43303. instance.arc = arc;
  43304. return instance;
  43305. }
  43306. // tube creation
  43307. path3D = new BABYLON.Path3D(path);
  43308. var newPathArray = new Array();
  43309. cap = (cap < 0 || cap > 3) ? 0 : cap;
  43310. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  43311. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43312. tube.pathArray = pathArray;
  43313. tube.path3D = path3D;
  43314. tube.tessellation = tessellation;
  43315. tube.cap = cap;
  43316. tube.arc = options.arc;
  43317. return tube;
  43318. };
  43319. /**
  43320. * Creates a polyhedron mesh.
  43321. *
  43322. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  43323. * 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
  43324. * to choose the wanted type.
  43325. * The parameter `size` (positive float, default 1) sets the polygon size.
  43326. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  43327. * 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`.
  43328. * 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
  43329. * 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)`).
  43330. * 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
  43331. * 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.
  43332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43333. * 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).
  43334. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43336. */
  43337. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  43338. var polyhedron = new BABYLON.Mesh(name, scene);
  43339. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43340. polyhedron.sideOrientation = options.sideOrientation;
  43341. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  43342. vertexData.applyToMesh(polyhedron, options.updatable);
  43343. return polyhedron;
  43344. };
  43345. /**
  43346. * Creates a decal mesh.
  43347. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  43348. * 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.
  43349. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  43350. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  43351. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  43352. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  43353. */
  43354. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  43355. var indices = sourceMesh.getIndices();
  43356. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43357. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43358. var position = options.position || BABYLON.Vector3.Zero();
  43359. var normal = options.normal || BABYLON.Vector3.Up();
  43360. var size = options.size || BABYLON.Vector3.One();
  43361. var angle = options.angle || 0;
  43362. // Getting correct rotation
  43363. if (!normal) {
  43364. var target = new BABYLON.Vector3(0, 0, 1);
  43365. var camera = sourceMesh.getScene().activeCamera;
  43366. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  43367. normal = camera.globalPosition.subtract(cameraWorldTarget);
  43368. }
  43369. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  43370. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  43371. var pitch = Math.atan2(normal.y, len);
  43372. // Matrix
  43373. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  43374. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  43375. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  43376. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  43377. var vertexData = new BABYLON.VertexData();
  43378. vertexData.indices = [];
  43379. vertexData.positions = [];
  43380. vertexData.normals = [];
  43381. vertexData.uvs = [];
  43382. var currentVertexDataIndex = 0;
  43383. var extractDecalVector3 = function (indexId) {
  43384. var vertexId = indices[indexId];
  43385. var result = new BABYLON.PositionNormalVertex();
  43386. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  43387. // Send vector to decal local world
  43388. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  43389. // Get normal
  43390. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  43391. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  43392. return result;
  43393. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  43394. var clip = function (vertices, axis) {
  43395. if (vertices.length === 0) {
  43396. return vertices;
  43397. }
  43398. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  43399. var clipVertices = function (v0, v1) {
  43400. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  43401. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  43402. };
  43403. var result = new Array();
  43404. for (var index = 0; index < vertices.length; index += 3) {
  43405. var v1Out;
  43406. var v2Out;
  43407. var v3Out;
  43408. var total = 0;
  43409. var nV1, nV2, nV3, nV4;
  43410. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  43411. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  43412. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  43413. v1Out = d1 > 0;
  43414. v2Out = d2 > 0;
  43415. v3Out = d3 > 0;
  43416. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  43417. switch (total) {
  43418. case 0:
  43419. result.push(vertices[index]);
  43420. result.push(vertices[index + 1]);
  43421. result.push(vertices[index + 2]);
  43422. break;
  43423. case 1:
  43424. if (v1Out) {
  43425. nV1 = vertices[index + 1];
  43426. nV2 = vertices[index + 2];
  43427. nV3 = clipVertices(vertices[index], nV1);
  43428. nV4 = clipVertices(vertices[index], nV2);
  43429. }
  43430. if (v2Out) {
  43431. nV1 = vertices[index];
  43432. nV2 = vertices[index + 2];
  43433. nV3 = clipVertices(vertices[index + 1], nV1);
  43434. nV4 = clipVertices(vertices[index + 1], nV2);
  43435. result.push(nV3);
  43436. result.push(nV2.clone());
  43437. result.push(nV1.clone());
  43438. result.push(nV2.clone());
  43439. result.push(nV3.clone());
  43440. result.push(nV4);
  43441. break;
  43442. }
  43443. if (v3Out) {
  43444. nV1 = vertices[index];
  43445. nV2 = vertices[index + 1];
  43446. nV3 = clipVertices(vertices[index + 2], nV1);
  43447. nV4 = clipVertices(vertices[index + 2], nV2);
  43448. }
  43449. result.push(nV1.clone());
  43450. result.push(nV2.clone());
  43451. result.push(nV3);
  43452. result.push(nV4);
  43453. result.push(nV3.clone());
  43454. result.push(nV2.clone());
  43455. break;
  43456. case 2:
  43457. if (!v1Out) {
  43458. nV1 = vertices[index].clone();
  43459. nV2 = clipVertices(nV1, vertices[index + 1]);
  43460. nV3 = clipVertices(nV1, vertices[index + 2]);
  43461. result.push(nV1);
  43462. result.push(nV2);
  43463. result.push(nV3);
  43464. }
  43465. if (!v2Out) {
  43466. nV1 = vertices[index + 1].clone();
  43467. nV2 = clipVertices(nV1, vertices[index + 2]);
  43468. nV3 = clipVertices(nV1, vertices[index]);
  43469. result.push(nV1);
  43470. result.push(nV2);
  43471. result.push(nV3);
  43472. }
  43473. if (!v3Out) {
  43474. nV1 = vertices[index + 2].clone();
  43475. nV2 = clipVertices(nV1, vertices[index]);
  43476. nV3 = clipVertices(nV1, vertices[index + 1]);
  43477. result.push(nV1);
  43478. result.push(nV2);
  43479. result.push(nV3);
  43480. }
  43481. break;
  43482. case 3:
  43483. break;
  43484. }
  43485. }
  43486. return result;
  43487. };
  43488. for (var index = 0; index < indices.length; index += 3) {
  43489. var faceVertices = new Array();
  43490. faceVertices.push(extractDecalVector3(index));
  43491. faceVertices.push(extractDecalVector3(index + 1));
  43492. faceVertices.push(extractDecalVector3(index + 2));
  43493. // Clip
  43494. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  43495. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  43496. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  43497. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  43498. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  43499. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  43500. if (faceVertices.length === 0) {
  43501. continue;
  43502. }
  43503. // Add UVs and get back to world
  43504. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  43505. var vertex = faceVertices[vIndex];
  43506. //TODO check for Int32Array | Uint32Array | Uint16Array
  43507. vertexData.indices.push(currentVertexDataIndex);
  43508. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  43509. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  43510. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  43511. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  43512. currentVertexDataIndex++;
  43513. }
  43514. }
  43515. // Return mesh
  43516. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  43517. vertexData.applyToMesh(decal);
  43518. decal.position = position.clone();
  43519. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  43520. return decal;
  43521. };
  43522. // Privates
  43523. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  43524. // extrusion geometry
  43525. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  43526. var tangents = path3D.getTangents();
  43527. var normals = path3D.getNormals();
  43528. var binormals = path3D.getBinormals();
  43529. var distances = path3D.getDistances();
  43530. var angle = 0;
  43531. var returnScale = function () { return scale; };
  43532. var returnRotation = function () { return rotation; };
  43533. var rotate = custom ? rotateFunction : returnRotation;
  43534. var scl = custom ? scaleFunction : returnScale;
  43535. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43536. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43537. for (var i = 0; i < curve.length; i++) {
  43538. var shapePath = new Array();
  43539. var angleStep = rotate(i, distances[i]);
  43540. var scaleRatio = scl(i, distances[i]);
  43541. for (var p = 0; p < shape.length; p++) {
  43542. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  43543. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  43544. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  43545. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  43546. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  43547. shapePath[p] = rotated;
  43548. }
  43549. shapePaths[index] = shapePath;
  43550. angle += angleStep;
  43551. index++;
  43552. }
  43553. // cap
  43554. var capPath = function (shapePath) {
  43555. var pointCap = Array();
  43556. var barycenter = BABYLON.Vector3.Zero();
  43557. var i;
  43558. for (i = 0; i < shapePath.length; i++) {
  43559. barycenter.addInPlace(shapePath[i]);
  43560. }
  43561. barycenter.scaleInPlace(1.0 / shapePath.length);
  43562. for (i = 0; i < shapePath.length; i++) {
  43563. pointCap.push(barycenter);
  43564. }
  43565. return pointCap;
  43566. };
  43567. switch (cap) {
  43568. case BABYLON.Mesh.NO_CAP:
  43569. break;
  43570. case BABYLON.Mesh.CAP_START:
  43571. shapePaths[0] = capPath(shapePaths[2]);
  43572. shapePaths[1] = shapePaths[2];
  43573. break;
  43574. case BABYLON.Mesh.CAP_END:
  43575. shapePaths[index] = shapePaths[index - 1];
  43576. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  43577. break;
  43578. case BABYLON.Mesh.CAP_ALL:
  43579. shapePaths[0] = capPath(shapePaths[2]);
  43580. shapePaths[1] = shapePaths[2];
  43581. shapePaths[index] = shapePaths[index - 1];
  43582. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  43583. break;
  43584. default:
  43585. break;
  43586. }
  43587. return shapePaths;
  43588. };
  43589. var path3D;
  43590. var pathArray;
  43591. if (instance) {
  43592. path3D = (instance.path3D).update(curve);
  43593. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  43594. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  43595. return instance;
  43596. }
  43597. // extruded shape creation
  43598. path3D = new BABYLON.Path3D(curve);
  43599. var newShapePaths = new Array();
  43600. cap = (cap < 0 || cap > 3) ? 0 : cap;
  43601. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  43602. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  43603. extrudedGeneric.pathArray = pathArray;
  43604. extrudedGeneric.path3D = path3D;
  43605. extrudedGeneric.cap = cap;
  43606. return extrudedGeneric;
  43607. };
  43608. return MeshBuilder;
  43609. }());
  43610. BABYLON.MeshBuilder = MeshBuilder;
  43611. })(BABYLON || (BABYLON = {}));
  43612. //# sourceMappingURL=babylon.meshBuilder.js.map
  43613. var BABYLON;
  43614. (function (BABYLON) {
  43615. var AudioEngine = (function () {
  43616. function AudioEngine() {
  43617. this._audioContext = null;
  43618. this._audioContextInitialized = false;
  43619. this.canUseWebAudio = false;
  43620. this.WarnedWebAudioUnsupported = false;
  43621. this.unlocked = false;
  43622. this.isMP3supported = false;
  43623. this.isOGGsupported = false;
  43624. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  43625. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  43626. this.canUseWebAudio = true;
  43627. }
  43628. var audioElem = document.createElement('audio');
  43629. try {
  43630. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  43631. this.isMP3supported = true;
  43632. }
  43633. }
  43634. catch (e) {
  43635. // protect error during capability check.
  43636. }
  43637. try {
  43638. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  43639. this.isOGGsupported = true;
  43640. }
  43641. }
  43642. catch (e) {
  43643. // protect error during capability check.
  43644. }
  43645. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  43646. this._unlockiOSaudio();
  43647. }
  43648. else {
  43649. this.unlocked = true;
  43650. }
  43651. }
  43652. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  43653. get: function () {
  43654. if (!this._audioContextInitialized) {
  43655. this._initializeAudioContext();
  43656. }
  43657. return this._audioContext;
  43658. },
  43659. enumerable: true,
  43660. configurable: true
  43661. });
  43662. AudioEngine.prototype._unlockiOSaudio = function () {
  43663. var _this = this;
  43664. var unlockaudio = function () {
  43665. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  43666. var source = _this.audioContext.createBufferSource();
  43667. source.buffer = buffer;
  43668. source.connect(_this.audioContext.destination);
  43669. source.start(0);
  43670. setTimeout(function () {
  43671. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  43672. _this.unlocked = true;
  43673. window.removeEventListener('touchend', unlockaudio, false);
  43674. if (_this.onAudioUnlocked) {
  43675. _this.onAudioUnlocked();
  43676. }
  43677. }
  43678. }, 0);
  43679. };
  43680. window.addEventListener('touchend', unlockaudio, false);
  43681. };
  43682. AudioEngine.prototype._initializeAudioContext = function () {
  43683. try {
  43684. if (this.canUseWebAudio) {
  43685. this._audioContext = new AudioContext();
  43686. // create a global volume gain node
  43687. this.masterGain = this._audioContext.createGain();
  43688. this.masterGain.gain.value = 1;
  43689. this.masterGain.connect(this._audioContext.destination);
  43690. this._audioContextInitialized = true;
  43691. }
  43692. }
  43693. catch (e) {
  43694. this.canUseWebAudio = false;
  43695. BABYLON.Tools.Error("Web Audio: " + e.message);
  43696. }
  43697. };
  43698. AudioEngine.prototype.dispose = function () {
  43699. if (this.canUseWebAudio && this._audioContextInitialized) {
  43700. if (this._connectedAnalyser) {
  43701. this._connectedAnalyser.stopDebugCanvas();
  43702. this._connectedAnalyser.dispose();
  43703. this.masterGain.disconnect();
  43704. this.masterGain.connect(this._audioContext.destination);
  43705. this._connectedAnalyser = null;
  43706. }
  43707. this.masterGain.gain.value = 1;
  43708. }
  43709. this.WarnedWebAudioUnsupported = false;
  43710. };
  43711. AudioEngine.prototype.getGlobalVolume = function () {
  43712. if (this.canUseWebAudio && this._audioContextInitialized) {
  43713. return this.masterGain.gain.value;
  43714. }
  43715. else {
  43716. return -1;
  43717. }
  43718. };
  43719. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  43720. if (this.canUseWebAudio && this._audioContextInitialized) {
  43721. this.masterGain.gain.value = newVolume;
  43722. }
  43723. };
  43724. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  43725. if (this._connectedAnalyser) {
  43726. this._connectedAnalyser.stopDebugCanvas();
  43727. }
  43728. if (this.canUseWebAudio && this._audioContextInitialized) {
  43729. this._connectedAnalyser = analyser;
  43730. this.masterGain.disconnect();
  43731. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  43732. }
  43733. };
  43734. return AudioEngine;
  43735. }());
  43736. BABYLON.AudioEngine = AudioEngine;
  43737. })(BABYLON || (BABYLON = {}));
  43738. //# sourceMappingURL=babylon.audioEngine.js.map
  43739. var BABYLON;
  43740. (function (BABYLON) {
  43741. var Sound = (function () {
  43742. /**
  43743. * Create a sound and attach it to a scene
  43744. * @param name Name of your sound
  43745. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  43746. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  43747. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  43748. */
  43749. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  43750. var _this = this;
  43751. this.autoplay = false;
  43752. this.loop = false;
  43753. this.useCustomAttenuation = false;
  43754. this.spatialSound = false;
  43755. this.refDistance = 1;
  43756. this.rolloffFactor = 1;
  43757. this.maxDistance = 100;
  43758. this.distanceModel = "linear";
  43759. this._panningModel = "equalpower";
  43760. this._playbackRate = 1;
  43761. this._streaming = false;
  43762. this._startTime = 0;
  43763. this._startOffset = 0;
  43764. this._position = BABYLON.Vector3.Zero();
  43765. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  43766. this._volume = 1;
  43767. this._isLoaded = false;
  43768. this._isReadyToPlay = false;
  43769. this.isPlaying = false;
  43770. this.isPaused = false;
  43771. this._isDirectional = false;
  43772. // Used if you'd like to create a directional sound.
  43773. // If not set, the sound will be omnidirectional
  43774. this._coneInnerAngle = 360;
  43775. this._coneOuterAngle = 360;
  43776. this._coneOuterGain = 0;
  43777. this._isOutputConnected = false;
  43778. this._urlType = "Unknown";
  43779. this.name = name;
  43780. this._scene = scene;
  43781. this._readyToPlayCallback = readyToPlayCallback;
  43782. // Default custom attenuation function is a linear attenuation
  43783. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  43784. if (currentDistance < maxDistance) {
  43785. return currentVolume * (1 - currentDistance / maxDistance);
  43786. }
  43787. else {
  43788. return 0;
  43789. }
  43790. };
  43791. if (options) {
  43792. this.autoplay = options.autoplay || false;
  43793. this.loop = options.loop || false;
  43794. // if volume === 0, we need another way to check this option
  43795. if (options.volume !== undefined) {
  43796. this._volume = options.volume;
  43797. }
  43798. this.spatialSound = options.spatialSound || false;
  43799. this.maxDistance = options.maxDistance || 100;
  43800. this.useCustomAttenuation = options.useCustomAttenuation || false;
  43801. this.rolloffFactor = options.rolloffFactor || 1;
  43802. this.refDistance = options.refDistance || 1;
  43803. this.distanceModel = options.distanceModel || "linear";
  43804. this._playbackRate = options.playbackRate || 1;
  43805. this._streaming = options.streaming || false;
  43806. }
  43807. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43808. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  43809. this._soundGain.gain.value = this._volume;
  43810. this._inputAudioNode = this._soundGain;
  43811. this._ouputAudioNode = this._soundGain;
  43812. if (this.spatialSound) {
  43813. this._createSpatialParameters();
  43814. }
  43815. this._scene.mainSoundTrack.AddSound(this);
  43816. var validParameter = true;
  43817. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  43818. if (urlOrArrayBuffer) {
  43819. if (typeof (urlOrArrayBuffer) === "string")
  43820. this._urlType = "String";
  43821. if (Array.isArray(urlOrArrayBuffer))
  43822. this._urlType = "Array";
  43823. if (urlOrArrayBuffer instanceof ArrayBuffer)
  43824. this._urlType = "ArrayBuffer";
  43825. var urls = [];
  43826. var codecSupportedFound = false;
  43827. switch (this._urlType) {
  43828. case "ArrayBuffer":
  43829. if (urlOrArrayBuffer.byteLength > 0) {
  43830. codecSupportedFound = true;
  43831. this._soundLoaded(urlOrArrayBuffer);
  43832. }
  43833. break;
  43834. case "String":
  43835. urls.push(urlOrArrayBuffer);
  43836. case "Array":
  43837. if (urls.length === 0)
  43838. urls = urlOrArrayBuffer;
  43839. // If we found a supported format, we load it immediately and stop the loop
  43840. for (var i = 0; i < urls.length; i++) {
  43841. var url = urls[i];
  43842. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  43843. codecSupportedFound = true;
  43844. }
  43845. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  43846. codecSupportedFound = true;
  43847. }
  43848. if (url.indexOf(".wav", url.length - 4) !== -1) {
  43849. codecSupportedFound = true;
  43850. }
  43851. if (url.indexOf("blob:") !== -1) {
  43852. codecSupportedFound = true;
  43853. }
  43854. if (codecSupportedFound) {
  43855. // Loading sound using XHR2
  43856. if (!this._streaming) {
  43857. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  43858. }
  43859. else {
  43860. this._htmlAudioElement = new Audio(url);
  43861. this._htmlAudioElement.controls = false;
  43862. this._htmlAudioElement.loop = this.loop;
  43863. this._htmlAudioElement.crossOrigin = "anonymous";
  43864. this._htmlAudioElement.preload = "auto";
  43865. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  43866. _this._isReadyToPlay = true;
  43867. if (_this.autoplay) {
  43868. _this.play();
  43869. }
  43870. if (_this._readyToPlayCallback) {
  43871. _this._readyToPlayCallback();
  43872. }
  43873. });
  43874. document.body.appendChild(this._htmlAudioElement);
  43875. }
  43876. break;
  43877. }
  43878. }
  43879. break;
  43880. default:
  43881. validParameter = false;
  43882. break;
  43883. }
  43884. if (!validParameter) {
  43885. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  43886. }
  43887. else {
  43888. if (!codecSupportedFound) {
  43889. this._isReadyToPlay = true;
  43890. // Simulating a ready to play event to avoid breaking code path
  43891. if (this._readyToPlayCallback) {
  43892. window.setTimeout(function () {
  43893. _this._readyToPlayCallback();
  43894. }, 1000);
  43895. }
  43896. }
  43897. }
  43898. }
  43899. }
  43900. else {
  43901. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  43902. this._scene.mainSoundTrack.AddSound(this);
  43903. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  43904. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  43905. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  43906. }
  43907. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  43908. if (this._readyToPlayCallback) {
  43909. window.setTimeout(function () {
  43910. _this._readyToPlayCallback();
  43911. }, 1000);
  43912. }
  43913. }
  43914. }
  43915. Sound.prototype.dispose = function () {
  43916. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  43917. if (this.isPlaying) {
  43918. this.stop();
  43919. }
  43920. this._isReadyToPlay = false;
  43921. if (this.soundTrackId === -1) {
  43922. this._scene.mainSoundTrack.RemoveSound(this);
  43923. }
  43924. else {
  43925. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  43926. }
  43927. if (this._soundGain) {
  43928. this._soundGain.disconnect();
  43929. this._soundGain = null;
  43930. }
  43931. if (this._soundPanner) {
  43932. this._soundPanner.disconnect();
  43933. this._soundPanner = null;
  43934. }
  43935. if (this._soundSource) {
  43936. this._soundSource.disconnect();
  43937. this._soundSource = null;
  43938. }
  43939. this._audioBuffer = null;
  43940. if (this._htmlAudioElement) {
  43941. this._htmlAudioElement.pause();
  43942. this._htmlAudioElement.src = "";
  43943. document.body.removeChild(this._htmlAudioElement);
  43944. }
  43945. if (this._connectedMesh) {
  43946. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43947. this._connectedMesh = null;
  43948. }
  43949. }
  43950. };
  43951. Sound.prototype.isReady = function () {
  43952. return this._isReadyToPlay;
  43953. };
  43954. Sound.prototype._soundLoaded = function (audioData) {
  43955. var _this = this;
  43956. this._isLoaded = true;
  43957. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  43958. _this._audioBuffer = buffer;
  43959. _this._isReadyToPlay = true;
  43960. if (_this.autoplay) {
  43961. _this.play();
  43962. }
  43963. if (_this._readyToPlayCallback) {
  43964. _this._readyToPlayCallback();
  43965. }
  43966. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  43967. };
  43968. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  43969. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43970. this._audioBuffer = audioBuffer;
  43971. this._isReadyToPlay = true;
  43972. }
  43973. };
  43974. Sound.prototype.updateOptions = function (options) {
  43975. if (options) {
  43976. this.loop = options.loop || this.loop;
  43977. this.maxDistance = options.maxDistance || this.maxDistance;
  43978. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  43979. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  43980. this.refDistance = options.refDistance || this.refDistance;
  43981. this.distanceModel = options.distanceModel || this.distanceModel;
  43982. this._playbackRate = options.playbackRate || this._playbackRate;
  43983. this._updateSpatialParameters();
  43984. if (this.isPlaying) {
  43985. if (this._streaming) {
  43986. this._htmlAudioElement.playbackRate = this._playbackRate;
  43987. }
  43988. else {
  43989. this._soundSource.playbackRate.value = this._playbackRate;
  43990. }
  43991. }
  43992. }
  43993. };
  43994. Sound.prototype._createSpatialParameters = function () {
  43995. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43996. if (this._scene.headphone) {
  43997. this._panningModel = "HRTF";
  43998. }
  43999. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  44000. this._updateSpatialParameters();
  44001. this._soundPanner.connect(this._ouputAudioNode);
  44002. this._inputAudioNode = this._soundPanner;
  44003. }
  44004. };
  44005. Sound.prototype._updateSpatialParameters = function () {
  44006. if (this.spatialSound) {
  44007. if (this.useCustomAttenuation) {
  44008. // Tricks to disable in a way embedded Web Audio attenuation
  44009. this._soundPanner.distanceModel = "linear";
  44010. this._soundPanner.maxDistance = Number.MAX_VALUE;
  44011. this._soundPanner.refDistance = 1;
  44012. this._soundPanner.rolloffFactor = 1;
  44013. this._soundPanner.panningModel = this._panningModel;
  44014. }
  44015. else {
  44016. this._soundPanner.distanceModel = this.distanceModel;
  44017. this._soundPanner.maxDistance = this.maxDistance;
  44018. this._soundPanner.refDistance = this.refDistance;
  44019. this._soundPanner.rolloffFactor = this.rolloffFactor;
  44020. this._soundPanner.panningModel = this._panningModel;
  44021. }
  44022. }
  44023. };
  44024. Sound.prototype.switchPanningModelToHRTF = function () {
  44025. this._panningModel = "HRTF";
  44026. this._switchPanningModel();
  44027. };
  44028. Sound.prototype.switchPanningModelToEqualPower = function () {
  44029. this._panningModel = "equalpower";
  44030. this._switchPanningModel();
  44031. };
  44032. Sound.prototype._switchPanningModel = function () {
  44033. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44034. this._soundPanner.panningModel = this._panningModel;
  44035. }
  44036. };
  44037. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  44038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44039. if (this._isOutputConnected) {
  44040. this._ouputAudioNode.disconnect();
  44041. }
  44042. this._ouputAudioNode.connect(soundTrackAudioNode);
  44043. this._isOutputConnected = true;
  44044. }
  44045. };
  44046. /**
  44047. * Transform this sound into a directional source
  44048. * @param coneInnerAngle Size of the inner cone in degree
  44049. * @param coneOuterAngle Size of the outer cone in degree
  44050. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  44051. */
  44052. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  44053. if (coneOuterAngle < coneInnerAngle) {
  44054. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  44055. return;
  44056. }
  44057. this._coneInnerAngle = coneInnerAngle;
  44058. this._coneOuterAngle = coneOuterAngle;
  44059. this._coneOuterGain = coneOuterGain;
  44060. this._isDirectional = true;
  44061. if (this.isPlaying && this.loop) {
  44062. this.stop();
  44063. this.play();
  44064. }
  44065. };
  44066. Sound.prototype.setPosition = function (newPosition) {
  44067. this._position = newPosition;
  44068. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44069. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44070. }
  44071. };
  44072. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  44073. this._localDirection = newLocalDirection;
  44074. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  44075. this._updateDirection();
  44076. }
  44077. };
  44078. Sound.prototype._updateDirection = function () {
  44079. var mat = this._connectedMesh.getWorldMatrix();
  44080. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  44081. direction.normalize();
  44082. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  44083. };
  44084. Sound.prototype.updateDistanceFromListener = function () {
  44085. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  44086. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  44087. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  44088. }
  44089. };
  44090. Sound.prototype.setAttenuationFunction = function (callback) {
  44091. this._customAttenuationFunction = callback;
  44092. };
  44093. /**
  44094. * Play the sound
  44095. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  44096. * @param offset (optional) Start the sound setting it at a specific time
  44097. */
  44098. Sound.prototype.play = function (time, offset) {
  44099. var _this = this;
  44100. if (this._isReadyToPlay && this._scene.audioEnabled) {
  44101. try {
  44102. if (this._startOffset < 0) {
  44103. time = -this._startOffset;
  44104. this._startOffset = 0;
  44105. }
  44106. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44107. if (!this._soundSource || !this._streamingSource) {
  44108. if (this.spatialSound) {
  44109. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44110. if (this._isDirectional) {
  44111. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  44112. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  44113. this._soundPanner.coneOuterGain = this._coneOuterGain;
  44114. if (this._connectedMesh) {
  44115. this._updateDirection();
  44116. }
  44117. else {
  44118. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  44119. }
  44120. }
  44121. }
  44122. }
  44123. if (this._streaming) {
  44124. if (!this._streamingSource) {
  44125. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  44126. this._htmlAudioElement.onended = function () { _this._onended(); };
  44127. this._htmlAudioElement.playbackRate = this._playbackRate;
  44128. }
  44129. this._streamingSource.disconnect();
  44130. this._streamingSource.connect(this._inputAudioNode);
  44131. this._htmlAudioElement.play();
  44132. }
  44133. else {
  44134. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  44135. this._soundSource.buffer = this._audioBuffer;
  44136. this._soundSource.connect(this._inputAudioNode);
  44137. this._soundSource.loop = this.loop;
  44138. this._soundSource.playbackRate.value = this._playbackRate;
  44139. this._soundSource.onended = function () { _this._onended(); };
  44140. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  44141. }
  44142. this._startTime = startTime;
  44143. this.isPlaying = true;
  44144. this.isPaused = false;
  44145. }
  44146. catch (ex) {
  44147. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  44148. }
  44149. }
  44150. };
  44151. Sound.prototype._onended = function () {
  44152. this.isPlaying = false;
  44153. if (this.onended) {
  44154. this.onended();
  44155. }
  44156. };
  44157. /**
  44158. * Stop the sound
  44159. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  44160. */
  44161. Sound.prototype.stop = function (time) {
  44162. if (this.isPlaying) {
  44163. if (this._streaming) {
  44164. this._htmlAudioElement.pause();
  44165. // Test needed for Firefox or it will generate an Invalid State Error
  44166. if (this._htmlAudioElement.currentTime > 0) {
  44167. this._htmlAudioElement.currentTime = 0;
  44168. }
  44169. }
  44170. else {
  44171. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44172. this._soundSource.stop(stopTime);
  44173. this._soundSource.onended = null;
  44174. if (!this.isPaused) {
  44175. this._startOffset = 0;
  44176. }
  44177. }
  44178. this.isPlaying = false;
  44179. }
  44180. };
  44181. Sound.prototype.pause = function () {
  44182. if (this.isPlaying) {
  44183. this.isPaused = true;
  44184. if (this._streaming) {
  44185. this._htmlAudioElement.pause();
  44186. }
  44187. else {
  44188. this.stop(0);
  44189. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  44190. }
  44191. }
  44192. };
  44193. Sound.prototype.setVolume = function (newVolume, time) {
  44194. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44195. if (time) {
  44196. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  44197. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  44198. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  44199. }
  44200. else {
  44201. this._soundGain.gain.value = newVolume;
  44202. }
  44203. }
  44204. this._volume = newVolume;
  44205. };
  44206. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  44207. this._playbackRate = newPlaybackRate;
  44208. if (this.isPlaying) {
  44209. if (this._streaming) {
  44210. this._htmlAudioElement.playbackRate = this._playbackRate;
  44211. }
  44212. else {
  44213. this._soundSource.playbackRate.value = this._playbackRate;
  44214. }
  44215. }
  44216. };
  44217. Sound.prototype.getVolume = function () {
  44218. return this._volume;
  44219. };
  44220. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  44221. var _this = this;
  44222. if (this._connectedMesh) {
  44223. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44224. this._registerFunc = null;
  44225. }
  44226. this._connectedMesh = meshToConnectTo;
  44227. if (!this.spatialSound) {
  44228. this.spatialSound = true;
  44229. this._createSpatialParameters();
  44230. if (this.isPlaying && this.loop) {
  44231. this.stop();
  44232. this.play();
  44233. }
  44234. }
  44235. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  44236. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  44237. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  44238. };
  44239. Sound.prototype.detachFromMesh = function () {
  44240. if (this._connectedMesh) {
  44241. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44242. this._registerFunc = null;
  44243. this._connectedMesh = null;
  44244. }
  44245. };
  44246. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  44247. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  44248. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  44249. this._updateDirection();
  44250. }
  44251. };
  44252. Sound.prototype.clone = function () {
  44253. var _this = this;
  44254. if (!this._streaming) {
  44255. var setBufferAndRun = function () {
  44256. if (_this._isReadyToPlay) {
  44257. clonedSound._audioBuffer = _this.getAudioBuffer();
  44258. clonedSound._isReadyToPlay = true;
  44259. if (clonedSound.autoplay) {
  44260. clonedSound.play();
  44261. }
  44262. }
  44263. else {
  44264. window.setTimeout(setBufferAndRun, 300);
  44265. }
  44266. };
  44267. var currentOptions = {
  44268. autoplay: this.autoplay, loop: this.loop,
  44269. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  44270. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  44271. refDistance: this.refDistance, distanceModel: this.distanceModel
  44272. };
  44273. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  44274. if (this.useCustomAttenuation) {
  44275. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  44276. }
  44277. clonedSound.setPosition(this._position);
  44278. clonedSound.setPlaybackRate(this._playbackRate);
  44279. setBufferAndRun();
  44280. return clonedSound;
  44281. }
  44282. else {
  44283. return null;
  44284. }
  44285. };
  44286. Sound.prototype.getAudioBuffer = function () {
  44287. return this._audioBuffer;
  44288. };
  44289. Sound.prototype.serialize = function () {
  44290. var serializationObject = {
  44291. name: this.name,
  44292. url: this.name,
  44293. autoplay: this.autoplay,
  44294. loop: this.loop,
  44295. volume: this._volume,
  44296. spatialSound: this.spatialSound,
  44297. maxDistance: this.maxDistance,
  44298. rolloffFactor: this.rolloffFactor,
  44299. refDistance: this.refDistance,
  44300. distanceModel: this.distanceModel,
  44301. playbackRate: this._playbackRate,
  44302. panningModel: this._panningModel,
  44303. soundTrackId: this.soundTrackId
  44304. };
  44305. if (this.spatialSound) {
  44306. if (this._connectedMesh)
  44307. serializationObject.connectedMeshId = this._connectedMesh.id;
  44308. serializationObject.position = this._position.asArray();
  44309. serializationObject.refDistance = this.refDistance;
  44310. serializationObject.distanceModel = this.distanceModel;
  44311. serializationObject.isDirectional = this._isDirectional;
  44312. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  44313. serializationObject.coneInnerAngle = this._coneInnerAngle;
  44314. serializationObject.coneOuterAngle = this._coneOuterAngle;
  44315. serializationObject.coneOuterGain = this._coneOuterGain;
  44316. }
  44317. return serializationObject;
  44318. };
  44319. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  44320. var soundName = parsedSound.name;
  44321. var soundUrl;
  44322. if (parsedSound.url) {
  44323. soundUrl = rootUrl + parsedSound.url;
  44324. }
  44325. else {
  44326. soundUrl = rootUrl + soundName;
  44327. }
  44328. var options = {
  44329. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  44330. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  44331. rolloffFactor: parsedSound.rolloffFactor,
  44332. refDistance: parsedSound.refDistance,
  44333. distanceModel: parsedSound.distanceModel,
  44334. playbackRate: parsedSound.playbackRate
  44335. };
  44336. var newSound;
  44337. if (!sourceSound) {
  44338. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  44339. scene._addPendingData(newSound);
  44340. }
  44341. else {
  44342. var setBufferAndRun = function () {
  44343. if (sourceSound._isReadyToPlay) {
  44344. newSound._audioBuffer = sourceSound.getAudioBuffer();
  44345. newSound._isReadyToPlay = true;
  44346. if (newSound.autoplay) {
  44347. newSound.play();
  44348. }
  44349. }
  44350. else {
  44351. window.setTimeout(setBufferAndRun, 300);
  44352. }
  44353. };
  44354. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  44355. setBufferAndRun();
  44356. }
  44357. if (parsedSound.position) {
  44358. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  44359. newSound.setPosition(soundPosition);
  44360. }
  44361. if (parsedSound.isDirectional) {
  44362. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  44363. if (parsedSound.localDirectionToMesh) {
  44364. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  44365. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  44366. }
  44367. }
  44368. if (parsedSound.connectedMeshId) {
  44369. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  44370. if (connectedMesh) {
  44371. newSound.attachToMesh(connectedMesh);
  44372. }
  44373. }
  44374. return newSound;
  44375. };
  44376. return Sound;
  44377. }());
  44378. BABYLON.Sound = Sound;
  44379. })(BABYLON || (BABYLON = {}));
  44380. //# sourceMappingURL=babylon.sound.js.map
  44381. var BABYLON;
  44382. (function (BABYLON) {
  44383. var SoundTrack = (function () {
  44384. function SoundTrack(scene, options) {
  44385. this.id = -1;
  44386. this._isMainTrack = false;
  44387. this._isInitialized = false;
  44388. this._scene = scene;
  44389. this.soundCollection = new Array();
  44390. this._options = options;
  44391. if (!this._isMainTrack) {
  44392. this._scene.soundTracks.push(this);
  44393. this.id = this._scene.soundTracks.length - 1;
  44394. }
  44395. }
  44396. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  44397. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44398. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  44399. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  44400. if (this._options) {
  44401. if (this._options.volume) {
  44402. this._outputAudioNode.gain.value = this._options.volume;
  44403. }
  44404. if (this._options.mainTrack) {
  44405. this._isMainTrack = this._options.mainTrack;
  44406. }
  44407. }
  44408. this._isInitialized = true;
  44409. }
  44410. };
  44411. SoundTrack.prototype.dispose = function () {
  44412. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44413. if (this._connectedAnalyser) {
  44414. this._connectedAnalyser.stopDebugCanvas();
  44415. }
  44416. while (this.soundCollection.length) {
  44417. this.soundCollection[0].dispose();
  44418. }
  44419. if (this._outputAudioNode) {
  44420. this._outputAudioNode.disconnect();
  44421. }
  44422. this._outputAudioNode = null;
  44423. }
  44424. };
  44425. SoundTrack.prototype.AddSound = function (sound) {
  44426. if (!this._isInitialized) {
  44427. this._initializeSoundTrackAudioGraph();
  44428. }
  44429. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44430. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  44431. }
  44432. if (sound.soundTrackId) {
  44433. if (sound.soundTrackId === -1) {
  44434. this._scene.mainSoundTrack.RemoveSound(sound);
  44435. }
  44436. else {
  44437. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44438. }
  44439. }
  44440. this.soundCollection.push(sound);
  44441. sound.soundTrackId = this.id;
  44442. };
  44443. SoundTrack.prototype.RemoveSound = function (sound) {
  44444. var index = this.soundCollection.indexOf(sound);
  44445. if (index !== -1) {
  44446. this.soundCollection.splice(index, 1);
  44447. }
  44448. };
  44449. SoundTrack.prototype.setVolume = function (newVolume) {
  44450. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44451. this._outputAudioNode.gain.value = newVolume;
  44452. }
  44453. };
  44454. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  44455. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44456. for (var i = 0; i < this.soundCollection.length; i++) {
  44457. this.soundCollection[i].switchPanningModelToHRTF();
  44458. }
  44459. }
  44460. };
  44461. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  44462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44463. for (var i = 0; i < this.soundCollection.length; i++) {
  44464. this.soundCollection[i].switchPanningModelToEqualPower();
  44465. }
  44466. }
  44467. };
  44468. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  44469. if (this._connectedAnalyser) {
  44470. this._connectedAnalyser.stopDebugCanvas();
  44471. }
  44472. this._connectedAnalyser = analyser;
  44473. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44474. this._outputAudioNode.disconnect();
  44475. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  44476. }
  44477. };
  44478. return SoundTrack;
  44479. }());
  44480. BABYLON.SoundTrack = SoundTrack;
  44481. })(BABYLON || (BABYLON = {}));
  44482. //# sourceMappingURL=babylon.soundtrack.js.map
  44483. var BABYLON;
  44484. (function (BABYLON) {
  44485. var Analyser = (function () {
  44486. function Analyser(scene) {
  44487. this.SMOOTHING = 0.75;
  44488. this.FFT_SIZE = 512;
  44489. this.BARGRAPHAMPLITUDE = 256;
  44490. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  44491. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  44492. this._scene = scene;
  44493. this._audioEngine = BABYLON.Engine.audioEngine;
  44494. if (this._audioEngine.canUseWebAudio) {
  44495. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  44496. this._webAudioAnalyser.minDecibels = -140;
  44497. this._webAudioAnalyser.maxDecibels = 0;
  44498. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44499. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44500. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  44501. }
  44502. }
  44503. Analyser.prototype.getFrequencyBinCount = function () {
  44504. if (this._audioEngine.canUseWebAudio) {
  44505. return this._webAudioAnalyser.frequencyBinCount;
  44506. }
  44507. else {
  44508. return 0;
  44509. }
  44510. };
  44511. Analyser.prototype.getByteFrequencyData = function () {
  44512. if (this._audioEngine.canUseWebAudio) {
  44513. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44514. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44515. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  44516. }
  44517. return this._byteFreqs;
  44518. };
  44519. Analyser.prototype.getByteTimeDomainData = function () {
  44520. if (this._audioEngine.canUseWebAudio) {
  44521. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44522. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44523. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  44524. }
  44525. return this._byteTime;
  44526. };
  44527. Analyser.prototype.getFloatFrequencyData = function () {
  44528. if (this._audioEngine.canUseWebAudio) {
  44529. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44530. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44531. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  44532. }
  44533. return this._floatFreqs;
  44534. };
  44535. Analyser.prototype.drawDebugCanvas = function () {
  44536. var _this = this;
  44537. if (this._audioEngine.canUseWebAudio) {
  44538. if (!this._debugCanvas) {
  44539. this._debugCanvas = document.createElement("canvas");
  44540. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  44541. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  44542. this._debugCanvas.style.position = "absolute";
  44543. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  44544. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  44545. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  44546. document.body.appendChild(this._debugCanvas);
  44547. this._registerFunc = function () {
  44548. _this.drawDebugCanvas();
  44549. };
  44550. this._scene.registerBeforeRender(this._registerFunc);
  44551. }
  44552. if (this._registerFunc) {
  44553. var workingArray = this.getByteFrequencyData();
  44554. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  44555. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  44556. // Draw the frequency domain chart.
  44557. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  44558. var value = workingArray[i];
  44559. var percent = value / this.BARGRAPHAMPLITUDE;
  44560. var height = this.DEBUGCANVASSIZE.height * percent;
  44561. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  44562. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  44563. var hue = i / this.getFrequencyBinCount() * 360;
  44564. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  44565. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  44566. }
  44567. }
  44568. }
  44569. };
  44570. Analyser.prototype.stopDebugCanvas = function () {
  44571. if (this._debugCanvas) {
  44572. this._scene.unregisterBeforeRender(this._registerFunc);
  44573. this._registerFunc = null;
  44574. document.body.removeChild(this._debugCanvas);
  44575. this._debugCanvas = null;
  44576. this._debugCanvasContext = null;
  44577. }
  44578. };
  44579. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  44580. if (this._audioEngine.canUseWebAudio) {
  44581. inputAudioNode.connect(this._webAudioAnalyser);
  44582. this._webAudioAnalyser.connect(outputAudioNode);
  44583. }
  44584. };
  44585. Analyser.prototype.dispose = function () {
  44586. if (this._audioEngine.canUseWebAudio) {
  44587. this._webAudioAnalyser.disconnect();
  44588. }
  44589. };
  44590. return Analyser;
  44591. }());
  44592. BABYLON.Analyser = Analyser;
  44593. })(BABYLON || (BABYLON = {}));
  44594. //# sourceMappingURL=babylon.analyser.js.map
  44595. var BABYLON;
  44596. (function (BABYLON) {
  44597. var CubeTexture = (function (_super) {
  44598. __extends(CubeTexture, _super);
  44599. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  44600. if (onLoad === void 0) { onLoad = null; }
  44601. if (onError === void 0) { onError = null; }
  44602. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  44603. if (prefiltered === void 0) { prefiltered = false; }
  44604. if (forcedExtension === void 0) { forcedExtension = null; }
  44605. var _this = _super.call(this, scene) || this;
  44606. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  44607. _this.name = rootUrl;
  44608. _this.url = rootUrl;
  44609. _this._noMipmap = noMipmap;
  44610. _this.hasAlpha = false;
  44611. _this._format = format;
  44612. _this._prefiltered = prefiltered;
  44613. _this.isCube = true;
  44614. _this._textureMatrix = BABYLON.Matrix.Identity();
  44615. if (prefiltered) {
  44616. _this.gammaSpace = false;
  44617. }
  44618. if (!rootUrl && !files) {
  44619. return _this;
  44620. }
  44621. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  44622. if (!files) {
  44623. if (!extensions) {
  44624. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  44625. }
  44626. files = [];
  44627. for (var index = 0; index < extensions.length; index++) {
  44628. files.push(rootUrl + extensions[index]);
  44629. }
  44630. _this._extensions = extensions;
  44631. }
  44632. _this._files = files;
  44633. if (!_this._texture) {
  44634. if (!scene.useDelayedTextureLoading) {
  44635. if (prefiltered) {
  44636. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  44637. }
  44638. else {
  44639. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  44640. }
  44641. }
  44642. else {
  44643. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  44644. }
  44645. }
  44646. else if (onLoad) {
  44647. if (_this._texture.isReady) {
  44648. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  44649. }
  44650. else {
  44651. _this._texture.onLoadedCallbacks.push(onLoad);
  44652. }
  44653. }
  44654. return _this;
  44655. }
  44656. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  44657. return new CubeTexture("", scene, null, noMipmap, files);
  44658. };
  44659. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  44660. if (forcedExtension === void 0) { forcedExtension = null; }
  44661. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  44662. };
  44663. // Methods
  44664. CubeTexture.prototype.delayLoad = function () {
  44665. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  44666. return;
  44667. }
  44668. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  44669. this._texture = this._getFromCache(this.url, this._noMipmap);
  44670. if (!this._texture) {
  44671. if (this._prefiltered) {
  44672. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  44673. }
  44674. else {
  44675. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  44676. }
  44677. }
  44678. };
  44679. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  44680. return this._textureMatrix;
  44681. };
  44682. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  44683. this._textureMatrix = value;
  44684. };
  44685. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  44686. var texture = BABYLON.SerializationHelper.Parse(function () {
  44687. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  44688. }, parsedTexture, scene);
  44689. // Animations
  44690. if (parsedTexture.animations) {
  44691. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  44692. var parsedAnimation = parsedTexture.animations[animationIndex];
  44693. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44694. }
  44695. }
  44696. return texture;
  44697. };
  44698. CubeTexture.prototype.clone = function () {
  44699. var _this = this;
  44700. return BABYLON.SerializationHelper.Clone(function () {
  44701. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  44702. }, this);
  44703. };
  44704. return CubeTexture;
  44705. }(BABYLON.BaseTexture));
  44706. BABYLON.CubeTexture = CubeTexture;
  44707. })(BABYLON || (BABYLON = {}));
  44708. //# sourceMappingURL=babylon.cubeTexture.js.map
  44709. var BABYLON;
  44710. (function (BABYLON) {
  44711. var RenderTargetTexture = (function (_super) {
  44712. __extends(RenderTargetTexture, _super);
  44713. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  44714. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  44715. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  44716. if (isCube === void 0) { isCube = false; }
  44717. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44718. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  44719. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  44720. if (isMulti === void 0) { isMulti = false; }
  44721. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  44722. _this.isCube = isCube;
  44723. /**
  44724. * Use this list to define the list of mesh you want to render.
  44725. */
  44726. _this.renderList = new Array();
  44727. _this.renderParticles = true;
  44728. _this.renderSprites = false;
  44729. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  44730. _this.ignoreCameraViewport = false;
  44731. // Events
  44732. /**
  44733. * An event triggered when the texture is unbind.
  44734. * @type {BABYLON.Observable}
  44735. */
  44736. _this.onBeforeBindObservable = new BABYLON.Observable();
  44737. /**
  44738. * An event triggered when the texture is unbind.
  44739. * @type {BABYLON.Observable}
  44740. */
  44741. _this.onAfterUnbindObservable = new BABYLON.Observable();
  44742. /**
  44743. * An event triggered before rendering the texture
  44744. * @type {BABYLON.Observable}
  44745. */
  44746. _this.onBeforeRenderObservable = new BABYLON.Observable();
  44747. /**
  44748. * An event triggered after rendering the texture
  44749. * @type {BABYLON.Observable}
  44750. */
  44751. _this.onAfterRenderObservable = new BABYLON.Observable();
  44752. /**
  44753. * An event triggered after the texture clear
  44754. * @type {BABYLON.Observable}
  44755. */
  44756. _this.onClearObservable = new BABYLON.Observable();
  44757. _this._currentRefreshId = -1;
  44758. _this._refreshRate = 1;
  44759. _this._samples = 1;
  44760. scene = _this.getScene();
  44761. _this.name = name;
  44762. _this.isRenderTarget = true;
  44763. _this._size = size;
  44764. _this._generateMipMaps = generateMipMaps;
  44765. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  44766. // Rendering groups
  44767. _this._renderingManager = new BABYLON.RenderingManager(scene);
  44768. if (isMulti) {
  44769. return _this;
  44770. }
  44771. _this._renderTargetOptions = {
  44772. generateMipMaps: generateMipMaps,
  44773. type: type,
  44774. samplingMode: samplingMode,
  44775. generateDepthBuffer: generateDepthBuffer,
  44776. generateStencilBuffer: generateStencilBuffer
  44777. };
  44778. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  44779. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44780. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44781. }
  44782. if (isCube) {
  44783. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  44784. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  44785. _this._textureMatrix = BABYLON.Matrix.Identity();
  44786. }
  44787. else {
  44788. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  44789. }
  44790. return _this;
  44791. }
  44792. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  44793. get: function () {
  44794. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  44795. },
  44796. enumerable: true,
  44797. configurable: true
  44798. });
  44799. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  44800. get: function () {
  44801. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  44802. },
  44803. enumerable: true,
  44804. configurable: true
  44805. });
  44806. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  44807. get: function () {
  44808. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  44809. },
  44810. enumerable: true,
  44811. configurable: true
  44812. });
  44813. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  44814. set: function (callback) {
  44815. if (this._onAfterUnbindObserver) {
  44816. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  44817. }
  44818. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  44819. },
  44820. enumerable: true,
  44821. configurable: true
  44822. });
  44823. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  44824. set: function (callback) {
  44825. if (this._onBeforeRenderObserver) {
  44826. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  44827. }
  44828. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  44829. },
  44830. enumerable: true,
  44831. configurable: true
  44832. });
  44833. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  44834. set: function (callback) {
  44835. if (this._onAfterRenderObserver) {
  44836. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  44837. }
  44838. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  44839. },
  44840. enumerable: true,
  44841. configurable: true
  44842. });
  44843. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  44844. set: function (callback) {
  44845. if (this._onClearObserver) {
  44846. this.onClearObservable.remove(this._onClearObserver);
  44847. }
  44848. this._onClearObserver = this.onClearObservable.add(callback);
  44849. },
  44850. enumerable: true,
  44851. configurable: true
  44852. });
  44853. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  44854. get: function () {
  44855. return this._renderTargetOptions;
  44856. },
  44857. enumerable: true,
  44858. configurable: true
  44859. });
  44860. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  44861. get: function () {
  44862. return this._samples;
  44863. },
  44864. set: function (value) {
  44865. if (this._samples === value) {
  44866. return;
  44867. }
  44868. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  44869. },
  44870. enumerable: true,
  44871. configurable: true
  44872. });
  44873. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  44874. this._currentRefreshId = -1;
  44875. };
  44876. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  44877. get: function () {
  44878. return this._refreshRate;
  44879. },
  44880. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44881. set: function (value) {
  44882. this._refreshRate = value;
  44883. this.resetRefreshCounter();
  44884. },
  44885. enumerable: true,
  44886. configurable: true
  44887. });
  44888. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  44889. if (!this._postProcessManager) {
  44890. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  44891. this._postProcesses = new Array();
  44892. }
  44893. this._postProcesses.push(postProcess);
  44894. this._postProcesses[0].autoClear = false;
  44895. };
  44896. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  44897. if (!this._postProcesses) {
  44898. return;
  44899. }
  44900. if (dispose) {
  44901. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  44902. var postProcess = _a[_i];
  44903. postProcess.dispose();
  44904. postProcess = null;
  44905. }
  44906. }
  44907. this._postProcesses = [];
  44908. };
  44909. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  44910. if (!this._postProcesses) {
  44911. return;
  44912. }
  44913. var index = this._postProcesses.indexOf(postProcess);
  44914. if (index === -1) {
  44915. return;
  44916. }
  44917. this._postProcesses.splice(index, 1);
  44918. if (this._postProcesses.length > 0) {
  44919. this._postProcesses[0].autoClear = false;
  44920. }
  44921. };
  44922. RenderTargetTexture.prototype._shouldRender = function () {
  44923. if (this._currentRefreshId === -1) {
  44924. this._currentRefreshId = 1;
  44925. return true;
  44926. }
  44927. if (this.refreshRate === this._currentRefreshId) {
  44928. this._currentRefreshId = 1;
  44929. return true;
  44930. }
  44931. this._currentRefreshId++;
  44932. return false;
  44933. };
  44934. RenderTargetTexture.prototype.isReady = function () {
  44935. if (!this.getScene().renderTargetsEnabled) {
  44936. return false;
  44937. }
  44938. return _super.prototype.isReady.call(this);
  44939. };
  44940. RenderTargetTexture.prototype.getRenderSize = function () {
  44941. return this._size;
  44942. };
  44943. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  44944. get: function () {
  44945. return true;
  44946. },
  44947. enumerable: true,
  44948. configurable: true
  44949. });
  44950. RenderTargetTexture.prototype.scale = function (ratio) {
  44951. var newSize = this._size * ratio;
  44952. this.resize(newSize);
  44953. };
  44954. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  44955. if (this.isCube) {
  44956. return this._textureMatrix;
  44957. }
  44958. return _super.prototype.getReflectionTextureMatrix.call(this);
  44959. };
  44960. RenderTargetTexture.prototype.resize = function (size) {
  44961. this.releaseInternalTexture();
  44962. if (this.isCube) {
  44963. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  44964. }
  44965. else {
  44966. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  44967. }
  44968. };
  44969. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  44970. var scene = this.getScene();
  44971. var engine = scene.getEngine();
  44972. if (this.useCameraPostProcesses !== undefined) {
  44973. useCameraPostProcess = this.useCameraPostProcesses;
  44974. }
  44975. if (this._waitingRenderList) {
  44976. this.renderList = [];
  44977. for (var index = 0; index < this._waitingRenderList.length; index++) {
  44978. var id = this._waitingRenderList[index];
  44979. this.renderList.push(scene.getMeshByID(id));
  44980. }
  44981. delete this._waitingRenderList;
  44982. }
  44983. // Is predicate defined?
  44984. if (this.renderListPredicate) {
  44985. this.renderList.splice(0); // Clear previous renderList
  44986. var sceneMeshes = this.getScene().meshes;
  44987. for (var index = 0; index < sceneMeshes.length; index++) {
  44988. var mesh = sceneMeshes[index];
  44989. if (this.renderListPredicate(mesh)) {
  44990. this.renderList.push(mesh);
  44991. }
  44992. }
  44993. }
  44994. if (this.renderList && this.renderList.length === 0) {
  44995. return;
  44996. }
  44997. this.onBeforeBindObservable.notifyObservers(this);
  44998. // Set custom projection.
  44999. // Needs to be before binding to prevent changing the aspect ratio.
  45000. var camera;
  45001. if (this.activeCamera) {
  45002. camera = this.activeCamera;
  45003. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  45004. if (this.activeCamera !== scene.activeCamera) {
  45005. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  45006. }
  45007. }
  45008. else {
  45009. camera = scene.activeCamera;
  45010. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  45011. }
  45012. // Prepare renderingManager
  45013. this._renderingManager.reset();
  45014. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  45015. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  45016. var sceneRenderId = scene.getRenderId();
  45017. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  45018. var mesh = currentRenderList[meshIndex];
  45019. if (mesh) {
  45020. if (!mesh.isReady()) {
  45021. // Reset _currentRefreshId
  45022. this.resetRefreshCounter();
  45023. continue;
  45024. }
  45025. mesh._preActivateForIntermediateRendering(sceneRenderId);
  45026. var isMasked = void 0;
  45027. if (!this.renderList) {
  45028. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  45029. }
  45030. else {
  45031. isMasked = false;
  45032. }
  45033. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  45034. mesh._activate(sceneRenderId);
  45035. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45036. var subMesh = mesh.subMeshes[subIndex];
  45037. scene._activeIndices.addCount(subMesh.indexCount, false);
  45038. this._renderingManager.dispatch(subMesh);
  45039. }
  45040. }
  45041. }
  45042. }
  45043. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  45044. var particleSystem = scene.particleSystems[particleIndex];
  45045. var emitter = particleSystem.emitter;
  45046. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  45047. continue;
  45048. }
  45049. if (currentRenderList.indexOf(emitter) >= 0) {
  45050. this._renderingManager.dispatchParticles(particleSystem);
  45051. }
  45052. }
  45053. if (this.isCube) {
  45054. for (var face = 0; face < 6; face++) {
  45055. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45056. scene.incrementRenderId();
  45057. scene.resetCachedMaterial();
  45058. }
  45059. }
  45060. else {
  45061. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45062. }
  45063. this.onAfterUnbindObservable.notifyObservers(this);
  45064. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  45065. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  45066. }
  45067. engine.setViewport(scene.activeCamera.viewport);
  45068. scene.resetCachedMaterial();
  45069. };
  45070. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  45071. var _this = this;
  45072. var scene = this.getScene();
  45073. var engine = scene.getEngine();
  45074. // Bind
  45075. if (this._postProcessManager) {
  45076. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  45077. }
  45078. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  45079. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  45080. }
  45081. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  45082. // Clear
  45083. if (this.onClearObservable.hasObservers()) {
  45084. this.onClearObservable.notifyObservers(engine);
  45085. }
  45086. else {
  45087. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  45088. }
  45089. if (!this._doNotChangeAspectRatio) {
  45090. scene.updateTransformMatrix(true);
  45091. }
  45092. // Render
  45093. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  45094. if (this._postProcessManager) {
  45095. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  45096. }
  45097. else if (useCameraPostProcess) {
  45098. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  45099. }
  45100. if (!this._doNotChangeAspectRatio) {
  45101. scene.updateTransformMatrix(true);
  45102. }
  45103. // Dump ?
  45104. if (dumpForDebug) {
  45105. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  45106. }
  45107. // Unbind
  45108. if (!this.isCube || faceIndex === 5) {
  45109. if (this.isCube) {
  45110. if (faceIndex === 5) {
  45111. engine.generateMipMapsForCubemap(this._texture);
  45112. }
  45113. }
  45114. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  45115. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  45116. });
  45117. }
  45118. else {
  45119. this.onAfterRenderObservable.notifyObservers(faceIndex);
  45120. }
  45121. };
  45122. /**
  45123. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  45124. * This allowed control for front to back rendering or reversly depending of the special needs.
  45125. *
  45126. * @param renderingGroupId The rendering group id corresponding to its index
  45127. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  45128. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  45129. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  45130. */
  45131. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  45132. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  45133. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  45134. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  45135. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  45136. };
  45137. /**
  45138. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  45139. *
  45140. * @param renderingGroupId The rendering group id corresponding to its index
  45141. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  45142. */
  45143. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  45144. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  45145. };
  45146. RenderTargetTexture.prototype.clone = function () {
  45147. var textureSize = this.getSize();
  45148. 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);
  45149. // Base texture
  45150. newTexture.hasAlpha = this.hasAlpha;
  45151. newTexture.level = this.level;
  45152. // RenderTarget Texture
  45153. newTexture.coordinatesMode = this.coordinatesMode;
  45154. newTexture.renderList = this.renderList.slice(0);
  45155. return newTexture;
  45156. };
  45157. RenderTargetTexture.prototype.serialize = function () {
  45158. if (!this.name) {
  45159. return null;
  45160. }
  45161. var serializationObject = _super.prototype.serialize.call(this);
  45162. serializationObject.renderTargetSize = this.getRenderSize();
  45163. serializationObject.renderList = [];
  45164. for (var index = 0; index < this.renderList.length; index++) {
  45165. serializationObject.renderList.push(this.renderList[index].id);
  45166. }
  45167. return serializationObject;
  45168. };
  45169. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  45170. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  45171. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  45172. };
  45173. RenderTargetTexture.prototype.dispose = function () {
  45174. if (this._postProcessManager) {
  45175. this._postProcessManager.dispose();
  45176. this._postProcessManager = null;
  45177. }
  45178. this.clearPostProcesses(true);
  45179. this.renderList = null;
  45180. // Remove from custom render targets
  45181. var scene = this.getScene();
  45182. var index = scene.customRenderTargets.indexOf(this);
  45183. if (index >= 0) {
  45184. scene.customRenderTargets.splice(index, 1);
  45185. }
  45186. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  45187. var camera = _a[_i];
  45188. index = camera.customRenderTargets.indexOf(this);
  45189. if (index >= 0) {
  45190. camera.customRenderTargets.splice(index, 1);
  45191. }
  45192. }
  45193. _super.prototype.dispose.call(this);
  45194. };
  45195. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  45196. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  45197. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  45198. return RenderTargetTexture;
  45199. }(BABYLON.Texture));
  45200. BABYLON.RenderTargetTexture = RenderTargetTexture;
  45201. })(BABYLON || (BABYLON = {}));
  45202. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  45203. var BABYLON;
  45204. (function (BABYLON) {
  45205. ;
  45206. var MultiRenderTarget = (function (_super) {
  45207. __extends(MultiRenderTarget, _super);
  45208. function MultiRenderTarget(name, size, count, scene, options) {
  45209. var _this = this;
  45210. options = options || {};
  45211. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  45212. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  45213. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  45214. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  45215. if (!_this.isSupported) {
  45216. _this.dispose();
  45217. return;
  45218. }
  45219. var types = [];
  45220. var samplingModes = [];
  45221. for (var i = 0; i < count; i++) {
  45222. if (options.types && options.types[i]) {
  45223. types.push(options.types[i]);
  45224. }
  45225. else {
  45226. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  45227. }
  45228. if (options.samplingModes && options.samplingModes[i]) {
  45229. samplingModes.push(options.samplingModes[i]);
  45230. }
  45231. else {
  45232. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45233. }
  45234. }
  45235. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  45236. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  45237. _this._count = count;
  45238. _this._size = size;
  45239. _this._multiRenderTargetOptions = {
  45240. samplingModes: samplingModes,
  45241. generateMipMaps: generateMipMaps,
  45242. generateDepthBuffer: generateDepthBuffer,
  45243. generateStencilBuffer: generateStencilBuffer,
  45244. generateDepthTexture: generateDepthTexture,
  45245. types: types,
  45246. textureCount: count
  45247. };
  45248. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  45249. _this._createInternalTextures();
  45250. return _this;
  45251. }
  45252. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  45253. get: function () {
  45254. var engine = this.getScene().getEngine();
  45255. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  45256. },
  45257. enumerable: true,
  45258. configurable: true
  45259. });
  45260. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  45261. get: function () {
  45262. return this._textures;
  45263. },
  45264. enumerable: true,
  45265. configurable: true
  45266. });
  45267. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  45268. get: function () {
  45269. return this._textures[this._textures.length - 1];
  45270. },
  45271. enumerable: true,
  45272. configurable: true
  45273. });
  45274. MultiRenderTarget.prototype._createInternalTextures = function () {
  45275. this._textures = [];
  45276. for (var i = 0; i < this._webGLTextures.length; i++) {
  45277. var texture = new BABYLON.Texture(null, this.getScene());
  45278. texture._texture = this._webGLTextures[i];
  45279. this._textures.push(texture);
  45280. }
  45281. // Keeps references to frame buffer and stencil/depth buffer
  45282. this._texture = this._webGLTextures[0];
  45283. };
  45284. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  45285. get: function () {
  45286. return this._samples;
  45287. },
  45288. set: function (value) {
  45289. if (this._samples === value) {
  45290. return;
  45291. }
  45292. for (var i = 0; i < this._webGLTextures.length; i++) {
  45293. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  45294. }
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. MultiRenderTarget.prototype.resize = function (size) {
  45300. this.releaseInternalTextures();
  45301. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  45302. this._createInternalTextures();
  45303. };
  45304. MultiRenderTarget.prototype.dispose = function () {
  45305. this.releaseInternalTextures();
  45306. _super.prototype.dispose.call(this);
  45307. };
  45308. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  45309. if (!this._webGLTextures) {
  45310. return;
  45311. }
  45312. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  45313. if (this._webGLTextures[i] !== undefined) {
  45314. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  45315. this._webGLTextures.splice(i, 1);
  45316. }
  45317. }
  45318. };
  45319. return MultiRenderTarget;
  45320. }(BABYLON.RenderTargetTexture));
  45321. BABYLON.MultiRenderTarget = MultiRenderTarget;
  45322. })(BABYLON || (BABYLON = {}));
  45323. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  45324. /// <reference path="babylon.renderTargetTexture.ts" />
  45325. var BABYLON;
  45326. (function (BABYLON) {
  45327. var MirrorTexture = (function (_super) {
  45328. __extends(MirrorTexture, _super);
  45329. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  45330. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45332. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45333. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  45334. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  45335. _this._transformMatrix = BABYLON.Matrix.Zero();
  45336. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  45337. _this._blurKernelX = 0;
  45338. _this._blurKernelY = 0;
  45339. _this._blurRatio = 1.0;
  45340. _this.onBeforeRenderObservable.add(function () {
  45341. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  45342. _this._savedViewMatrix = scene.getViewMatrix();
  45343. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  45344. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  45345. scene.clipPlane = _this.mirrorPlane;
  45346. scene.getEngine().cullBackFaces = false;
  45347. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  45348. });
  45349. _this.onAfterRenderObservable.add(function () {
  45350. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  45351. scene.getEngine().cullBackFaces = true;
  45352. scene._mirroredCameraPosition = null;
  45353. delete scene.clipPlane;
  45354. });
  45355. return _this;
  45356. }
  45357. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  45358. get: function () {
  45359. return this._blurRatio;
  45360. },
  45361. set: function (value) {
  45362. if (this._blurRatio === value) {
  45363. return;
  45364. }
  45365. this._blurRatio = value;
  45366. this._preparePostProcesses();
  45367. },
  45368. enumerable: true,
  45369. configurable: true
  45370. });
  45371. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  45372. set: function (value) {
  45373. this.blurKernelX = value;
  45374. this.blurKernelY = value;
  45375. },
  45376. enumerable: true,
  45377. configurable: true
  45378. });
  45379. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  45380. get: function () {
  45381. return this._blurKernelX;
  45382. },
  45383. set: function (value) {
  45384. if (this._blurKernelX === value) {
  45385. return;
  45386. }
  45387. this._blurKernelX = value;
  45388. this._preparePostProcesses();
  45389. },
  45390. enumerable: true,
  45391. configurable: true
  45392. });
  45393. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  45394. get: function () {
  45395. return this._blurKernelY;
  45396. },
  45397. set: function (value) {
  45398. if (this._blurKernelY === value) {
  45399. return;
  45400. }
  45401. this._blurKernelY = value;
  45402. this._preparePostProcesses();
  45403. },
  45404. enumerable: true,
  45405. configurable: true
  45406. });
  45407. MirrorTexture.prototype._preparePostProcesses = function () {
  45408. this.clearPostProcesses(true);
  45409. if (this._blurKernelX && this._blurKernelY) {
  45410. var engine = this.getScene().getEngine();
  45411. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45412. 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);
  45413. this._blurX.autoClear = false;
  45414. if (this._blurRatio === 1 && this.samples < 2) {
  45415. this._blurX.outputTexture = this._texture;
  45416. }
  45417. else {
  45418. this._blurX.alwaysForcePOT = true;
  45419. }
  45420. 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);
  45421. this._blurY.autoClear = false;
  45422. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  45423. this.addPostProcess(this._blurX);
  45424. this.addPostProcess(this._blurY);
  45425. }
  45426. };
  45427. MirrorTexture.prototype.clone = function () {
  45428. var textureSize = this.getSize();
  45429. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  45430. // Base texture
  45431. newTexture.hasAlpha = this.hasAlpha;
  45432. newTexture.level = this.level;
  45433. // Mirror Texture
  45434. newTexture.mirrorPlane = this.mirrorPlane.clone();
  45435. newTexture.renderList = this.renderList.slice(0);
  45436. return newTexture;
  45437. };
  45438. MirrorTexture.prototype.serialize = function () {
  45439. if (!this.name) {
  45440. return null;
  45441. }
  45442. var serializationObject = _super.prototype.serialize.call(this);
  45443. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  45444. return serializationObject;
  45445. };
  45446. return MirrorTexture;
  45447. }(BABYLON.RenderTargetTexture));
  45448. BABYLON.MirrorTexture = MirrorTexture;
  45449. })(BABYLON || (BABYLON = {}));
  45450. //# sourceMappingURL=babylon.mirrorTexture.js.map
  45451. /// <reference path="babylon.renderTargetTexture.ts" />
  45452. var BABYLON;
  45453. (function (BABYLON) {
  45454. /**
  45455. * Creates a refraction texture used by refraction channel of the standard material.
  45456. * @param name the texture name
  45457. * @param size size of the underlying texture
  45458. * @param scene root scene
  45459. */
  45460. var RefractionTexture = (function (_super) {
  45461. __extends(RefractionTexture, _super);
  45462. function RefractionTexture(name, size, scene, generateMipMaps) {
  45463. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  45464. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  45465. _this.depth = 2.0;
  45466. _this.onBeforeRenderObservable.add(function () {
  45467. scene.clipPlane = _this.refractionPlane;
  45468. });
  45469. _this.onAfterRenderObservable.add(function () {
  45470. delete scene.clipPlane;
  45471. });
  45472. return _this;
  45473. }
  45474. RefractionTexture.prototype.clone = function () {
  45475. var textureSize = this.getSize();
  45476. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  45477. // Base texture
  45478. newTexture.hasAlpha = this.hasAlpha;
  45479. newTexture.level = this.level;
  45480. // Refraction Texture
  45481. newTexture.refractionPlane = this.refractionPlane.clone();
  45482. newTexture.renderList = this.renderList.slice(0);
  45483. newTexture.depth = this.depth;
  45484. return newTexture;
  45485. };
  45486. RefractionTexture.prototype.serialize = function () {
  45487. if (!this.name) {
  45488. return null;
  45489. }
  45490. var serializationObject = _super.prototype.serialize.call(this);
  45491. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  45492. serializationObject.depth = this.depth;
  45493. return serializationObject;
  45494. };
  45495. return RefractionTexture;
  45496. }(BABYLON.RenderTargetTexture));
  45497. BABYLON.RefractionTexture = RefractionTexture;
  45498. })(BABYLON || (BABYLON = {}));
  45499. //# sourceMappingURL=babylon.refractionTexture.js.map
  45500. /// <reference path="babylon.texture.ts" />
  45501. var BABYLON;
  45502. (function (BABYLON) {
  45503. var DynamicTexture = (function (_super) {
  45504. __extends(DynamicTexture, _super);
  45505. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  45506. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45507. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45508. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  45509. _this.name = name;
  45510. var engine = _this.getScene().getEngine();
  45511. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45512. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45513. _this._generateMipMaps = generateMipMaps;
  45514. if (options.getContext) {
  45515. _this._canvas = options;
  45516. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45517. }
  45518. else {
  45519. _this._canvas = document.createElement("canvas");
  45520. if (options.width) {
  45521. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45522. }
  45523. else {
  45524. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  45525. }
  45526. }
  45527. var textureSize = _this.getSize();
  45528. _this._canvas.width = textureSize.width;
  45529. _this._canvas.height = textureSize.height;
  45530. _this._context = _this._canvas.getContext("2d");
  45531. return _this;
  45532. }
  45533. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  45534. get: function () {
  45535. return true;
  45536. },
  45537. enumerable: true,
  45538. configurable: true
  45539. });
  45540. DynamicTexture.prototype._recreate = function (textureSize) {
  45541. this._canvas.width = textureSize.width;
  45542. this._canvas.height = textureSize.height;
  45543. this.releaseInternalTexture();
  45544. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  45545. };
  45546. DynamicTexture.prototype.scale = function (ratio) {
  45547. var textureSize = this.getSize();
  45548. textureSize.width *= ratio;
  45549. textureSize.height *= ratio;
  45550. this._recreate(textureSize);
  45551. };
  45552. DynamicTexture.prototype.scaleTo = function (width, height) {
  45553. var textureSize = this.getSize();
  45554. textureSize.width = width;
  45555. textureSize.height = height;
  45556. this._recreate(textureSize);
  45557. };
  45558. DynamicTexture.prototype.getContext = function () {
  45559. return this._context;
  45560. };
  45561. DynamicTexture.prototype.clear = function () {
  45562. var size = this.getSize();
  45563. this._context.fillRect(0, 0, size.width, size.height);
  45564. };
  45565. DynamicTexture.prototype.update = function (invertY) {
  45566. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  45567. };
  45568. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  45569. if (update === void 0) { update = true; }
  45570. var size = this.getSize();
  45571. if (clearColor) {
  45572. this._context.fillStyle = clearColor;
  45573. this._context.fillRect(0, 0, size.width, size.height);
  45574. }
  45575. this._context.font = font;
  45576. if (x === null || x === undefined) {
  45577. var textSize = this._context.measureText(text);
  45578. x = (size.width - textSize.width) / 2;
  45579. }
  45580. if (y === null || y === undefined) {
  45581. var fontSize = parseInt((font.replace(/\D/g, '')));
  45582. ;
  45583. y = (size.height / 2) + (fontSize / 3.65);
  45584. }
  45585. this._context.fillStyle = color;
  45586. this._context.fillText(text, x, y);
  45587. if (update) {
  45588. this.update(invertY);
  45589. }
  45590. };
  45591. DynamicTexture.prototype.clone = function () {
  45592. var textureSize = this.getSize();
  45593. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  45594. // Base texture
  45595. newTexture.hasAlpha = this.hasAlpha;
  45596. newTexture.level = this.level;
  45597. // Dynamic Texture
  45598. newTexture.wrapU = this.wrapU;
  45599. newTexture.wrapV = this.wrapV;
  45600. return newTexture;
  45601. };
  45602. return DynamicTexture;
  45603. }(BABYLON.Texture));
  45604. BABYLON.DynamicTexture = DynamicTexture;
  45605. })(BABYLON || (BABYLON = {}));
  45606. //# sourceMappingURL=babylon.dynamicTexture.js.map
  45607. var BABYLON;
  45608. (function (BABYLON) {
  45609. var VideoTexture = (function (_super) {
  45610. __extends(VideoTexture, _super);
  45611. /**
  45612. * Creates a video texture.
  45613. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  45614. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  45615. * @param {BABYLON.Scene} scene is obviously the current scene.
  45616. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  45617. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  45618. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  45619. */
  45620. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  45621. if (generateMipMaps === void 0) { generateMipMaps = false; }
  45622. if (invertY === void 0) { invertY = false; }
  45623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45624. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45625. _this._autoLaunch = true;
  45626. var urls;
  45627. _this.name = name;
  45628. if (urlsOrVideo instanceof HTMLVideoElement) {
  45629. _this.video = urlsOrVideo;
  45630. }
  45631. else {
  45632. urls = urlsOrVideo;
  45633. _this.video = document.createElement("video");
  45634. _this.video.autoplay = false;
  45635. _this.video.loop = true;
  45636. }
  45637. _this._generateMipMaps = generateMipMaps;
  45638. _this._samplingMode = samplingMode;
  45639. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  45640. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45641. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45642. }
  45643. else {
  45644. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45645. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45646. _this._generateMipMaps = false;
  45647. }
  45648. if (urls) {
  45649. _this.video.addEventListener("canplay", function () {
  45650. _this._createTexture();
  45651. });
  45652. urls.forEach(function (url) {
  45653. var source = document.createElement("source");
  45654. source.src = url;
  45655. _this.video.appendChild(source);
  45656. });
  45657. }
  45658. else {
  45659. _this._createTexture();
  45660. }
  45661. _this._lastUpdate = BABYLON.Tools.Now;
  45662. return _this;
  45663. }
  45664. VideoTexture.prototype.__setTextureReady = function () {
  45665. this._texture.isReady = true;
  45666. };
  45667. VideoTexture.prototype._createTexture = function () {
  45668. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  45669. if (this._autoLaunch) {
  45670. this._autoLaunch = false;
  45671. this.video.play();
  45672. }
  45673. this._setTextureReady = this.__setTextureReady.bind(this);
  45674. this.video.addEventListener("playing", this._setTextureReady);
  45675. };
  45676. VideoTexture.prototype.update = function () {
  45677. var now = BABYLON.Tools.Now;
  45678. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  45679. return false;
  45680. }
  45681. this._lastUpdate = now;
  45682. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  45683. return true;
  45684. };
  45685. VideoTexture.prototype.dispose = function () {
  45686. _super.prototype.dispose.call(this);
  45687. this.video.removeEventListener("playing", this._setTextureReady);
  45688. };
  45689. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  45690. var video = document.createElement("video");
  45691. var constraintsDeviceId;
  45692. if (constraints && constraints.deviceId) {
  45693. constraintsDeviceId = {
  45694. exact: constraints.deviceId
  45695. };
  45696. }
  45697. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  45698. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  45699. if (navigator.getUserMedia) {
  45700. navigator.getUserMedia({
  45701. video: {
  45702. deviceId: constraintsDeviceId,
  45703. width: {
  45704. min: (constraints && constraints.minWidth) || 256,
  45705. max: (constraints && constraints.maxWidth) || 640
  45706. },
  45707. height: {
  45708. min: (constraints && constraints.minHeight) || 256,
  45709. max: (constraints && constraints.maxHeight) || 480
  45710. }
  45711. }
  45712. }, function (stream) {
  45713. if (video.mozSrcObject !== undefined) {
  45714. video.mozSrcObject = stream;
  45715. }
  45716. else {
  45717. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  45718. }
  45719. video.play();
  45720. if (onReady) {
  45721. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  45722. }
  45723. }, function (e) {
  45724. BABYLON.Tools.Error(e.name);
  45725. });
  45726. }
  45727. };
  45728. return VideoTexture;
  45729. }(BABYLON.Texture));
  45730. BABYLON.VideoTexture = VideoTexture;
  45731. })(BABYLON || (BABYLON = {}));
  45732. //# sourceMappingURL=babylon.videoTexture.js.map
  45733. var BABYLON;
  45734. (function (BABYLON) {
  45735. var RawTexture = (function (_super) {
  45736. __extends(RawTexture, _super);
  45737. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45738. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45739. if (invertY === void 0) { invertY = false; }
  45740. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45741. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45742. _this.format = format;
  45743. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45744. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45745. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45746. return _this;
  45747. }
  45748. RawTexture.prototype.update = function (data) {
  45749. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45750. };
  45751. // Statics
  45752. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45753. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45754. if (invertY === void 0) { invertY = false; }
  45755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45756. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45757. };
  45758. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45759. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45760. if (invertY === void 0) { invertY = false; }
  45761. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45762. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45763. };
  45764. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45765. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45766. if (invertY === void 0) { invertY = false; }
  45767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45768. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45769. };
  45770. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45771. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45772. if (invertY === void 0) { invertY = false; }
  45773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45774. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45775. };
  45776. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45777. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45778. if (invertY === void 0) { invertY = false; }
  45779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45780. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45781. };
  45782. return RawTexture;
  45783. }(BABYLON.Texture));
  45784. BABYLON.RawTexture = RawTexture;
  45785. })(BABYLON || (BABYLON = {}));
  45786. //# sourceMappingURL=babylon.rawTexture.js.map
  45787. var BABYLON;
  45788. (function (BABYLON) {
  45789. var PostProcess = (function () {
  45790. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  45791. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  45792. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45793. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  45794. if (blockCompilation === void 0) { blockCompilation = false; }
  45795. this.name = name;
  45796. this.width = -1;
  45797. this.height = -1;
  45798. this.autoClear = true;
  45799. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  45800. /*
  45801. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  45802. Can only be used on a single postprocess or on the last one of a chain.
  45803. */
  45804. this.enablePixelPerfectMode = false;
  45805. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  45806. this.alwaysForcePOT = false;
  45807. this.samples = 1;
  45808. this._reusable = false;
  45809. this._textures = new BABYLON.SmartArray(2);
  45810. this._currentRenderTextureInd = 0;
  45811. this._scaleRatio = new BABYLON.Vector2(1, 1);
  45812. this._texelSize = BABYLON.Vector2.Zero();
  45813. // Events
  45814. /**
  45815. * An event triggered when the postprocess is activated.
  45816. * @type {BABYLON.Observable}
  45817. */
  45818. this.onActivateObservable = new BABYLON.Observable();
  45819. /**
  45820. * An event triggered when the postprocess changes its size.
  45821. * @type {BABYLON.Observable}
  45822. */
  45823. this.onSizeChangedObservable = new BABYLON.Observable();
  45824. /**
  45825. * An event triggered when the postprocess applies its effect.
  45826. * @type {BABYLON.Observable}
  45827. */
  45828. this.onApplyObservable = new BABYLON.Observable();
  45829. /**
  45830. * An event triggered before rendering the postprocess
  45831. * @type {BABYLON.Observable}
  45832. */
  45833. this.onBeforeRenderObservable = new BABYLON.Observable();
  45834. /**
  45835. * An event triggered after rendering the postprocess
  45836. * @type {BABYLON.Observable}
  45837. */
  45838. this.onAfterRenderObservable = new BABYLON.Observable();
  45839. if (camera != null) {
  45840. this._camera = camera;
  45841. this._scene = camera.getScene();
  45842. camera.attachPostProcess(this);
  45843. this._engine = this._scene.getEngine();
  45844. }
  45845. else {
  45846. this._engine = engine;
  45847. }
  45848. this._options = options;
  45849. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  45850. this._reusable = reusable || false;
  45851. this._textureType = textureType;
  45852. this._samplers = samplers || [];
  45853. this._samplers.push("textureSampler");
  45854. this._fragmentUrl = fragmentUrl;
  45855. this._vertexUrl = vertexUrl;
  45856. this._parameters = parameters || [];
  45857. this._parameters.push("scale");
  45858. this._indexParameters = indexParameters;
  45859. if (!blockCompilation) {
  45860. this.updateEffect(defines);
  45861. }
  45862. }
  45863. Object.defineProperty(PostProcess.prototype, "onActivate", {
  45864. set: function (callback) {
  45865. if (this._onActivateObserver) {
  45866. this.onActivateObservable.remove(this._onActivateObserver);
  45867. }
  45868. this._onActivateObserver = this.onActivateObservable.add(callback);
  45869. },
  45870. enumerable: true,
  45871. configurable: true
  45872. });
  45873. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  45874. set: function (callback) {
  45875. if (this._onSizeChangedObserver) {
  45876. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  45877. }
  45878. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  45879. },
  45880. enumerable: true,
  45881. configurable: true
  45882. });
  45883. Object.defineProperty(PostProcess.prototype, "onApply", {
  45884. set: function (callback) {
  45885. if (this._onApplyObserver) {
  45886. this.onApplyObservable.remove(this._onApplyObserver);
  45887. }
  45888. this._onApplyObserver = this.onApplyObservable.add(callback);
  45889. },
  45890. enumerable: true,
  45891. configurable: true
  45892. });
  45893. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  45894. set: function (callback) {
  45895. if (this._onBeforeRenderObserver) {
  45896. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45897. }
  45898. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45899. },
  45900. enumerable: true,
  45901. configurable: true
  45902. });
  45903. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  45904. set: function (callback) {
  45905. if (this._onAfterRenderObserver) {
  45906. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45907. }
  45908. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45909. },
  45910. enumerable: true,
  45911. configurable: true
  45912. });
  45913. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  45914. get: function () {
  45915. return this._textures.data[this._currentRenderTextureInd];
  45916. },
  45917. set: function (value) {
  45918. this._forcedOutputTexture = value;
  45919. },
  45920. enumerable: true,
  45921. configurable: true
  45922. });
  45923. PostProcess.prototype.getCamera = function () {
  45924. return this._camera;
  45925. };
  45926. Object.defineProperty(PostProcess.prototype, "texelSize", {
  45927. get: function () {
  45928. if (this._shareOutputWithPostProcess) {
  45929. return this._shareOutputWithPostProcess.texelSize;
  45930. }
  45931. if (this._forcedOutputTexture) {
  45932. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  45933. }
  45934. return this._texelSize;
  45935. },
  45936. enumerable: true,
  45937. configurable: true
  45938. });
  45939. PostProcess.prototype.getEngine = function () {
  45940. return this._engine;
  45941. };
  45942. PostProcess.prototype.getEffect = function () {
  45943. return this._effect;
  45944. };
  45945. PostProcess.prototype.shareOutputWith = function (postProcess) {
  45946. this._disposeTextures();
  45947. this._shareOutputWithPostProcess = postProcess;
  45948. return this;
  45949. };
  45950. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  45951. 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);
  45952. };
  45953. PostProcess.prototype.isReusable = function () {
  45954. return this._reusable;
  45955. };
  45956. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  45957. PostProcess.prototype.markTextureDirty = function () {
  45958. this.width = -1;
  45959. };
  45960. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  45961. var _this = this;
  45962. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  45963. camera = camera || this._camera;
  45964. var scene = camera.getScene();
  45965. var engine = scene.getEngine();
  45966. var maxSize = engine.getCaps().maxTextureSize;
  45967. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  45968. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  45969. var desiredWidth = this._options.width || requiredWidth;
  45970. var desiredHeight = this._options.height || requiredHeight;
  45971. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  45972. if (!this._options.width) {
  45973. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  45974. }
  45975. if (!this._options.height) {
  45976. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  45977. }
  45978. }
  45979. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  45980. if (this._textures.length > 0) {
  45981. for (var i = 0; i < this._textures.length; i++) {
  45982. this._engine._releaseTexture(this._textures.data[i]);
  45983. }
  45984. this._textures.reset();
  45985. }
  45986. this.width = desiredWidth;
  45987. this.height = desiredHeight;
  45988. var textureSize = { width: this.width, height: this.height };
  45989. var textureOptions = {
  45990. generateMipMaps: false,
  45991. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  45992. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  45993. samplingMode: this.renderTargetSamplingMode,
  45994. type: this._textureType
  45995. };
  45996. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  45997. if (this._reusable) {
  45998. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  45999. }
  46000. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  46001. this.onSizeChangedObservable.notifyObservers(this);
  46002. }
  46003. this._textures.forEach(function (texture) {
  46004. if (texture.samples !== _this.samples) {
  46005. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  46006. }
  46007. });
  46008. }
  46009. var target;
  46010. if (this._shareOutputWithPostProcess) {
  46011. target = this._shareOutputWithPostProcess.outputTexture;
  46012. }
  46013. else if (this._forcedOutputTexture) {
  46014. target = this._forcedOutputTexture;
  46015. this.width = this._forcedOutputTexture._width;
  46016. this.height = this._forcedOutputTexture._height;
  46017. }
  46018. else {
  46019. target = this.outputTexture;
  46020. }
  46021. if (this.enablePixelPerfectMode) {
  46022. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  46023. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  46024. }
  46025. else {
  46026. this._scaleRatio.copyFromFloats(1, 1);
  46027. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  46028. }
  46029. this.onActivateObservable.notifyObservers(camera);
  46030. // Clear
  46031. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  46032. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  46033. }
  46034. if (this._reusable) {
  46035. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  46036. }
  46037. };
  46038. Object.defineProperty(PostProcess.prototype, "isSupported", {
  46039. get: function () {
  46040. return this._effect.isSupported;
  46041. },
  46042. enumerable: true,
  46043. configurable: true
  46044. });
  46045. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  46046. get: function () {
  46047. if (this._shareOutputWithPostProcess) {
  46048. return this._shareOutputWithPostProcess.aspectRatio;
  46049. }
  46050. if (this._forcedOutputTexture) {
  46051. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  46052. }
  46053. return this.width / this.height;
  46054. },
  46055. enumerable: true,
  46056. configurable: true
  46057. });
  46058. PostProcess.prototype.apply = function () {
  46059. // Check
  46060. if (!this._effect || !this._effect.isReady())
  46061. return null;
  46062. // States
  46063. this._engine.enableEffect(this._effect);
  46064. this._engine.setState(false);
  46065. this._engine.setDepthBuffer(false);
  46066. this._engine.setDepthWrite(false);
  46067. // Alpha
  46068. this._engine.setAlphaMode(this.alphaMode);
  46069. if (this.alphaConstants) {
  46070. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  46071. }
  46072. // Texture
  46073. var source;
  46074. if (this._shareOutputWithPostProcess) {
  46075. source = this._shareOutputWithPostProcess.outputTexture;
  46076. }
  46077. else if (this._forcedOutputTexture) {
  46078. source = this._forcedOutputTexture;
  46079. }
  46080. else {
  46081. source = this.outputTexture;
  46082. }
  46083. this._effect._bindTexture("textureSampler", source);
  46084. // Parameters
  46085. this._effect.setVector2("scale", this._scaleRatio);
  46086. this.onApplyObservable.notifyObservers(this._effect);
  46087. return this._effect;
  46088. };
  46089. PostProcess.prototype._disposeTextures = function () {
  46090. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  46091. return;
  46092. }
  46093. if (this._textures.length > 0) {
  46094. for (var i = 0; i < this._textures.length; i++) {
  46095. this._engine._releaseTexture(this._textures.data[i]);
  46096. }
  46097. }
  46098. this._textures.dispose();
  46099. };
  46100. PostProcess.prototype.dispose = function (camera) {
  46101. camera = camera || this._camera;
  46102. this._disposeTextures();
  46103. if (!camera) {
  46104. return;
  46105. }
  46106. camera.detachPostProcess(this);
  46107. var index = camera._postProcesses.indexOf(this);
  46108. if (index === 0 && camera._postProcesses.length > 0) {
  46109. this._camera._postProcesses[0].markTextureDirty();
  46110. }
  46111. this.onActivateObservable.clear();
  46112. this.onAfterRenderObservable.clear();
  46113. this.onApplyObservable.clear();
  46114. this.onBeforeRenderObservable.clear();
  46115. this.onSizeChangedObservable.clear();
  46116. };
  46117. return PostProcess;
  46118. }());
  46119. BABYLON.PostProcess = PostProcess;
  46120. })(BABYLON || (BABYLON = {}));
  46121. //# sourceMappingURL=babylon.postProcess.js.map
  46122. var BABYLON;
  46123. (function (BABYLON) {
  46124. var PassPostProcess = (function (_super) {
  46125. __extends(PassPostProcess, _super);
  46126. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  46127. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46128. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  46129. }
  46130. return PassPostProcess;
  46131. }(BABYLON.PostProcess));
  46132. BABYLON.PassPostProcess = PassPostProcess;
  46133. })(BABYLON || (BABYLON = {}));
  46134. //# sourceMappingURL=babylon.passPostProcess.js.map
  46135. var BABYLON;
  46136. (function (BABYLON) {
  46137. var ShadowGenerator = (function () {
  46138. /**
  46139. * Creates a ShadowGenerator object.
  46140. * A ShadowGenerator is the required tool to use the shadows.
  46141. * Each light casting shadows needs to use its own ShadowGenerator.
  46142. * Required parameters :
  46143. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  46144. * - `light`: the light object generating the shadows.
  46145. * - `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.
  46146. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  46147. */
  46148. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  46149. // Members
  46150. this._bias = 0.00005;
  46151. this._blurBoxOffset = 1;
  46152. this._blurScale = 2;
  46153. this._blurKernel = 1;
  46154. this._useKernelBlur = false;
  46155. this._filter = ShadowGenerator.FILTER_NONE;
  46156. this._darkness = 0;
  46157. this._transparencyShadow = false;
  46158. /**
  46159. * Controls the extent to which the shadows fade out at the edge of the frustum
  46160. * Used only by directionals and spots
  46161. */
  46162. this.frustumEdgeFalloff = 0;
  46163. this.forceBackFacesOnly = false;
  46164. this._lightDirection = BABYLON.Vector3.Zero();
  46165. this._viewMatrix = BABYLON.Matrix.Zero();
  46166. this._projectionMatrix = BABYLON.Matrix.Zero();
  46167. this._transformMatrix = BABYLON.Matrix.Zero();
  46168. this._worldViewProjection = BABYLON.Matrix.Zero();
  46169. this._currentFaceIndex = 0;
  46170. this._currentFaceIndexCache = 0;
  46171. this._isCube = false;
  46172. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  46173. this._mapSize = mapSize;
  46174. this._light = light;
  46175. this._scene = light.getScene();
  46176. light._shadowGenerator = this;
  46177. // Texture type fallback from float to int if not supported.
  46178. var caps = this._scene.getEngine().getCaps();
  46179. if (!useFullFloatFirst) {
  46180. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  46181. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46182. }
  46183. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  46184. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46185. }
  46186. else {
  46187. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46188. }
  46189. }
  46190. else {
  46191. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  46192. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46193. }
  46194. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  46195. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46196. }
  46197. else {
  46198. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46199. }
  46200. }
  46201. this._initializeGenerator();
  46202. }
  46203. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  46204. // Static
  46205. get: function () {
  46206. return ShadowGenerator._FILTER_NONE;
  46207. },
  46208. enumerable: true,
  46209. configurable: true
  46210. });
  46211. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  46212. get: function () {
  46213. return ShadowGenerator._FILTER_POISSONSAMPLING;
  46214. },
  46215. enumerable: true,
  46216. configurable: true
  46217. });
  46218. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  46219. get: function () {
  46220. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  46221. },
  46222. enumerable: true,
  46223. configurable: true
  46224. });
  46225. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  46226. get: function () {
  46227. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  46228. },
  46229. enumerable: true,
  46230. configurable: true
  46231. });
  46232. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  46233. get: function () {
  46234. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  46235. },
  46236. enumerable: true,
  46237. configurable: true
  46238. });
  46239. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  46240. get: function () {
  46241. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  46242. },
  46243. enumerable: true,
  46244. configurable: true
  46245. });
  46246. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  46247. get: function () {
  46248. return this._bias;
  46249. },
  46250. set: function (bias) {
  46251. this._bias = bias;
  46252. },
  46253. enumerable: true,
  46254. configurable: true
  46255. });
  46256. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  46257. get: function () {
  46258. return this._blurBoxOffset;
  46259. },
  46260. set: function (value) {
  46261. if (this._blurBoxOffset === value) {
  46262. return;
  46263. }
  46264. this._blurBoxOffset = value;
  46265. this._disposeBlurPostProcesses();
  46266. },
  46267. enumerable: true,
  46268. configurable: true
  46269. });
  46270. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  46271. get: function () {
  46272. return this._blurScale;
  46273. },
  46274. set: function (value) {
  46275. if (this._blurScale === value) {
  46276. return;
  46277. }
  46278. this._blurScale = value;
  46279. this._disposeBlurPostProcesses();
  46280. },
  46281. enumerable: true,
  46282. configurable: true
  46283. });
  46284. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  46285. get: function () {
  46286. return this._blurKernel;
  46287. },
  46288. set: function (value) {
  46289. if (this._blurKernel === value) {
  46290. return;
  46291. }
  46292. this._blurKernel = value;
  46293. this._disposeBlurPostProcesses();
  46294. },
  46295. enumerable: true,
  46296. configurable: true
  46297. });
  46298. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  46299. get: function () {
  46300. return this._useKernelBlur;
  46301. },
  46302. set: function (value) {
  46303. if (this._useKernelBlur === value) {
  46304. return;
  46305. }
  46306. this._useKernelBlur = value;
  46307. this._disposeBlurPostProcesses();
  46308. },
  46309. enumerable: true,
  46310. configurable: true
  46311. });
  46312. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  46313. get: function () {
  46314. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  46315. },
  46316. set: function (value) {
  46317. this._depthScale = value;
  46318. },
  46319. enumerable: true,
  46320. configurable: true
  46321. });
  46322. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  46323. get: function () {
  46324. return this._filter;
  46325. },
  46326. set: function (value) {
  46327. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  46328. if (this._light.needCube()) {
  46329. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  46330. this.useExponentialShadowMap = true;
  46331. return;
  46332. }
  46333. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  46334. this.useCloseExponentialShadowMap = true;
  46335. return;
  46336. }
  46337. }
  46338. if (this._filter === value) {
  46339. return;
  46340. }
  46341. this._filter = value;
  46342. this._disposeBlurPostProcesses();
  46343. this._applyFilterValues();
  46344. this._light._markMeshesAsLightDirty();
  46345. },
  46346. enumerable: true,
  46347. configurable: true
  46348. });
  46349. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  46350. get: function () {
  46351. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  46352. },
  46353. set: function (value) {
  46354. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  46355. },
  46356. enumerable: true,
  46357. configurable: true
  46358. });
  46359. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  46360. get: function () {
  46361. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46362. return this.useExponentialShadowMap;
  46363. },
  46364. set: function (value) {
  46365. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46366. this.useExponentialShadowMap = value;
  46367. },
  46368. enumerable: true,
  46369. configurable: true
  46370. });
  46371. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  46372. get: function () {
  46373. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46374. return this.useBlurExponentialShadowMap;
  46375. },
  46376. set: function (value) {
  46377. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46378. this.useBlurExponentialShadowMap = value;
  46379. },
  46380. enumerable: true,
  46381. configurable: true
  46382. });
  46383. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  46384. get: function () {
  46385. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  46386. },
  46387. set: function (value) {
  46388. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46389. },
  46390. enumerable: true,
  46391. configurable: true
  46392. });
  46393. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  46394. get: function () {
  46395. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  46396. },
  46397. set: function (value) {
  46398. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46399. },
  46400. enumerable: true,
  46401. configurable: true
  46402. });
  46403. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  46404. get: function () {
  46405. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  46406. },
  46407. set: function (value) {
  46408. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46409. },
  46410. enumerable: true,
  46411. configurable: true
  46412. });
  46413. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  46414. get: function () {
  46415. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  46416. },
  46417. set: function (value) {
  46418. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46419. },
  46420. enumerable: true,
  46421. configurable: true
  46422. });
  46423. /**
  46424. * Returns the darkness value (float).
  46425. */
  46426. ShadowGenerator.prototype.getDarkness = function () {
  46427. return this._darkness;
  46428. };
  46429. /**
  46430. * Sets the ShadowGenerator darkness value (float <= 1.0).
  46431. * Returns the ShadowGenerator.
  46432. */
  46433. ShadowGenerator.prototype.setDarkness = function (darkness) {
  46434. if (darkness >= 1.0)
  46435. this._darkness = 1.0;
  46436. else if (darkness <= 0.0)
  46437. this._darkness = 0.0;
  46438. else
  46439. this._darkness = darkness;
  46440. return this;
  46441. };
  46442. /**
  46443. * Sets the ability to have transparent shadow (boolean).
  46444. * Returns the ShadowGenerator.
  46445. */
  46446. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  46447. this._transparencyShadow = hasShadow;
  46448. return this;
  46449. };
  46450. /**
  46451. * Returns a RenderTargetTexture object : the shadow map texture.
  46452. */
  46453. ShadowGenerator.prototype.getShadowMap = function () {
  46454. return this._shadowMap;
  46455. };
  46456. /**
  46457. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  46458. */
  46459. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  46460. if (this._shadowMap2) {
  46461. return this._shadowMap2;
  46462. }
  46463. return this._shadowMap;
  46464. };
  46465. /**
  46466. * Returns the associated light object.
  46467. */
  46468. ShadowGenerator.prototype.getLight = function () {
  46469. return this._light;
  46470. };
  46471. ShadowGenerator.prototype._initializeGenerator = function () {
  46472. this._light._markMeshesAsLightDirty();
  46473. this._initializeShadowMap();
  46474. };
  46475. ShadowGenerator.prototype._initializeShadowMap = function () {
  46476. var _this = this;
  46477. // Render target
  46478. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  46479. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46480. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46481. this._shadowMap.anisotropicFilteringLevel = 1;
  46482. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46483. this._shadowMap.renderParticles = false;
  46484. // Record Face Index before render.
  46485. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  46486. _this._currentFaceIndex = faceIndex;
  46487. });
  46488. // Custom render function.
  46489. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  46490. // Blur if required afer render.
  46491. this._shadowMap.onAfterUnbindObservable.add(function () {
  46492. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  46493. return;
  46494. }
  46495. if (!_this._blurPostProcesses) {
  46496. _this._initializeBlurRTTAndPostProcesses();
  46497. }
  46498. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  46499. });
  46500. // Clear according to the chosen filter.
  46501. this._shadowMap.onClearObservable.add(function (engine) {
  46502. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  46503. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  46504. }
  46505. else {
  46506. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46507. }
  46508. });
  46509. };
  46510. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  46511. var _this = this;
  46512. var engine = this._scene.getEngine();
  46513. var targetSize = this._mapSize / this.blurScale;
  46514. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  46515. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  46516. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46517. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46518. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46519. }
  46520. if (this.useKernelBlur) {
  46521. 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);
  46522. this._kernelBlurXPostprocess.width = targetSize;
  46523. this._kernelBlurXPostprocess.height = targetSize;
  46524. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  46525. effect.setTexture("textureSampler", _this._shadowMap);
  46526. });
  46527. 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);
  46528. this._kernelBlurXPostprocess.autoClear = false;
  46529. this._kernelBlurYPostprocess.autoClear = false;
  46530. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46531. this._kernelBlurXPostprocess.packedFloat = true;
  46532. this._kernelBlurYPostprocess.packedFloat = true;
  46533. }
  46534. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  46535. }
  46536. else {
  46537. 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);
  46538. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  46539. effect.setFloat2("screenSize", targetSize, targetSize);
  46540. effect.setTexture("textureSampler", _this._shadowMap);
  46541. });
  46542. this._boxBlurPostprocess.autoClear = false;
  46543. this._blurPostProcesses = [this._boxBlurPostprocess];
  46544. }
  46545. };
  46546. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46547. var index;
  46548. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46549. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  46550. }
  46551. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46552. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  46553. }
  46554. if (this._transparencyShadow) {
  46555. for (index = 0; index < transparentSubMeshes.length; index++) {
  46556. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  46557. }
  46558. }
  46559. };
  46560. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  46561. var _this = this;
  46562. var mesh = subMesh.getRenderingMesh();
  46563. var scene = this._scene;
  46564. var engine = scene.getEngine();
  46565. // Culling
  46566. engine.setState(subMesh.getMaterial().backFaceCulling);
  46567. // Managing instances
  46568. var batch = mesh._getInstancesRenderList(subMesh._id);
  46569. if (batch.mustReturn) {
  46570. return;
  46571. }
  46572. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  46573. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  46574. engine.enableEffect(this._effect);
  46575. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  46576. var material = subMesh.getMaterial();
  46577. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  46578. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  46579. this._effect.setVector3("lightPosition", this.getLight().position);
  46580. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  46581. // Alpha test
  46582. if (material && material.needAlphaTesting()) {
  46583. var alphaTexture = material.getAlphaTestTexture();
  46584. if (alphaTexture) {
  46585. this._effect.setTexture("diffuseSampler", alphaTexture);
  46586. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  46587. }
  46588. }
  46589. // Bones
  46590. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46591. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46592. }
  46593. if (this.forceBackFacesOnly) {
  46594. engine.setState(true, 0, false, true);
  46595. }
  46596. // Draw
  46597. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46598. if (this.forceBackFacesOnly) {
  46599. engine.setState(true, 0, false, false);
  46600. }
  46601. }
  46602. else {
  46603. // Need to reset refresh rate of the shadowMap
  46604. this._shadowMap.resetRefreshCounter();
  46605. }
  46606. };
  46607. ShadowGenerator.prototype._applyFilterValues = function () {
  46608. if (this.filter === ShadowGenerator.FILTER_NONE) {
  46609. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  46610. }
  46611. else {
  46612. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46613. }
  46614. };
  46615. /**
  46616. * Force shader compilation including textures ready check
  46617. */
  46618. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  46619. var _this = this;
  46620. var scene = this._scene;
  46621. var engine = scene.getEngine();
  46622. var subMeshes = new Array();
  46623. var currentIndex = 0;
  46624. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  46625. var mesh = _a[_i];
  46626. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  46627. }
  46628. var checkReady = function () {
  46629. if (!_this._scene || !_this._scene.getEngine()) {
  46630. return;
  46631. }
  46632. var subMesh = subMeshes[currentIndex];
  46633. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  46634. currentIndex++;
  46635. if (currentIndex >= subMeshes.length) {
  46636. if (onCompiled) {
  46637. onCompiled(_this);
  46638. }
  46639. return;
  46640. }
  46641. }
  46642. setTimeout(checkReady, 16);
  46643. };
  46644. if (subMeshes.length > 0) {
  46645. checkReady();
  46646. }
  46647. };
  46648. /**
  46649. * Boolean : true when the ShadowGenerator is finally computed.
  46650. */
  46651. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  46652. var defines = [];
  46653. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46654. defines.push("#define FLOAT");
  46655. }
  46656. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  46657. defines.push("#define ESM");
  46658. }
  46659. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46660. var mesh = subMesh.getMesh();
  46661. var material = subMesh.getMaterial();
  46662. // Alpha test
  46663. if (material && material.needAlphaTesting()) {
  46664. var alphaTexture = material.getAlphaTestTexture();
  46665. if (alphaTexture) {
  46666. defines.push("#define ALPHATEST");
  46667. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46668. attribs.push(BABYLON.VertexBuffer.UVKind);
  46669. defines.push("#define UV1");
  46670. }
  46671. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46672. if (alphaTexture.coordinatesIndex === 1) {
  46673. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46674. defines.push("#define UV2");
  46675. }
  46676. }
  46677. }
  46678. }
  46679. // Bones
  46680. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46681. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46682. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46683. if (mesh.numBoneInfluencers > 4) {
  46684. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46685. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46686. }
  46687. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46688. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46689. }
  46690. else {
  46691. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46692. }
  46693. // Instances
  46694. if (useInstances) {
  46695. defines.push("#define INSTANCES");
  46696. attribs.push("world0");
  46697. attribs.push("world1");
  46698. attribs.push("world2");
  46699. attribs.push("world3");
  46700. }
  46701. // Get correct effect
  46702. var join = defines.join("\n");
  46703. if (this._cachedDefines !== join) {
  46704. this._cachedDefines = join;
  46705. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  46706. }
  46707. return this._effect.isReady();
  46708. };
  46709. /**
  46710. * This creates the defines related to the standard BJS materials.
  46711. */
  46712. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  46713. var scene = this._scene;
  46714. var light = this._light;
  46715. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  46716. return;
  46717. }
  46718. defines["SHADOW" + lightIndex] = true;
  46719. if (this.usePoissonSampling) {
  46720. defines["SHADOWPCF" + lightIndex] = true;
  46721. }
  46722. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  46723. defines["SHADOWESM" + lightIndex] = true;
  46724. }
  46725. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  46726. defines["SHADOWCLOSEESM" + lightIndex] = true;
  46727. }
  46728. if (light.needCube()) {
  46729. defines["SHADOWCUBE" + lightIndex] = true;
  46730. }
  46731. };
  46732. /**
  46733. * This binds shadow lights related to the standard BJS materials.
  46734. * It implies the unifroms available on the materials are the standard BJS ones.
  46735. */
  46736. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  46737. var light = this._light;
  46738. var scene = this._scene;
  46739. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  46740. return;
  46741. }
  46742. if (!light.needCube()) {
  46743. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  46744. }
  46745. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  46746. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  46747. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  46748. };
  46749. // Methods
  46750. /**
  46751. * Returns a Matrix object : the updated transformation matrix.
  46752. */
  46753. ShadowGenerator.prototype.getTransformMatrix = function () {
  46754. var scene = this._scene;
  46755. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  46756. return this._transformMatrix;
  46757. }
  46758. this._currentRenderID = scene.getRenderId();
  46759. this._currentFaceIndexCache = this._currentFaceIndex;
  46760. var lightPosition = this._light.position;
  46761. if (this._light.computeTransformedInformation()) {
  46762. lightPosition = this._light.transformedPosition;
  46763. }
  46764. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  46765. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  46766. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  46767. }
  46768. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  46769. this._cachedPosition = lightPosition.clone();
  46770. this._cachedDirection = this._lightDirection.clone();
  46771. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  46772. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  46773. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  46774. }
  46775. return this._transformMatrix;
  46776. };
  46777. ShadowGenerator.prototype.recreateShadowMap = function () {
  46778. // Track render list.
  46779. var renderList = this._shadowMap.renderList;
  46780. // Clean up existing data.
  46781. this._disposeRTTandPostProcesses();
  46782. // Reinitializes.
  46783. this._initializeGenerator();
  46784. // Reaffect the filter to ensure a correct fallback if necessary.
  46785. this.filter = this.filter;
  46786. // Reaffect the filter.
  46787. this._applyFilterValues();
  46788. // Reaffect Render List.
  46789. this._shadowMap.renderList = renderList;
  46790. };
  46791. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  46792. if (this._shadowMap2) {
  46793. this._shadowMap2.dispose();
  46794. this._shadowMap2 = null;
  46795. }
  46796. if (this._downSamplePostprocess) {
  46797. this._downSamplePostprocess.dispose();
  46798. this._downSamplePostprocess = null;
  46799. }
  46800. if (this._boxBlurPostprocess) {
  46801. this._boxBlurPostprocess.dispose();
  46802. this._boxBlurPostprocess = null;
  46803. }
  46804. if (this._kernelBlurXPostprocess) {
  46805. this._kernelBlurXPostprocess.dispose();
  46806. this._kernelBlurXPostprocess = null;
  46807. }
  46808. if (this._kernelBlurYPostprocess) {
  46809. this._kernelBlurYPostprocess.dispose();
  46810. this._kernelBlurYPostprocess = null;
  46811. }
  46812. this._blurPostProcesses = null;
  46813. };
  46814. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  46815. if (this._shadowMap) {
  46816. this._shadowMap.dispose();
  46817. this._shadowMap = null;
  46818. }
  46819. this._disposeBlurPostProcesses();
  46820. };
  46821. /**
  46822. * Disposes the ShadowGenerator.
  46823. * Returns nothing.
  46824. */
  46825. ShadowGenerator.prototype.dispose = function () {
  46826. this._disposeRTTandPostProcesses();
  46827. this._light._shadowGenerator = null;
  46828. this._light._markMeshesAsLightDirty();
  46829. };
  46830. /**
  46831. * Serializes the ShadowGenerator and returns a serializationObject.
  46832. */
  46833. ShadowGenerator.prototype.serialize = function () {
  46834. var serializationObject = {};
  46835. var shadowMap = this.getShadowMap();
  46836. serializationObject.lightId = this._light.id;
  46837. serializationObject.mapSize = shadowMap.getRenderSize();
  46838. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  46839. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  46840. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  46841. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  46842. serializationObject.usePoissonSampling = this.usePoissonSampling;
  46843. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  46844. serializationObject.depthScale = this.depthScale;
  46845. serializationObject.darkness = this.getDarkness();
  46846. serializationObject.blurBoxOffset = this.blurBoxOffset;
  46847. serializationObject.blurKernel = this.blurKernel;
  46848. serializationObject.blurScale = this.blurScale;
  46849. serializationObject.useKernelBlur = this.useKernelBlur;
  46850. serializationObject.transparencyShadow = this._transparencyShadow;
  46851. serializationObject.renderList = [];
  46852. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  46853. var mesh = shadowMap.renderList[meshIndex];
  46854. serializationObject.renderList.push(mesh.id);
  46855. }
  46856. return serializationObject;
  46857. };
  46858. /**
  46859. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  46860. */
  46861. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  46862. //casting to point light, as light is missing the position attr and typescript complains.
  46863. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  46864. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  46865. var shadowMap = shadowGenerator.getShadowMap();
  46866. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  46867. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  46868. meshes.forEach(function (mesh) {
  46869. shadowMap.renderList.push(mesh);
  46870. });
  46871. }
  46872. if (parsedShadowGenerator.usePoissonSampling) {
  46873. shadowGenerator.usePoissonSampling = true;
  46874. }
  46875. else if (parsedShadowGenerator.useExponentialShadowMap) {
  46876. shadowGenerator.useExponentialShadowMap = true;
  46877. }
  46878. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  46879. shadowGenerator.useBlurExponentialShadowMap = true;
  46880. }
  46881. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  46882. shadowGenerator.useCloseExponentialShadowMap = true;
  46883. }
  46884. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  46885. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  46886. }
  46887. else if (parsedShadowGenerator.useVarianceShadowMap) {
  46888. shadowGenerator.useExponentialShadowMap = true;
  46889. }
  46890. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  46891. shadowGenerator.useBlurExponentialShadowMap = true;
  46892. }
  46893. if (parsedShadowGenerator.depthScale) {
  46894. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  46895. }
  46896. if (parsedShadowGenerator.blurScale) {
  46897. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  46898. }
  46899. if (parsedShadowGenerator.blurBoxOffset) {
  46900. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  46901. }
  46902. if (parsedShadowGenerator.useKernelBlur) {
  46903. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  46904. }
  46905. if (parsedShadowGenerator.blurKernel) {
  46906. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  46907. }
  46908. if (parsedShadowGenerator.bias !== undefined) {
  46909. shadowGenerator.bias = parsedShadowGenerator.bias;
  46910. }
  46911. if (parsedShadowGenerator.darkness) {
  46912. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  46913. }
  46914. if (parsedShadowGenerator.transparencyShadow) {
  46915. shadowGenerator.setTransparencyShadow(true);
  46916. }
  46917. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  46918. return shadowGenerator;
  46919. };
  46920. ShadowGenerator._FILTER_NONE = 0;
  46921. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  46922. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  46923. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  46924. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  46925. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  46926. return ShadowGenerator;
  46927. }());
  46928. BABYLON.ShadowGenerator = ShadowGenerator;
  46929. })(BABYLON || (BABYLON = {}));
  46930. //# sourceMappingURL=babylon.shadowGenerator.js.map
  46931. var BABYLON;
  46932. (function (BABYLON) {
  46933. var DefaultLoadingScreen = (function () {
  46934. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  46935. if (_loadingText === void 0) { _loadingText = ""; }
  46936. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  46937. var _this = this;
  46938. this._renderingCanvas = _renderingCanvas;
  46939. this._loadingText = _loadingText;
  46940. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  46941. // Resize
  46942. this._resizeLoadingUI = function () {
  46943. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  46944. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  46945. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  46946. _this._loadingDiv.style.left = canvasRect.left + "px";
  46947. _this._loadingDiv.style.top = canvasRect.top + "px";
  46948. _this._loadingDiv.style.width = canvasRect.width + "px";
  46949. _this._loadingDiv.style.height = canvasRect.height + "px";
  46950. };
  46951. }
  46952. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  46953. if (this._loadingDiv) {
  46954. // Do not add a loading screen if there is already one
  46955. return;
  46956. }
  46957. this._loadingDiv = document.createElement("div");
  46958. this._loadingDiv.id = "babylonjsLoadingDiv";
  46959. this._loadingDiv.style.opacity = "0";
  46960. this._loadingDiv.style.transition = "opacity 1.5s ease";
  46961. // Loading text
  46962. this._loadingTextDiv = document.createElement("div");
  46963. this._loadingTextDiv.style.position = "absolute";
  46964. this._loadingTextDiv.style.left = "0";
  46965. this._loadingTextDiv.style.top = "50%";
  46966. this._loadingTextDiv.style.marginTop = "80px";
  46967. this._loadingTextDiv.style.width = "100%";
  46968. this._loadingTextDiv.style.height = "20px";
  46969. this._loadingTextDiv.style.fontFamily = "Arial";
  46970. this._loadingTextDiv.style.fontSize = "14px";
  46971. this._loadingTextDiv.style.color = "white";
  46972. this._loadingTextDiv.style.textAlign = "center";
  46973. this._loadingTextDiv.innerHTML = "Loading";
  46974. this._loadingDiv.appendChild(this._loadingTextDiv);
  46975. //set the predefined text
  46976. this._loadingTextDiv.innerHTML = this._loadingText;
  46977. // Generating keyframes
  46978. var style = document.createElement('style');
  46979. style.type = 'text/css';
  46980. 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 }";
  46981. style.innerHTML = keyFrames;
  46982. document.getElementsByTagName('head')[0].appendChild(style);
  46983. // Loading img
  46984. var imgBack = new Image();
  46985. 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";
  46986. imgBack.style.position = "absolute";
  46987. imgBack.style.left = "50%";
  46988. imgBack.style.top = "50%";
  46989. imgBack.style.marginLeft = "-60px";
  46990. imgBack.style.marginTop = "-60px";
  46991. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  46992. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  46993. imgBack.style.transformOrigin = "50% 50%";
  46994. imgBack.style.webkitTransformOrigin = "50% 50%";
  46995. this._loadingDiv.appendChild(imgBack);
  46996. this._resizeLoadingUI();
  46997. window.addEventListener("resize", this._resizeLoadingUI);
  46998. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  46999. document.body.appendChild(this._loadingDiv);
  47000. this._loadingDiv.style.opacity = "1";
  47001. };
  47002. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47003. var _this = this;
  47004. if (!this._loadingDiv) {
  47005. return;
  47006. }
  47007. var onTransitionEnd = function () {
  47008. if (!_this._loadingDiv) {
  47009. return;
  47010. }
  47011. document.body.removeChild(_this._loadingDiv);
  47012. window.removeEventListener("resize", _this._resizeLoadingUI);
  47013. _this._loadingDiv = null;
  47014. };
  47015. this._loadingDiv.style.opacity = "0";
  47016. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47017. };
  47018. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47019. set: function (text) {
  47020. this._loadingText = text;
  47021. if (this._loadingTextDiv) {
  47022. this._loadingTextDiv.innerHTML = this._loadingText;
  47023. }
  47024. },
  47025. enumerable: true,
  47026. configurable: true
  47027. });
  47028. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  47029. get: function () {
  47030. return this._loadingDivBackgroundColor;
  47031. },
  47032. set: function (color) {
  47033. this._loadingDivBackgroundColor = color;
  47034. if (!this._loadingDiv) {
  47035. return;
  47036. }
  47037. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47038. },
  47039. enumerable: true,
  47040. configurable: true
  47041. });
  47042. return DefaultLoadingScreen;
  47043. }());
  47044. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  47045. })(BABYLON || (BABYLON = {}));
  47046. //# sourceMappingURL=babylon.loadingScreen.js.map
  47047. var BABYLON;
  47048. (function (BABYLON) {
  47049. var SceneLoader = (function () {
  47050. function SceneLoader() {
  47051. }
  47052. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  47053. get: function () {
  47054. return 0;
  47055. },
  47056. enumerable: true,
  47057. configurable: true
  47058. });
  47059. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  47060. get: function () {
  47061. return 1;
  47062. },
  47063. enumerable: true,
  47064. configurable: true
  47065. });
  47066. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  47067. get: function () {
  47068. return 2;
  47069. },
  47070. enumerable: true,
  47071. configurable: true
  47072. });
  47073. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  47074. get: function () {
  47075. return 3;
  47076. },
  47077. enumerable: true,
  47078. configurable: true
  47079. });
  47080. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  47081. get: function () {
  47082. return SceneLoader._ForceFullSceneLoadingForIncremental;
  47083. },
  47084. set: function (value) {
  47085. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  47086. },
  47087. enumerable: true,
  47088. configurable: true
  47089. });
  47090. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  47091. get: function () {
  47092. return SceneLoader._ShowLoadingScreen;
  47093. },
  47094. set: function (value) {
  47095. SceneLoader._ShowLoadingScreen = value;
  47096. },
  47097. enumerable: true,
  47098. configurable: true
  47099. });
  47100. Object.defineProperty(SceneLoader, "loggingLevel", {
  47101. get: function () {
  47102. return SceneLoader._loggingLevel;
  47103. },
  47104. set: function (value) {
  47105. SceneLoader._loggingLevel = value;
  47106. },
  47107. enumerable: true,
  47108. configurable: true
  47109. });
  47110. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  47111. get: function () {
  47112. return SceneLoader._CleanBoneMatrixWeights;
  47113. },
  47114. set: function (value) {
  47115. SceneLoader._CleanBoneMatrixWeights = value;
  47116. },
  47117. enumerable: true,
  47118. configurable: true
  47119. });
  47120. SceneLoader._getDefaultPlugin = function () {
  47121. return SceneLoader._registeredPlugins[".babylon"];
  47122. };
  47123. SceneLoader._getPluginForExtension = function (extension) {
  47124. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  47125. if (registeredPlugin) {
  47126. return registeredPlugin;
  47127. }
  47128. return SceneLoader._getDefaultPlugin();
  47129. };
  47130. SceneLoader._getPluginForDirectLoad = function (data) {
  47131. for (var extension in SceneLoader._registeredPlugins) {
  47132. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  47133. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  47134. return SceneLoader._registeredPlugins[extension];
  47135. }
  47136. }
  47137. return SceneLoader._getDefaultPlugin();
  47138. };
  47139. SceneLoader._getPluginForFilename = function (sceneFilename) {
  47140. if (sceneFilename.name) {
  47141. sceneFilename = sceneFilename.name;
  47142. }
  47143. var dotPosition = sceneFilename.lastIndexOf(".");
  47144. var queryStringPosition = sceneFilename.indexOf("?");
  47145. if (queryStringPosition === -1) {
  47146. queryStringPosition = sceneFilename.length;
  47147. }
  47148. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  47149. return SceneLoader._getPluginForExtension(extension);
  47150. };
  47151. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  47152. SceneLoader._getDirectLoad = function (sceneFilename) {
  47153. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  47154. return sceneFilename.substr(5);
  47155. }
  47156. return null;
  47157. };
  47158. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47159. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47160. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  47161. var plugin = registeredPlugin.plugin;
  47162. var useArrayBuffer = registeredPlugin.isBinary;
  47163. var database;
  47164. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  47165. var dataCallback = function (data) {
  47166. if (scene.isDisposed) {
  47167. onError("Scene has been disposed");
  47168. return;
  47169. }
  47170. scene.database = database;
  47171. try {
  47172. onSuccess(plugin, data);
  47173. }
  47174. catch (e) {
  47175. onError(null, e);
  47176. }
  47177. };
  47178. var manifestChecked = function (success) {
  47179. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  47180. onError(request.status + " " + request.statusText);
  47181. });
  47182. };
  47183. if (directLoad) {
  47184. dataCallback(directLoad);
  47185. return;
  47186. }
  47187. if (rootUrl.indexOf("file:") === -1) {
  47188. if (scene.getEngine().enableOfflineSupport) {
  47189. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47190. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47191. }
  47192. else {
  47193. manifestChecked(true);
  47194. }
  47195. }
  47196. else {
  47197. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  47198. }
  47199. };
  47200. // Public functions
  47201. SceneLoader.GetPluginForExtension = function (extension) {
  47202. return SceneLoader._getPluginForExtension(extension).plugin;
  47203. };
  47204. SceneLoader.RegisterPlugin = function (plugin) {
  47205. if (typeof plugin.extensions === "string") {
  47206. var extension = plugin.extensions;
  47207. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47208. plugin: plugin,
  47209. isBinary: false
  47210. };
  47211. }
  47212. else {
  47213. var extensions = plugin.extensions;
  47214. Object.keys(extensions).forEach(function (extension) {
  47215. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47216. plugin: plugin,
  47217. isBinary: extensions[extension].isBinary
  47218. };
  47219. });
  47220. }
  47221. };
  47222. /**
  47223. * Import meshes into a scene
  47224. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  47225. * @param rootUrl a string that defines the root url for scene and resources
  47226. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47227. * @param scene the instance of BABYLON.Scene to append to
  47228. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  47229. * @param onProgress a callback with a progress event for each file being loaded
  47230. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47231. */
  47232. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47233. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47234. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47235. return;
  47236. }
  47237. var loadingToken = {};
  47238. scene._addPendingData(loadingToken);
  47239. var errorHandler = function (message, exception) {
  47240. if (onError) {
  47241. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47242. }
  47243. scene._removePendingData(loadingToken);
  47244. };
  47245. var progressHandler = function (event) {
  47246. if (onProgress) {
  47247. onProgress(event);
  47248. }
  47249. };
  47250. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47251. if (plugin.importMesh) {
  47252. var syncedPlugin = plugin;
  47253. var meshes = [];
  47254. var particleSystems = [];
  47255. var skeletons = [];
  47256. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  47257. return;
  47258. }
  47259. if (onSuccess) {
  47260. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47261. onSuccess(meshes, particleSystems, skeletons);
  47262. scene._removePendingData(loadingToken);
  47263. }
  47264. }
  47265. else {
  47266. var asyncedPlugin = plugin;
  47267. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47268. if (onSuccess) {
  47269. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47270. onSuccess(meshes, particleSystems, skeletons);
  47271. scene._removePendingData(loadingToken);
  47272. }
  47273. }, progressHandler, errorHandler);
  47274. }
  47275. }, progressHandler, errorHandler);
  47276. };
  47277. /**
  47278. * Load a scene
  47279. * @param rootUrl a string that defines the root url for scene and resources
  47280. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47281. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47282. * @param onSuccess a callback with the scene when import succeeds
  47283. * @param onProgress a callback with a progress event for each file being loaded
  47284. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47285. */
  47286. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  47287. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  47288. };
  47289. /**
  47290. * Append a scene
  47291. * @param rootUrl a string that defines the root url for scene and resources
  47292. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47293. * @param scene is the instance of BABYLON.Scene to append to
  47294. * @param onSuccess a callback with the scene when import succeeds
  47295. * @param onProgress a callback with a progress event for each file being loaded
  47296. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47297. */
  47298. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47299. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47300. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47301. return;
  47302. }
  47303. if (SceneLoader.ShowLoadingScreen) {
  47304. scene.getEngine().displayLoadingUI();
  47305. }
  47306. var loadingToken = {};
  47307. scene._addPendingData(loadingToken);
  47308. var errorHandler = function (message, exception) {
  47309. if (onError) {
  47310. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47311. }
  47312. scene._removePendingData(loadingToken);
  47313. scene.getEngine().hideLoadingUI();
  47314. };
  47315. var progressHandler = function (event) {
  47316. if (onProgress) {
  47317. onProgress(event);
  47318. }
  47319. };
  47320. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47321. if (plugin.load) {
  47322. var syncedPlugin = plugin;
  47323. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  47324. return;
  47325. }
  47326. if (onSuccess) {
  47327. onSuccess(scene);
  47328. }
  47329. scene.loadingPluginName = plugin.name;
  47330. scene._removePendingData(loadingToken);
  47331. }
  47332. else {
  47333. var asyncedPlugin = plugin;
  47334. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47335. if (onSuccess) {
  47336. onSuccess(scene);
  47337. }
  47338. scene.loadingPluginName = plugin.name;
  47339. scene._removePendingData(loadingToken);
  47340. }, progressHandler, errorHandler);
  47341. }
  47342. if (SceneLoader.ShowLoadingScreen) {
  47343. scene.executeWhenReady(function () {
  47344. scene.getEngine().hideLoadingUI();
  47345. });
  47346. }
  47347. }, progressHandler, errorHandler);
  47348. };
  47349. // Flags
  47350. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47351. SceneLoader._ShowLoadingScreen = true;
  47352. SceneLoader._CleanBoneMatrixWeights = false;
  47353. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47354. // Members
  47355. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  47356. SceneLoader._registeredPlugins = {};
  47357. return SceneLoader;
  47358. }());
  47359. BABYLON.SceneLoader = SceneLoader;
  47360. ;
  47361. })(BABYLON || (BABYLON = {}));
  47362. //# sourceMappingURL=babylon.sceneLoader.js.map
  47363. var BABYLON;
  47364. (function (BABYLON) {
  47365. var Internals;
  47366. (function (Internals) {
  47367. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47368. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47369. var parsedMaterial = parsedData.materials[index];
  47370. if (parsedMaterial.id === id) {
  47371. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47372. }
  47373. }
  47374. return null;
  47375. };
  47376. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47377. for (var i in names) {
  47378. if (mesh.name === names[i]) {
  47379. hierarchyIds.push(mesh.id);
  47380. return true;
  47381. }
  47382. }
  47383. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47384. hierarchyIds.push(mesh.id);
  47385. return true;
  47386. }
  47387. return false;
  47388. };
  47389. var logOperation = function (operation, producer) {
  47390. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47391. };
  47392. BABYLON.SceneLoader.RegisterPlugin({
  47393. name: "babylon.js",
  47394. extensions: ".babylon",
  47395. canDirectLoad: function (data) {
  47396. if (data.indexOf("babylon") !== -1) {
  47397. return true;
  47398. }
  47399. return false;
  47400. },
  47401. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  47402. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47403. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47404. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47405. // and avoid problems with multiple concurrent .babylon loads.
  47406. var log = "importMesh has failed JSON parse";
  47407. try {
  47408. var parsedData = JSON.parse(data);
  47409. log = "";
  47410. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47411. if (!meshesNames) {
  47412. meshesNames = null;
  47413. }
  47414. else if (!Array.isArray(meshesNames)) {
  47415. meshesNames = [meshesNames];
  47416. }
  47417. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  47418. var loadedSkeletonsIds = [];
  47419. var loadedMaterialsIds = [];
  47420. var hierarchyIds = [];
  47421. var index;
  47422. var cache;
  47423. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47424. var parsedMesh = parsedData.meshes[index];
  47425. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  47426. if (meshesNames !== null) {
  47427. // Remove found mesh name from list.
  47428. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  47429. }
  47430. //Geometry?
  47431. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  47432. //does the file contain geometries?
  47433. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  47434. //find the correct geometry and add it to the scene
  47435. var found = false;
  47436. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47437. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  47438. return;
  47439. }
  47440. else {
  47441. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47442. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47443. switch (geometryType) {
  47444. case "boxes":
  47445. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47446. break;
  47447. case "spheres":
  47448. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47449. break;
  47450. case "cylinders":
  47451. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47452. break;
  47453. case "toruses":
  47454. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47455. break;
  47456. case "grounds":
  47457. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47458. break;
  47459. case "planes":
  47460. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47461. break;
  47462. case "torusKnots":
  47463. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47464. break;
  47465. case "vertexData":
  47466. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47467. break;
  47468. }
  47469. found = true;
  47470. }
  47471. });
  47472. }
  47473. });
  47474. if (found === false) {
  47475. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47476. }
  47477. }
  47478. }
  47479. // Material ?
  47480. if (parsedMesh.materialId) {
  47481. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47482. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  47483. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47484. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47485. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47486. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47487. var subMatId = parsedMultiMaterial.materials[matIndex];
  47488. loadedMaterialsIds.push(subMatId);
  47489. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47490. log += "\n\tMaterial " + mat.toString(fullDetails);
  47491. }
  47492. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47493. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47494. materialFound = true;
  47495. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47496. break;
  47497. }
  47498. }
  47499. }
  47500. if (materialFound === false) {
  47501. loadedMaterialsIds.push(parsedMesh.materialId);
  47502. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47503. if (!mat) {
  47504. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47505. }
  47506. else {
  47507. log += "\n\tMaterial " + mat.toString(fullDetails);
  47508. }
  47509. }
  47510. }
  47511. // Skeleton ?
  47512. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  47513. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47514. if (skeletonAlreadyLoaded === false) {
  47515. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47516. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47517. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47518. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47519. skeletons.push(skeleton);
  47520. loadedSkeletonsIds.push(parsedSkeleton.id);
  47521. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47522. }
  47523. }
  47524. }
  47525. }
  47526. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47527. meshes.push(mesh);
  47528. log += "\n\tMesh " + mesh.toString(fullDetails);
  47529. }
  47530. }
  47531. // Connecting parents
  47532. var currentMesh;
  47533. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47534. currentMesh = scene.meshes[index];
  47535. if (currentMesh._waitingParentId) {
  47536. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47537. currentMesh._waitingParentId = undefined;
  47538. }
  47539. }
  47540. // freeze and compute world matrix application
  47541. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47542. currentMesh = scene.meshes[index];
  47543. if (currentMesh._waitingFreezeWorldMatrix) {
  47544. currentMesh.freezeWorldMatrix();
  47545. currentMesh._waitingFreezeWorldMatrix = undefined;
  47546. }
  47547. else {
  47548. currentMesh.computeWorldMatrix(true);
  47549. }
  47550. }
  47551. }
  47552. // Particles
  47553. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  47554. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47555. var parsedParticleSystem = parsedData.particleSystems[index];
  47556. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  47557. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  47558. }
  47559. }
  47560. }
  47561. return true;
  47562. }
  47563. catch (err) {
  47564. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  47565. log = null;
  47566. throw err;
  47567. }
  47568. finally {
  47569. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47570. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47571. }
  47572. }
  47573. },
  47574. load: function (scene, data, rootUrl) {
  47575. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47576. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47577. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47578. // and avoid problems with multiple concurrent .babylon loads.
  47579. var log = "importScene has failed JSON parse";
  47580. try {
  47581. var parsedData = JSON.parse(data);
  47582. log = "";
  47583. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47584. // Scene
  47585. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  47586. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  47587. }
  47588. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  47589. scene.autoClear = parsedData.autoClear;
  47590. }
  47591. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  47592. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  47593. }
  47594. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  47595. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  47596. }
  47597. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  47598. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  47599. }
  47600. // Fog
  47601. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  47602. scene.fogMode = parsedData.fogMode;
  47603. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  47604. scene.fogStart = parsedData.fogStart;
  47605. scene.fogEnd = parsedData.fogEnd;
  47606. scene.fogDensity = parsedData.fogDensity;
  47607. log += "\tFog mode for scene: ";
  47608. switch (scene.fogMode) {
  47609. // getters not compiling, so using hardcoded
  47610. case 1:
  47611. log += "exp\n";
  47612. break;
  47613. case 2:
  47614. log += "exp2\n";
  47615. break;
  47616. case 3:
  47617. log += "linear\n";
  47618. break;
  47619. }
  47620. }
  47621. //Physics
  47622. if (parsedData.physicsEnabled) {
  47623. var physicsPlugin;
  47624. if (parsedData.physicsEngine === "cannon") {
  47625. physicsPlugin = new BABYLON.CannonJSPlugin();
  47626. }
  47627. else if (parsedData.physicsEngine === "oimo") {
  47628. physicsPlugin = new BABYLON.OimoJSPlugin();
  47629. }
  47630. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  47631. //else - default engine, which is currently oimo
  47632. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  47633. scene.enablePhysics(physicsGravity, physicsPlugin);
  47634. }
  47635. // Metadata
  47636. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  47637. scene.metadata = parsedData.metadata;
  47638. }
  47639. //collisions, if defined. otherwise, default is true
  47640. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  47641. scene.collisionsEnabled = parsedData.collisionsEnabled;
  47642. }
  47643. scene.workerCollisions = !!parsedData.workerCollisions;
  47644. var index;
  47645. var cache;
  47646. // Lights
  47647. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  47648. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  47649. var parsedLight = parsedData.lights[index];
  47650. var light = BABYLON.Light.Parse(parsedLight, scene);
  47651. log += (index === 0 ? "\n\tLights:" : "");
  47652. log += "\n\t\t" + light.toString(fullDetails);
  47653. }
  47654. }
  47655. // Animations
  47656. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  47657. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  47658. var parsedAnimation = parsedData.animations[index];
  47659. var animation = BABYLON.Animation.Parse(parsedAnimation);
  47660. scene.animations.push(animation);
  47661. log += (index === 0 ? "\n\tAnimations:" : "");
  47662. log += "\n\t\t" + animation.toString(fullDetails);
  47663. }
  47664. }
  47665. if (parsedData.autoAnimate) {
  47666. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  47667. }
  47668. // Materials
  47669. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  47670. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47671. var parsedMaterial = parsedData.materials[index];
  47672. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47673. log += (index === 0 ? "\n\tMaterials:" : "");
  47674. log += "\n\t\t" + mat.toString(fullDetails);
  47675. }
  47676. }
  47677. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  47678. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  47679. var parsedMultiMaterial = parsedData.multiMaterials[index];
  47680. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47681. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  47682. log += "\n\t\t" + mmat.toString(fullDetails);
  47683. }
  47684. }
  47685. // Morph targets
  47686. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  47687. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  47688. var managerData = _a[_i];
  47689. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  47690. }
  47691. }
  47692. // Skeletons
  47693. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  47694. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  47695. var parsedSkeleton = parsedData.skeletons[index];
  47696. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47697. log += (index === 0 ? "\n\tSkeletons:" : "");
  47698. log += "\n\t\t" + skeleton.toString(fullDetails);
  47699. }
  47700. }
  47701. // Geometries
  47702. var geometries = parsedData.geometries;
  47703. if (geometries !== undefined && geometries !== null) {
  47704. // Boxes
  47705. var boxes = geometries.boxes;
  47706. if (boxes !== undefined && boxes !== null) {
  47707. for (index = 0, cache = boxes.length; index < cache; index++) {
  47708. var parsedBox = boxes[index];
  47709. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  47710. }
  47711. }
  47712. // Spheres
  47713. var spheres = geometries.spheres;
  47714. if (spheres !== undefined && spheres !== null) {
  47715. for (index = 0, cache = spheres.length; index < cache; index++) {
  47716. var parsedSphere = spheres[index];
  47717. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  47718. }
  47719. }
  47720. // Cylinders
  47721. var cylinders = geometries.cylinders;
  47722. if (cylinders !== undefined && cylinders !== null) {
  47723. for (index = 0, cache = cylinders.length; index < cache; index++) {
  47724. var parsedCylinder = cylinders[index];
  47725. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  47726. }
  47727. }
  47728. // Toruses
  47729. var toruses = geometries.toruses;
  47730. if (toruses !== undefined && toruses !== null) {
  47731. for (index = 0, cache = toruses.length; index < cache; index++) {
  47732. var parsedTorus = toruses[index];
  47733. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  47734. }
  47735. }
  47736. // Grounds
  47737. var grounds = geometries.grounds;
  47738. if (grounds !== undefined && grounds !== null) {
  47739. for (index = 0, cache = grounds.length; index < cache; index++) {
  47740. var parsedGround = grounds[index];
  47741. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  47742. }
  47743. }
  47744. // Planes
  47745. var planes = geometries.planes;
  47746. if (planes !== undefined && planes !== null) {
  47747. for (index = 0, cache = planes.length; index < cache; index++) {
  47748. var parsedPlane = planes[index];
  47749. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  47750. }
  47751. }
  47752. // TorusKnots
  47753. var torusKnots = geometries.torusKnots;
  47754. if (torusKnots !== undefined && torusKnots !== null) {
  47755. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  47756. var parsedTorusKnot = torusKnots[index];
  47757. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  47758. }
  47759. }
  47760. // VertexData
  47761. var vertexData = geometries.vertexData;
  47762. if (vertexData !== undefined && vertexData !== null) {
  47763. for (index = 0, cache = vertexData.length; index < cache; index++) {
  47764. var parsedVertexData = vertexData[index];
  47765. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  47766. }
  47767. }
  47768. }
  47769. // Meshes
  47770. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  47771. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47772. var parsedMesh = parsedData.meshes[index];
  47773. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47774. log += (index === 0 ? "\n\tMeshes:" : "");
  47775. log += "\n\t\t" + mesh.toString(fullDetails);
  47776. }
  47777. }
  47778. // Cameras
  47779. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  47780. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  47781. var parsedCamera = parsedData.cameras[index];
  47782. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  47783. log += (index === 0 ? "\n\tCameras:" : "");
  47784. log += "\n\t\t" + camera.toString(fullDetails);
  47785. }
  47786. }
  47787. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  47788. scene.setActiveCameraByID(parsedData.activeCameraID);
  47789. }
  47790. // Browsing all the graph to connect the dots
  47791. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  47792. var camera = scene.cameras[index];
  47793. if (camera._waitingParentId) {
  47794. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  47795. camera._waitingParentId = undefined;
  47796. }
  47797. }
  47798. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47799. var light = scene.lights[index];
  47800. if (light._waitingParentId) {
  47801. light.parent = scene.getLastEntryByID(light._waitingParentId);
  47802. light._waitingParentId = undefined;
  47803. }
  47804. }
  47805. // Sounds
  47806. var loadedSounds = [];
  47807. var loadedSound;
  47808. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  47809. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  47810. var parsedSound = parsedData.sounds[index];
  47811. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47812. if (!parsedSound.url)
  47813. parsedSound.url = parsedSound.name;
  47814. if (!loadedSounds[parsedSound.url]) {
  47815. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  47816. loadedSounds[parsedSound.url] = loadedSound;
  47817. }
  47818. else {
  47819. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  47820. }
  47821. }
  47822. else {
  47823. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  47824. }
  47825. }
  47826. }
  47827. loadedSounds = [];
  47828. // Connect parents & children and parse actions
  47829. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47830. var mesh = scene.meshes[index];
  47831. if (mesh._waitingParentId) {
  47832. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  47833. mesh._waitingParentId = undefined;
  47834. }
  47835. if (mesh._waitingActions) {
  47836. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  47837. mesh._waitingActions = undefined;
  47838. }
  47839. }
  47840. // freeze world matrix application
  47841. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47842. var currentMesh = scene.meshes[index];
  47843. if (currentMesh._waitingFreezeWorldMatrix) {
  47844. currentMesh.freezeWorldMatrix();
  47845. currentMesh._waitingFreezeWorldMatrix = undefined;
  47846. }
  47847. else {
  47848. currentMesh.computeWorldMatrix(true);
  47849. }
  47850. }
  47851. // Particles Systems
  47852. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  47853. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47854. var parsedParticleSystem = parsedData.particleSystems[index];
  47855. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  47856. }
  47857. }
  47858. // Lens flares
  47859. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  47860. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  47861. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  47862. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  47863. }
  47864. }
  47865. // Shadows
  47866. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  47867. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  47868. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  47869. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  47870. }
  47871. }
  47872. // Lights exclusions / inclusions
  47873. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47874. var light = scene.lights[index];
  47875. // Excluded check
  47876. if (light._excludedMeshesIds.length > 0) {
  47877. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  47878. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  47879. if (excludedMesh) {
  47880. light.excludedMeshes.push(excludedMesh);
  47881. }
  47882. }
  47883. light._excludedMeshesIds = [];
  47884. }
  47885. // Included check
  47886. if (light._includedOnlyMeshesIds.length > 0) {
  47887. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  47888. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  47889. if (includedOnlyMesh) {
  47890. light.includedOnlyMeshes.push(includedOnlyMesh);
  47891. }
  47892. }
  47893. light._includedOnlyMeshesIds = [];
  47894. }
  47895. }
  47896. // Actions (scene)
  47897. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  47898. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  47899. }
  47900. // Finish
  47901. return true;
  47902. }
  47903. catch (err) {
  47904. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  47905. log = null;
  47906. throw err;
  47907. }
  47908. finally {
  47909. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47910. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47911. }
  47912. }
  47913. }
  47914. });
  47915. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47916. })(BABYLON || (BABYLON = {}));
  47917. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  47918. var BABYLON;
  47919. (function (BABYLON) {
  47920. var FilesInput = (function () {
  47921. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  47922. this._engine = engine;
  47923. this._currentScene = scene;
  47924. this._sceneLoadedCallback = sceneLoadedCallback;
  47925. this._progressCallback = progressCallback;
  47926. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  47927. this._textureLoadingCallback = textureLoadingCallback;
  47928. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  47929. this._onReloadCallback = onReloadCallback;
  47930. }
  47931. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  47932. var _this = this;
  47933. if (elementToMonitor) {
  47934. this._elementToMonitor = elementToMonitor;
  47935. this._dragEnterHandler = function (e) { _this.drag(e); };
  47936. this._dragOverHandler = function (e) { _this.drag(e); };
  47937. this._dropHandler = function (e) { _this.drop(e); };
  47938. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  47939. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  47940. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  47941. }
  47942. };
  47943. FilesInput.prototype.dispose = function () {
  47944. if (!this._elementToMonitor) {
  47945. return;
  47946. }
  47947. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  47948. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  47949. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  47950. };
  47951. FilesInput.prototype.renderFunction = function () {
  47952. if (this._additionalRenderLoopLogicCallback) {
  47953. this._additionalRenderLoopLogicCallback();
  47954. }
  47955. if (this._currentScene) {
  47956. if (this._textureLoadingCallback) {
  47957. var remaining = this._currentScene.getWaitingItemsCount();
  47958. if (remaining > 0) {
  47959. this._textureLoadingCallback(remaining);
  47960. }
  47961. }
  47962. this._currentScene.render();
  47963. }
  47964. };
  47965. FilesInput.prototype.drag = function (e) {
  47966. e.stopPropagation();
  47967. e.preventDefault();
  47968. };
  47969. FilesInput.prototype.drop = function (eventDrop) {
  47970. eventDrop.stopPropagation();
  47971. eventDrop.preventDefault();
  47972. this.loadFiles(eventDrop);
  47973. };
  47974. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  47975. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  47976. reader.readEntries(function (fileEntries) {
  47977. var remaining = fileEntries.length;
  47978. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  47979. var fileEntry = fileEntries_1[_i];
  47980. if (fileEntry.isFile) {
  47981. fileEntry.file(function (file) {
  47982. file.correctName = relativePath + file.name;
  47983. files.push(file);
  47984. remaining--;
  47985. if (remaining === 0) {
  47986. callback();
  47987. }
  47988. });
  47989. }
  47990. else {
  47991. remaining--;
  47992. if (remaining === 0) {
  47993. callback();
  47994. }
  47995. }
  47996. }
  47997. });
  47998. };
  47999. FilesInput.prototype._processFiles = function (files) {
  48000. for (var i = 0; i < files.length; i++) {
  48001. var name = files[i].correctName.toLowerCase();
  48002. var extension = name.split('.').pop();
  48003. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48004. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  48005. this._sceneFileToLoad = files[i];
  48006. }
  48007. else {
  48008. FilesInput.FilesToLoad[name] = files[i];
  48009. }
  48010. }
  48011. if (this._onReloadCallback) {
  48012. this._onReloadCallback(this._sceneFileToLoad);
  48013. }
  48014. else {
  48015. this.reload();
  48016. }
  48017. };
  48018. FilesInput.prototype.loadFiles = function (event) {
  48019. var _this = this;
  48020. if (this._startingProcessingFilesCallback)
  48021. this._startingProcessingFilesCallback();
  48022. // Handling data transfer via drag'n'drop
  48023. if (event && event.dataTransfer && event.dataTransfer.files) {
  48024. this._filesToLoad = event.dataTransfer.files;
  48025. }
  48026. // Handling files from input files
  48027. if (event && event.target && event.target.files) {
  48028. this._filesToLoad = event.target.files;
  48029. }
  48030. if (this._filesToLoad && this._filesToLoad.length > 0) {
  48031. var files_1 = [];
  48032. var folders = [];
  48033. var items = event.dataTransfer ? event.dataTransfer.items : null;
  48034. for (var i = 0; i < this._filesToLoad.length; i++) {
  48035. var fileToLoad = this._filesToLoad[i];
  48036. var name_1 = fileToLoad.name.toLowerCase();
  48037. var type = fileToLoad.type;
  48038. var entry = void 0;
  48039. fileToLoad.correctName = name_1;
  48040. if (items) {
  48041. var item = items[i];
  48042. if (item.getAsEntry) {
  48043. entry = item.getAsEntry();
  48044. }
  48045. else if (item.webkitGetAsEntry) {
  48046. entry = item.webkitGetAsEntry();
  48047. }
  48048. }
  48049. if (!entry) {
  48050. files_1.push(fileToLoad);
  48051. }
  48052. else {
  48053. if (entry.isDirectory) {
  48054. folders.push(entry);
  48055. }
  48056. else {
  48057. files_1.push(fileToLoad);
  48058. }
  48059. }
  48060. }
  48061. if (folders.length === 0) {
  48062. this._processFiles(files_1);
  48063. }
  48064. else {
  48065. var remaining = folders.length;
  48066. // Extract folder content
  48067. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  48068. var folder = folders_1[_i];
  48069. this._handleFolderDrop(folder, files_1, function () {
  48070. remaining--;
  48071. if (remaining === 0) {
  48072. _this._processFiles(files_1);
  48073. }
  48074. });
  48075. }
  48076. }
  48077. }
  48078. };
  48079. FilesInput.prototype.reload = function () {
  48080. var _this = this;
  48081. // If a ".babylon" file has been provided
  48082. if (this._sceneFileToLoad) {
  48083. if (this._currentScene) {
  48084. if (BABYLON.Tools.errorsCount > 0) {
  48085. BABYLON.Tools.ClearLogCache();
  48086. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  48087. }
  48088. this._engine.stopRenderLoop();
  48089. this._currentScene.dispose();
  48090. }
  48091. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  48092. _this._currentScene = newScene;
  48093. if (_this._sceneLoadedCallback) {
  48094. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  48095. }
  48096. // Wait for textures and shaders to be ready
  48097. _this._currentScene.executeWhenReady(function () {
  48098. _this._engine.runRenderLoop(function () {
  48099. _this.renderFunction();
  48100. });
  48101. });
  48102. }, function (progress) {
  48103. if (_this._progressCallback) {
  48104. _this._progressCallback(progress);
  48105. }
  48106. });
  48107. }
  48108. else {
  48109. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  48110. }
  48111. };
  48112. FilesInput.FilesToLoad = new Array();
  48113. return FilesInput;
  48114. }());
  48115. BABYLON.FilesInput = FilesInput;
  48116. })(BABYLON || (BABYLON = {}));
  48117. //# sourceMappingURL=babylon.filesInput.js.map
  48118. var BABYLON;
  48119. (function (BABYLON) {
  48120. /**
  48121. * This class implement a typical dictionary using a string as key and the generic type T as value.
  48122. * The underlying implementation relies on an associative array to ensure the best performances.
  48123. * The value can be anything including 'null' but except 'undefined'
  48124. */
  48125. var StringDictionary = (function () {
  48126. function StringDictionary() {
  48127. this._count = 0;
  48128. this._data = {};
  48129. }
  48130. /**
  48131. * This will clear this dictionary and copy the content from the 'source' one.
  48132. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  48133. * @param source the dictionary to take the content from and copy to this dictionary
  48134. */
  48135. StringDictionary.prototype.copyFrom = function (source) {
  48136. var _this = this;
  48137. this.clear();
  48138. source.forEach(function (t, v) { return _this.add(t, v); });
  48139. };
  48140. /**
  48141. * Get a value based from its key
  48142. * @param key the given key to get the matching value from
  48143. * @return the value if found, otherwise undefined is returned
  48144. */
  48145. StringDictionary.prototype.get = function (key) {
  48146. var val = this._data[key];
  48147. if (val !== undefined) {
  48148. return val;
  48149. }
  48150. return undefined;
  48151. };
  48152. /**
  48153. * Get a value from its key or add it if it doesn't exist.
  48154. * This method will ensure you that a given key/data will be present in the dictionary.
  48155. * @param key the given key to get the matching value from
  48156. * @param factory the factory that will create the value if the key is not present in the dictionary.
  48157. * The factory will only be invoked if there's no data for the given key.
  48158. * @return the value corresponding to the key.
  48159. */
  48160. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  48161. var val = this.get(key);
  48162. if (val !== undefined) {
  48163. return val;
  48164. }
  48165. val = factory(key);
  48166. if (val) {
  48167. this.add(key, val);
  48168. }
  48169. return val;
  48170. };
  48171. /**
  48172. * Get a value from its key if present in the dictionary otherwise add it
  48173. * @param key the key to get the value from
  48174. * @param val if there's no such key/value pair in the dictionary add it with this value
  48175. * @return the value corresponding to the key
  48176. */
  48177. StringDictionary.prototype.getOrAdd = function (key, val) {
  48178. var curVal = this.get(key);
  48179. if (curVal !== undefined) {
  48180. return curVal;
  48181. }
  48182. this.add(key, val);
  48183. return val;
  48184. };
  48185. /**
  48186. * Check if there's a given key in the dictionary
  48187. * @param key the key to check for
  48188. * @return true if the key is present, false otherwise
  48189. */
  48190. StringDictionary.prototype.contains = function (key) {
  48191. return this._data[key] !== undefined;
  48192. };
  48193. /**
  48194. * Add a new key and its corresponding value
  48195. * @param key the key to add
  48196. * @param value the value corresponding to the key
  48197. * @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
  48198. */
  48199. StringDictionary.prototype.add = function (key, value) {
  48200. if (this._data[key] !== undefined) {
  48201. return false;
  48202. }
  48203. this._data[key] = value;
  48204. ++this._count;
  48205. return true;
  48206. };
  48207. StringDictionary.prototype.set = function (key, value) {
  48208. if (this._data[key] === undefined) {
  48209. return false;
  48210. }
  48211. this._data[key] = value;
  48212. return true;
  48213. };
  48214. /**
  48215. * Get the element of the given key and remove it from the dictionary
  48216. * @param key
  48217. */
  48218. StringDictionary.prototype.getAndRemove = function (key) {
  48219. var val = this.get(key);
  48220. if (val !== undefined) {
  48221. delete this._data[key];
  48222. --this._count;
  48223. return val;
  48224. }
  48225. return null;
  48226. };
  48227. /**
  48228. * Remove a key/value from the dictionary.
  48229. * @param key the key to remove
  48230. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  48231. */
  48232. StringDictionary.prototype.remove = function (key) {
  48233. if (this.contains(key)) {
  48234. delete this._data[key];
  48235. --this._count;
  48236. return true;
  48237. }
  48238. return false;
  48239. };
  48240. /**
  48241. * Clear the whole content of the dictionary
  48242. */
  48243. StringDictionary.prototype.clear = function () {
  48244. this._data = {};
  48245. this._count = 0;
  48246. };
  48247. Object.defineProperty(StringDictionary.prototype, "count", {
  48248. get: function () {
  48249. return this._count;
  48250. },
  48251. enumerable: true,
  48252. configurable: true
  48253. });
  48254. /**
  48255. * Execute a callback on each key/val of the dictionary.
  48256. * Note that you can remove any element in this dictionary in the callback implementation
  48257. * @param callback the callback to execute on a given key/value pair
  48258. */
  48259. StringDictionary.prototype.forEach = function (callback) {
  48260. for (var cur in this._data) {
  48261. var val = this._data[cur];
  48262. callback(cur, val);
  48263. }
  48264. };
  48265. /**
  48266. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  48267. * If the callback returns null or undefined the method will iterate to the next key/value pair
  48268. * Note that you can remove any element in this dictionary in the callback implementation
  48269. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  48270. */
  48271. StringDictionary.prototype.first = function (callback) {
  48272. for (var cur in this._data) {
  48273. var val = this._data[cur];
  48274. var res = callback(cur, val);
  48275. if (res) {
  48276. return res;
  48277. }
  48278. }
  48279. return null;
  48280. };
  48281. return StringDictionary;
  48282. }());
  48283. BABYLON.StringDictionary = StringDictionary;
  48284. })(BABYLON || (BABYLON = {}));
  48285. //# sourceMappingURL=babylon.stringDictionary.js.map
  48286. var BABYLON;
  48287. (function (BABYLON) {
  48288. var Tags = (function () {
  48289. function Tags() {
  48290. }
  48291. Tags.EnableFor = function (obj) {
  48292. obj._tags = obj._tags || {};
  48293. obj.hasTags = function () {
  48294. return Tags.HasTags(obj);
  48295. };
  48296. obj.addTags = function (tagsString) {
  48297. return Tags.AddTagsTo(obj, tagsString);
  48298. };
  48299. obj.removeTags = function (tagsString) {
  48300. return Tags.RemoveTagsFrom(obj, tagsString);
  48301. };
  48302. obj.matchesTagsQuery = function (tagsQuery) {
  48303. return Tags.MatchesQuery(obj, tagsQuery);
  48304. };
  48305. };
  48306. Tags.DisableFor = function (obj) {
  48307. delete obj._tags;
  48308. delete obj.hasTags;
  48309. delete obj.addTags;
  48310. delete obj.removeTags;
  48311. delete obj.matchesTagsQuery;
  48312. };
  48313. Tags.HasTags = function (obj) {
  48314. if (!obj._tags) {
  48315. return false;
  48316. }
  48317. return !BABYLON.Tools.IsEmpty(obj._tags);
  48318. };
  48319. Tags.GetTags = function (obj, asString) {
  48320. if (asString === void 0) { asString = true; }
  48321. if (!obj._tags) {
  48322. return null;
  48323. }
  48324. if (asString) {
  48325. var tagsArray = [];
  48326. for (var tag in obj._tags) {
  48327. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  48328. tagsArray.push(tag);
  48329. }
  48330. }
  48331. return tagsArray.join(" ");
  48332. }
  48333. else {
  48334. return obj._tags;
  48335. }
  48336. };
  48337. // the tags 'true' and 'false' are reserved and cannot be used as tags
  48338. // a tag cannot start with '||', '&&', and '!'
  48339. // it cannot contain whitespaces
  48340. Tags.AddTagsTo = function (obj, tagsString) {
  48341. if (!tagsString) {
  48342. return;
  48343. }
  48344. if (typeof tagsString !== "string") {
  48345. return;
  48346. }
  48347. var tags = tagsString.split(" ");
  48348. tags.forEach(function (tag, index, array) {
  48349. Tags._AddTagTo(obj, tag);
  48350. });
  48351. };
  48352. Tags._AddTagTo = function (obj, tag) {
  48353. tag = tag.trim();
  48354. if (tag === "" || tag === "true" || tag === "false") {
  48355. return;
  48356. }
  48357. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  48358. return;
  48359. }
  48360. Tags.EnableFor(obj);
  48361. obj._tags[tag] = true;
  48362. };
  48363. Tags.RemoveTagsFrom = function (obj, tagsString) {
  48364. if (!Tags.HasTags(obj)) {
  48365. return;
  48366. }
  48367. var tags = tagsString.split(" ");
  48368. for (var t in tags) {
  48369. Tags._RemoveTagFrom(obj, tags[t]);
  48370. }
  48371. };
  48372. Tags._RemoveTagFrom = function (obj, tag) {
  48373. delete obj._tags[tag];
  48374. };
  48375. Tags.MatchesQuery = function (obj, tagsQuery) {
  48376. if (tagsQuery === undefined) {
  48377. return true;
  48378. }
  48379. if (tagsQuery === "") {
  48380. return Tags.HasTags(obj);
  48381. }
  48382. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  48383. };
  48384. return Tags;
  48385. }());
  48386. BABYLON.Tags = Tags;
  48387. })(BABYLON || (BABYLON = {}));
  48388. //# sourceMappingURL=babylon.tags.js.map
  48389. var BABYLON;
  48390. (function (BABYLON) {
  48391. var Internals;
  48392. (function (Internals) {
  48393. var AndOrNotEvaluator = (function () {
  48394. function AndOrNotEvaluator() {
  48395. }
  48396. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  48397. if (!query.match(/\([^\(\)]*\)/g)) {
  48398. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  48399. }
  48400. else {
  48401. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  48402. // remove parenthesis
  48403. r = r.slice(1, r.length - 1);
  48404. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  48405. });
  48406. }
  48407. if (query === "true") {
  48408. return true;
  48409. }
  48410. if (query === "false") {
  48411. return false;
  48412. }
  48413. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  48414. };
  48415. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  48416. evaluateCallback = evaluateCallback || (function (r) {
  48417. return r === "true" ? true : false;
  48418. });
  48419. var result;
  48420. var or = parenthesisContent.split("||");
  48421. for (var i in or) {
  48422. if (or.hasOwnProperty(i)) {
  48423. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  48424. var and = ori.split("&&");
  48425. if (and.length > 1) {
  48426. for (var j = 0; j < and.length; ++j) {
  48427. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  48428. if (andj !== "true" && andj !== "false") {
  48429. if (andj[0] === "!") {
  48430. result = !evaluateCallback(andj.substring(1));
  48431. }
  48432. else {
  48433. result = evaluateCallback(andj);
  48434. }
  48435. }
  48436. else {
  48437. result = andj === "true" ? true : false;
  48438. }
  48439. if (!result) {
  48440. ori = "false";
  48441. break;
  48442. }
  48443. }
  48444. }
  48445. if (result || ori === "true") {
  48446. result = true;
  48447. break;
  48448. }
  48449. // result equals false (or undefined)
  48450. if (ori !== "true" && ori !== "false") {
  48451. if (ori[0] === "!") {
  48452. result = !evaluateCallback(ori.substring(1));
  48453. }
  48454. else {
  48455. result = evaluateCallback(ori);
  48456. }
  48457. }
  48458. else {
  48459. result = ori === "true" ? true : false;
  48460. }
  48461. }
  48462. }
  48463. // the whole parenthesis scope is replaced by 'true' or 'false'
  48464. return result ? "true" : "false";
  48465. };
  48466. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  48467. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  48468. // remove whitespaces
  48469. r = r.replace(/[\s]/g, function () { return ""; });
  48470. return r.length % 2 ? "!" : "";
  48471. });
  48472. booleanString = booleanString.trim();
  48473. if (booleanString === "!true") {
  48474. booleanString = "false";
  48475. }
  48476. else if (booleanString === "!false") {
  48477. booleanString = "true";
  48478. }
  48479. return booleanString;
  48480. };
  48481. return AndOrNotEvaluator;
  48482. }());
  48483. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  48484. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48485. })(BABYLON || (BABYLON = {}));
  48486. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  48487. var BABYLON;
  48488. (function (BABYLON) {
  48489. var Database = (function () {
  48490. function Database(urlToScene, callbackManifestChecked) {
  48491. // Handling various flavors of prefixed version of IndexedDB
  48492. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  48493. this.callbackManifestChecked = callbackManifestChecked;
  48494. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  48495. this.db = null;
  48496. this.enableSceneOffline = false;
  48497. this.enableTexturesOffline = false;
  48498. this.manifestVersionFound = 0;
  48499. this.mustUpdateRessources = false;
  48500. this.hasReachedQuota = false;
  48501. if (!Database.IDBStorageEnabled) {
  48502. this.callbackManifestChecked(true);
  48503. }
  48504. else {
  48505. this.checkManifestFile();
  48506. }
  48507. }
  48508. Database.prototype.checkManifestFile = function () {
  48509. var _this = this;
  48510. function noManifestFile() {
  48511. that.enableSceneOffline = false;
  48512. that.enableTexturesOffline = false;
  48513. that.callbackManifestChecked(false);
  48514. }
  48515. var that = this;
  48516. var timeStampUsed = false;
  48517. var manifestURL = this.currentSceneUrl + ".manifest";
  48518. var xhr = new XMLHttpRequest();
  48519. if (navigator.onLine) {
  48520. // Adding a timestamp to by-pass browsers' cache
  48521. timeStampUsed = true;
  48522. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  48523. }
  48524. xhr.open("GET", manifestURL, true);
  48525. xhr.addEventListener("load", function () {
  48526. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  48527. try {
  48528. var manifestFile = JSON.parse(xhr.response);
  48529. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  48530. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  48531. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  48532. _this.manifestVersionFound = manifestFile.version;
  48533. }
  48534. if (_this.callbackManifestChecked) {
  48535. _this.callbackManifestChecked(true);
  48536. }
  48537. }
  48538. catch (ex) {
  48539. noManifestFile();
  48540. }
  48541. }
  48542. else {
  48543. noManifestFile();
  48544. }
  48545. }, false);
  48546. xhr.addEventListener("error", function (event) {
  48547. if (timeStampUsed) {
  48548. timeStampUsed = false;
  48549. // Let's retry without the timeStamp
  48550. // It could fail when coupled with HTML5 Offline API
  48551. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  48552. xhr.open("GET", retryManifestURL, true);
  48553. xhr.send();
  48554. }
  48555. else {
  48556. noManifestFile();
  48557. }
  48558. }, false);
  48559. try {
  48560. xhr.send();
  48561. }
  48562. catch (ex) {
  48563. BABYLON.Tools.Error("Error on XHR send request.");
  48564. that.callbackManifestChecked(false);
  48565. }
  48566. };
  48567. Database.prototype.openAsync = function (successCallback, errorCallback) {
  48568. var _this = this;
  48569. function handleError() {
  48570. that.isSupported = false;
  48571. if (errorCallback)
  48572. errorCallback();
  48573. }
  48574. var that = this;
  48575. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  48576. // Your browser doesn't support IndexedDB
  48577. this.isSupported = false;
  48578. if (errorCallback)
  48579. errorCallback();
  48580. }
  48581. else {
  48582. // If the DB hasn't been opened or created yet
  48583. if (!this.db) {
  48584. this.hasReachedQuota = false;
  48585. this.isSupported = true;
  48586. var request = this.idbFactory.open("babylonjs", 1);
  48587. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  48588. request.onerror = function (event) {
  48589. handleError();
  48590. };
  48591. // executes when a version change transaction cannot complete due to other active transactions
  48592. request.onblocked = function (event) {
  48593. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  48594. handleError();
  48595. };
  48596. // DB has been opened successfully
  48597. request.onsuccess = function (event) {
  48598. _this.db = request.result;
  48599. successCallback();
  48600. };
  48601. // Initialization of the DB. Creating Scenes & Textures stores
  48602. request.onupgradeneeded = function (event) {
  48603. _this.db = (event.target).result;
  48604. try {
  48605. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  48606. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  48607. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  48608. }
  48609. catch (ex) {
  48610. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  48611. handleError();
  48612. }
  48613. };
  48614. }
  48615. else {
  48616. if (successCallback)
  48617. successCallback();
  48618. }
  48619. }
  48620. };
  48621. Database.prototype.loadImageFromDB = function (url, image) {
  48622. var _this = this;
  48623. var completeURL = Database.ReturnFullUrlLocation(url);
  48624. var saveAndLoadImage = function () {
  48625. if (!_this.hasReachedQuota && _this.db !== null) {
  48626. // the texture is not yet in the DB, let's try to save it
  48627. _this._saveImageIntoDBAsync(completeURL, image);
  48628. }
  48629. else {
  48630. image.src = url;
  48631. }
  48632. };
  48633. if (!this.mustUpdateRessources) {
  48634. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  48635. }
  48636. else {
  48637. saveAndLoadImage();
  48638. }
  48639. };
  48640. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  48641. if (this.isSupported && this.db !== null) {
  48642. var texture;
  48643. var transaction = this.db.transaction(["textures"]);
  48644. transaction.onabort = function (event) {
  48645. image.src = url;
  48646. };
  48647. transaction.oncomplete = function (event) {
  48648. var blobTextureURL;
  48649. if (texture) {
  48650. var URL = window.URL || window.webkitURL;
  48651. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  48652. image.onerror = function () {
  48653. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  48654. image.src = url;
  48655. };
  48656. image.src = blobTextureURL;
  48657. }
  48658. else {
  48659. notInDBCallback();
  48660. }
  48661. };
  48662. var getRequest = transaction.objectStore("textures").get(url);
  48663. getRequest.onsuccess = function (event) {
  48664. texture = (event.target).result;
  48665. };
  48666. getRequest.onerror = function (event) {
  48667. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  48668. image.src = url;
  48669. };
  48670. }
  48671. else {
  48672. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48673. image.src = url;
  48674. }
  48675. };
  48676. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  48677. var _this = this;
  48678. if (this.isSupported) {
  48679. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  48680. var generateBlobUrl = function () {
  48681. var blobTextureURL;
  48682. if (blob) {
  48683. var URL = window.URL || window.webkitURL;
  48684. try {
  48685. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  48686. }
  48687. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  48688. catch (ex) {
  48689. blobTextureURL = URL.createObjectURL(blob);
  48690. }
  48691. }
  48692. image.src = blobTextureURL;
  48693. };
  48694. if (Database.IsUASupportingBlobStorage) {
  48695. var xhr = new XMLHttpRequest(), blob;
  48696. xhr.open("GET", url, true);
  48697. xhr.responseType = "blob";
  48698. xhr.addEventListener("load", function () {
  48699. if (xhr.status === 200) {
  48700. // Blob as response (XHR2)
  48701. blob = xhr.response;
  48702. var transaction = _this.db.transaction(["textures"], "readwrite");
  48703. // the transaction could abort because of a QuotaExceededError error
  48704. transaction.onabort = function (event) {
  48705. try {
  48706. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  48707. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48708. _this.hasReachedQuota = true;
  48709. }
  48710. }
  48711. catch (ex) { }
  48712. generateBlobUrl();
  48713. };
  48714. transaction.oncomplete = function (event) {
  48715. generateBlobUrl();
  48716. };
  48717. var newTexture = { textureUrl: url, data: blob };
  48718. try {
  48719. // Put the blob into the dabase
  48720. var addRequest = transaction.objectStore("textures").put(newTexture);
  48721. addRequest.onsuccess = function (event) {
  48722. };
  48723. addRequest.onerror = function (event) {
  48724. generateBlobUrl();
  48725. };
  48726. }
  48727. catch (ex) {
  48728. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  48729. if (ex.code === 25) {
  48730. Database.IsUASupportingBlobStorage = false;
  48731. }
  48732. image.src = url;
  48733. }
  48734. }
  48735. else {
  48736. image.src = url;
  48737. }
  48738. }, false);
  48739. xhr.addEventListener("error", function (event) {
  48740. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  48741. image.src = url;
  48742. }, false);
  48743. xhr.send();
  48744. }
  48745. else {
  48746. image.src = url;
  48747. }
  48748. }
  48749. else {
  48750. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48751. image.src = url;
  48752. }
  48753. };
  48754. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  48755. var _this = this;
  48756. var updateVersion = function (event) {
  48757. // the version is not yet in the DB or we need to update it
  48758. _this._saveVersionIntoDBAsync(url, versionLoaded);
  48759. };
  48760. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  48761. };
  48762. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  48763. var _this = this;
  48764. if (this.isSupported) {
  48765. var version;
  48766. try {
  48767. var transaction = this.db.transaction(["versions"]);
  48768. transaction.oncomplete = function (event) {
  48769. if (version) {
  48770. // If the version in the JSON file is > than the version in DB
  48771. if (_this.manifestVersionFound > version.data) {
  48772. _this.mustUpdateRessources = true;
  48773. updateInDBCallback();
  48774. }
  48775. else {
  48776. callback(version.data);
  48777. }
  48778. }
  48779. else {
  48780. _this.mustUpdateRessources = true;
  48781. updateInDBCallback();
  48782. }
  48783. };
  48784. transaction.onabort = function (event) {
  48785. callback(-1);
  48786. };
  48787. var getRequest = transaction.objectStore("versions").get(url);
  48788. getRequest.onsuccess = function (event) {
  48789. version = (event.target).result;
  48790. };
  48791. getRequest.onerror = function (event) {
  48792. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  48793. callback(-1);
  48794. };
  48795. }
  48796. catch (ex) {
  48797. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  48798. callback(-1);
  48799. }
  48800. }
  48801. else {
  48802. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48803. callback(-1);
  48804. }
  48805. };
  48806. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  48807. var _this = this;
  48808. if (this.isSupported && !this.hasReachedQuota) {
  48809. try {
  48810. // Open a transaction to the database
  48811. var transaction = this.db.transaction(["versions"], "readwrite");
  48812. // the transaction could abort because of a QuotaExceededError error
  48813. transaction.onabort = function (event) {
  48814. try {
  48815. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48816. _this.hasReachedQuota = true;
  48817. }
  48818. }
  48819. catch (ex) { }
  48820. callback(-1);
  48821. };
  48822. transaction.oncomplete = function (event) {
  48823. callback(_this.manifestVersionFound);
  48824. };
  48825. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  48826. // Put the scene into the database
  48827. var addRequest = transaction.objectStore("versions").put(newVersion);
  48828. addRequest.onsuccess = function (event) {
  48829. };
  48830. addRequest.onerror = function (event) {
  48831. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  48832. };
  48833. }
  48834. catch (ex) {
  48835. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  48836. callback(-1);
  48837. }
  48838. }
  48839. else {
  48840. callback(-1);
  48841. }
  48842. };
  48843. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  48844. var _this = this;
  48845. var completeUrl = Database.ReturnFullUrlLocation(url);
  48846. var saveAndLoadFile = function (event) {
  48847. // the scene is not yet in the DB, let's try to save it
  48848. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  48849. };
  48850. this._checkVersionFromDB(completeUrl, function (version) {
  48851. if (version !== -1) {
  48852. if (!_this.mustUpdateRessources) {
  48853. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  48854. }
  48855. else {
  48856. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  48857. }
  48858. }
  48859. else {
  48860. errorCallback();
  48861. }
  48862. });
  48863. };
  48864. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  48865. if (this.isSupported) {
  48866. var targetStore;
  48867. if (url.indexOf(".babylon") !== -1) {
  48868. targetStore = "scenes";
  48869. }
  48870. else {
  48871. targetStore = "textures";
  48872. }
  48873. var file;
  48874. var transaction = this.db.transaction([targetStore]);
  48875. transaction.oncomplete = function (event) {
  48876. if (file) {
  48877. callback(file.data);
  48878. }
  48879. else {
  48880. notInDBCallback();
  48881. }
  48882. };
  48883. transaction.onabort = function (event) {
  48884. notInDBCallback();
  48885. };
  48886. var getRequest = transaction.objectStore(targetStore).get(url);
  48887. getRequest.onsuccess = function (event) {
  48888. file = (event.target).result;
  48889. };
  48890. getRequest.onerror = function (event) {
  48891. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  48892. notInDBCallback();
  48893. };
  48894. }
  48895. else {
  48896. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48897. callback();
  48898. }
  48899. };
  48900. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  48901. var _this = this;
  48902. if (this.isSupported) {
  48903. var targetStore;
  48904. if (url.indexOf(".babylon") !== -1) {
  48905. targetStore = "scenes";
  48906. }
  48907. else {
  48908. targetStore = "textures";
  48909. }
  48910. // Create XHR
  48911. var xhr = new XMLHttpRequest(), fileData;
  48912. xhr.open("GET", url, true);
  48913. if (useArrayBuffer) {
  48914. xhr.responseType = "arraybuffer";
  48915. }
  48916. xhr.onprogress = progressCallback;
  48917. xhr.addEventListener("load", function () {
  48918. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  48919. // Blob as response (XHR2)
  48920. //fileData = xhr.responseText;
  48921. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  48922. if (!_this.hasReachedQuota) {
  48923. // Open a transaction to the database
  48924. var transaction = _this.db.transaction([targetStore], "readwrite");
  48925. // the transaction could abort because of a QuotaExceededError error
  48926. transaction.onabort = function (event) {
  48927. try {
  48928. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  48929. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  48930. _this.hasReachedQuota = true;
  48931. }
  48932. }
  48933. catch (ex) { }
  48934. callback(fileData);
  48935. };
  48936. transaction.oncomplete = function (event) {
  48937. callback(fileData);
  48938. };
  48939. var newFile;
  48940. if (targetStore === "scenes") {
  48941. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  48942. }
  48943. else {
  48944. newFile = { textureUrl: url, data: fileData };
  48945. }
  48946. try {
  48947. // Put the scene into the database
  48948. var addRequest = transaction.objectStore(targetStore).put(newFile);
  48949. addRequest.onsuccess = function (event) {
  48950. };
  48951. addRequest.onerror = function (event) {
  48952. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  48953. };
  48954. }
  48955. catch (ex) {
  48956. callback(fileData);
  48957. }
  48958. }
  48959. else {
  48960. callback(fileData);
  48961. }
  48962. }
  48963. else {
  48964. callback();
  48965. }
  48966. }, false);
  48967. xhr.addEventListener("error", function (event) {
  48968. BABYLON.Tools.Error("error on XHR request.");
  48969. callback();
  48970. }, false);
  48971. xhr.send();
  48972. }
  48973. else {
  48974. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  48975. callback();
  48976. }
  48977. };
  48978. Database.IsUASupportingBlobStorage = true;
  48979. Database.IDBStorageEnabled = true;
  48980. Database.parseURL = function (url) {
  48981. var a = document.createElement('a');
  48982. a.href = url;
  48983. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  48984. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  48985. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  48986. return absLocation;
  48987. };
  48988. Database.ReturnFullUrlLocation = function (url) {
  48989. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  48990. return (Database.parseURL(window.location.href) + url);
  48991. }
  48992. else {
  48993. return url;
  48994. }
  48995. };
  48996. return Database;
  48997. }());
  48998. BABYLON.Database = Database;
  48999. })(BABYLON || (BABYLON = {}));
  49000. //# sourceMappingURL=babylon.database.js.map
  49001. var BABYLON;
  49002. (function (BABYLON) {
  49003. var FresnelParameters = (function () {
  49004. function FresnelParameters() {
  49005. this._isEnabled = true;
  49006. this.leftColor = BABYLON.Color3.White();
  49007. this.rightColor = BABYLON.Color3.Black();
  49008. this.bias = 0;
  49009. this.power = 1;
  49010. }
  49011. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  49012. get: function () {
  49013. return this._isEnabled;
  49014. },
  49015. set: function (value) {
  49016. if (this._isEnabled === value) {
  49017. return;
  49018. }
  49019. this._isEnabled = value;
  49020. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  49021. },
  49022. enumerable: true,
  49023. configurable: true
  49024. });
  49025. FresnelParameters.prototype.clone = function () {
  49026. var newFresnelParameters = new FresnelParameters();
  49027. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  49028. return newFresnelParameters;
  49029. };
  49030. FresnelParameters.prototype.serialize = function () {
  49031. var serializationObject = {};
  49032. serializationObject.isEnabled = this.isEnabled;
  49033. serializationObject.leftColor = this.leftColor;
  49034. serializationObject.rightColor = this.rightColor;
  49035. serializationObject.bias = this.bias;
  49036. serializationObject.power = this.power;
  49037. return serializationObject;
  49038. };
  49039. FresnelParameters.Parse = function (parsedFresnelParameters) {
  49040. var fresnelParameters = new FresnelParameters();
  49041. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  49042. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  49043. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  49044. fresnelParameters.bias = parsedFresnelParameters.bias;
  49045. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  49046. return fresnelParameters;
  49047. };
  49048. return FresnelParameters;
  49049. }());
  49050. BABYLON.FresnelParameters = FresnelParameters;
  49051. })(BABYLON || (BABYLON = {}));
  49052. //# sourceMappingURL=babylon.fresnelParameters.js.map
  49053. var BABYLON;
  49054. (function (BABYLON) {
  49055. var MultiMaterial = (function (_super) {
  49056. __extends(MultiMaterial, _super);
  49057. function MultiMaterial(name, scene) {
  49058. var _this = _super.call(this, name, scene, true) || this;
  49059. scene.multiMaterials.push(_this);
  49060. _this.subMaterials = new Array();
  49061. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  49062. return _this;
  49063. }
  49064. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  49065. get: function () {
  49066. return this._subMaterials;
  49067. },
  49068. set: function (value) {
  49069. this._subMaterials = value;
  49070. this._hookArray(value);
  49071. },
  49072. enumerable: true,
  49073. configurable: true
  49074. });
  49075. MultiMaterial.prototype._hookArray = function (array) {
  49076. var _this = this;
  49077. var oldPush = array.push;
  49078. array.push = function () {
  49079. var items = [];
  49080. for (var _i = 0; _i < arguments.length; _i++) {
  49081. items[_i] = arguments[_i];
  49082. }
  49083. var result = oldPush.apply(array, items);
  49084. _this._markAllSubMeshesAsTexturesDirty();
  49085. return result;
  49086. };
  49087. var oldSplice = array.splice;
  49088. array.splice = function (index, deleteCount) {
  49089. var deleted = oldSplice.apply(array, [index, deleteCount]);
  49090. _this._markAllSubMeshesAsTexturesDirty();
  49091. return deleted;
  49092. };
  49093. };
  49094. // Properties
  49095. MultiMaterial.prototype.getSubMaterial = function (index) {
  49096. if (index < 0 || index >= this.subMaterials.length) {
  49097. return this.getScene().defaultMaterial;
  49098. }
  49099. return this.subMaterials[index];
  49100. };
  49101. MultiMaterial.prototype.getActiveTextures = function () {
  49102. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  49103. var _a;
  49104. };
  49105. // Methods
  49106. MultiMaterial.prototype.getClassName = function () {
  49107. return "MultiMaterial";
  49108. };
  49109. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  49110. for (var index = 0; index < this.subMaterials.length; index++) {
  49111. var subMaterial = this.subMaterials[index];
  49112. if (subMaterial) {
  49113. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  49114. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  49115. return false;
  49116. }
  49117. continue;
  49118. }
  49119. if (!this.subMaterials[index].isReady(mesh)) {
  49120. return false;
  49121. }
  49122. }
  49123. }
  49124. return true;
  49125. };
  49126. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  49127. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  49128. for (var index = 0; index < this.subMaterials.length; index++) {
  49129. var subMaterial = null;
  49130. if (cloneChildren) {
  49131. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  49132. }
  49133. else {
  49134. subMaterial = this.subMaterials[index];
  49135. }
  49136. newMultiMaterial.subMaterials.push(subMaterial);
  49137. }
  49138. return newMultiMaterial;
  49139. };
  49140. MultiMaterial.prototype.serialize = function () {
  49141. var serializationObject = {};
  49142. serializationObject.name = this.name;
  49143. serializationObject.id = this.id;
  49144. serializationObject.tags = BABYLON.Tags.GetTags(this);
  49145. serializationObject.materials = [];
  49146. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  49147. var subMat = this.subMaterials[matIndex];
  49148. if (subMat) {
  49149. serializationObject.materials.push(subMat.id);
  49150. }
  49151. else {
  49152. serializationObject.materials.push(null);
  49153. }
  49154. }
  49155. return serializationObject;
  49156. };
  49157. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49158. var scene = this.getScene();
  49159. if (!scene) {
  49160. return;
  49161. }
  49162. var index = scene.multiMaterials.indexOf(this);
  49163. if (index >= 0) {
  49164. scene.multiMaterials.splice(index, 1);
  49165. }
  49166. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49167. };
  49168. return MultiMaterial;
  49169. }(BABYLON.Material));
  49170. BABYLON.MultiMaterial = MultiMaterial;
  49171. })(BABYLON || (BABYLON = {}));
  49172. //# sourceMappingURL=babylon.multiMaterial.js.map
  49173. var BABYLON;
  49174. (function (BABYLON) {
  49175. var FreeCameraTouchInput = (function () {
  49176. function FreeCameraTouchInput() {
  49177. this._offsetX = null;
  49178. this._offsetY = null;
  49179. this._pointerCount = 0;
  49180. this._pointerPressed = [];
  49181. this.touchAngularSensibility = 200000.0;
  49182. this.touchMoveSensibility = 250.0;
  49183. }
  49184. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  49185. var _this = this;
  49186. var previousPosition;
  49187. if (this._pointerInput === undefined) {
  49188. this._onLostFocus = function (evt) {
  49189. _this._offsetX = null;
  49190. _this._offsetY = null;
  49191. };
  49192. this._pointerInput = function (p, s) {
  49193. var evt = p.event;
  49194. if (evt.pointerType === "mouse") {
  49195. return;
  49196. }
  49197. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  49198. if (!noPreventDefault) {
  49199. evt.preventDefault();
  49200. }
  49201. _this._pointerPressed.push(evt.pointerId);
  49202. if (_this._pointerPressed.length !== 1) {
  49203. return;
  49204. }
  49205. previousPosition = {
  49206. x: evt.clientX,
  49207. y: evt.clientY
  49208. };
  49209. }
  49210. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  49211. if (!noPreventDefault) {
  49212. evt.preventDefault();
  49213. }
  49214. var index = _this._pointerPressed.indexOf(evt.pointerId);
  49215. if (index === -1) {
  49216. return;
  49217. }
  49218. _this._pointerPressed.splice(index, 1);
  49219. if (index != 0) {
  49220. return;
  49221. }
  49222. previousPosition = null;
  49223. _this._offsetX = null;
  49224. _this._offsetY = null;
  49225. }
  49226. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49227. if (!noPreventDefault) {
  49228. evt.preventDefault();
  49229. }
  49230. if (!previousPosition) {
  49231. return;
  49232. }
  49233. var index = _this._pointerPressed.indexOf(evt.pointerId);
  49234. if (index != 0) {
  49235. return;
  49236. }
  49237. _this._offsetX = evt.clientX - previousPosition.x;
  49238. _this._offsetY = -(evt.clientY - previousPosition.y);
  49239. }
  49240. };
  49241. }
  49242. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49243. element.addEventListener("blur", this._onLostFocus);
  49244. };
  49245. FreeCameraTouchInput.prototype.detachControl = function (element) {
  49246. if (this._pointerInput && element) {
  49247. this.camera.getScene().onPointerObservable.remove(this._observer);
  49248. this._observer = null;
  49249. element.removeEventListener("blur", this._onLostFocus);
  49250. this._onLostFocus = null;
  49251. this._pointerPressed = [];
  49252. this._offsetX = null;
  49253. this._offsetY = null;
  49254. this._pointerCount = 0;
  49255. }
  49256. };
  49257. FreeCameraTouchInput.prototype.checkInputs = function () {
  49258. if (this._offsetX) {
  49259. var camera = this.camera;
  49260. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  49261. if (this._pointerPressed.length > 1) {
  49262. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  49263. }
  49264. else {
  49265. var speed = camera._computeLocalCameraSpeed();
  49266. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  49267. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  49268. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  49269. }
  49270. }
  49271. };
  49272. FreeCameraTouchInput.prototype.getClassName = function () {
  49273. return "FreeCameraTouchInput";
  49274. };
  49275. FreeCameraTouchInput.prototype.getSimpleName = function () {
  49276. return "touch";
  49277. };
  49278. __decorate([
  49279. BABYLON.serialize()
  49280. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  49281. __decorate([
  49282. BABYLON.serialize()
  49283. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  49284. return FreeCameraTouchInput;
  49285. }());
  49286. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  49287. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  49288. })(BABYLON || (BABYLON = {}));
  49289. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  49290. /// <reference path="babylon.freeCamera.ts" />
  49291. var BABYLON;
  49292. (function (BABYLON) {
  49293. // We're mainly based on the logic defined into the FreeCamera code
  49294. var TouchCamera = (function (_super) {
  49295. __extends(TouchCamera, _super);
  49296. //-- end properties for backward compatibility for inputs
  49297. function TouchCamera(name, position, scene) {
  49298. var _this = _super.call(this, name, position, scene) || this;
  49299. _this.inputs.addTouch();
  49300. _this._setupInputs();
  49301. return _this;
  49302. }
  49303. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  49304. //-- Begin properties for backward compatibility for inputs
  49305. get: function () {
  49306. var touch = this.inputs.attached["touch"];
  49307. if (touch)
  49308. return touch.touchAngularSensibility;
  49309. },
  49310. set: function (value) {
  49311. var touch = this.inputs.attached["touch"];
  49312. if (touch)
  49313. touch.touchAngularSensibility = value;
  49314. },
  49315. enumerable: true,
  49316. configurable: true
  49317. });
  49318. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  49319. get: function () {
  49320. var touch = this.inputs.attached["touch"];
  49321. if (touch)
  49322. return touch.touchMoveSensibility;
  49323. },
  49324. set: function (value) {
  49325. var touch = this.inputs.attached["touch"];
  49326. if (touch)
  49327. touch.touchMoveSensibility = value;
  49328. },
  49329. enumerable: true,
  49330. configurable: true
  49331. });
  49332. TouchCamera.prototype.getClassName = function () {
  49333. return "TouchCamera";
  49334. };
  49335. TouchCamera.prototype._setupInputs = function () {
  49336. var mouse = this.inputs.attached["mouse"];
  49337. if (mouse) {
  49338. mouse.touchEnabled = false;
  49339. }
  49340. };
  49341. return TouchCamera;
  49342. }(BABYLON.FreeCamera));
  49343. BABYLON.TouchCamera = TouchCamera;
  49344. })(BABYLON || (BABYLON = {}));
  49345. //# sourceMappingURL=babylon.touchCamera.js.map
  49346. var BABYLON;
  49347. (function (BABYLON) {
  49348. var ProceduralTexture = (function (_super) {
  49349. __extends(ProceduralTexture, _super);
  49350. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  49351. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49352. if (isCube === void 0) { isCube = false; }
  49353. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49354. _this.isCube = isCube;
  49355. _this.isEnabled = true;
  49356. _this._currentRefreshId = -1;
  49357. _this._refreshRate = 1;
  49358. _this._vertexBuffers = {};
  49359. _this._uniforms = new Array();
  49360. _this._samplers = new Array();
  49361. _this._textures = new Array();
  49362. _this._floats = new Array();
  49363. _this._floatsArrays = {};
  49364. _this._colors3 = new Array();
  49365. _this._colors4 = new Array();
  49366. _this._vectors2 = new Array();
  49367. _this._vectors3 = new Array();
  49368. _this._matrices = new Array();
  49369. _this._fallbackTextureUsed = false;
  49370. scene._proceduralTextures.push(_this);
  49371. _this.name = name;
  49372. _this.isRenderTarget = true;
  49373. _this._size = size;
  49374. _this._generateMipMaps = generateMipMaps;
  49375. _this.setFragment(fragment);
  49376. _this._fallbackTexture = fallbackTexture;
  49377. var engine = scene.getEngine();
  49378. if (isCube) {
  49379. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  49380. _this.setFloat("face", 0);
  49381. }
  49382. else {
  49383. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  49384. }
  49385. // VBO
  49386. var vertices = [];
  49387. vertices.push(1, 1);
  49388. vertices.push(-1, 1);
  49389. vertices.push(-1, -1);
  49390. vertices.push(1, -1);
  49391. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49392. // Indices
  49393. var indices = [];
  49394. indices.push(0);
  49395. indices.push(1);
  49396. indices.push(2);
  49397. indices.push(0);
  49398. indices.push(2);
  49399. indices.push(3);
  49400. _this._indexBuffer = engine.createIndexBuffer(indices);
  49401. return _this;
  49402. }
  49403. ProceduralTexture.prototype.reset = function () {
  49404. if (this._effect === undefined) {
  49405. return;
  49406. }
  49407. var engine = this.getScene().getEngine();
  49408. engine._releaseEffect(this._effect);
  49409. };
  49410. ProceduralTexture.prototype.isReady = function () {
  49411. var _this = this;
  49412. var engine = this.getScene().getEngine();
  49413. var shaders;
  49414. if (!this._fragment) {
  49415. return false;
  49416. }
  49417. if (this._fallbackTextureUsed) {
  49418. return true;
  49419. }
  49420. if (this._fragment.fragmentElement !== undefined) {
  49421. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  49422. }
  49423. else {
  49424. shaders = { vertex: "procedural", fragment: this._fragment };
  49425. }
  49426. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  49427. _this.releaseInternalTexture();
  49428. if (_this._fallbackTexture) {
  49429. _this._texture = _this._fallbackTexture._texture;
  49430. _this._texture.references++;
  49431. }
  49432. _this._fallbackTextureUsed = true;
  49433. });
  49434. return this._effect.isReady();
  49435. };
  49436. ProceduralTexture.prototype.resetRefreshCounter = function () {
  49437. this._currentRefreshId = -1;
  49438. };
  49439. ProceduralTexture.prototype.setFragment = function (fragment) {
  49440. this._fragment = fragment;
  49441. };
  49442. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  49443. get: function () {
  49444. return this._refreshRate;
  49445. },
  49446. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49447. set: function (value) {
  49448. this._refreshRate = value;
  49449. this.resetRefreshCounter();
  49450. },
  49451. enumerable: true,
  49452. configurable: true
  49453. });
  49454. ProceduralTexture.prototype._shouldRender = function () {
  49455. if (!this.isEnabled || !this.isReady() || !this._texture) {
  49456. return false;
  49457. }
  49458. if (this._fallbackTextureUsed) {
  49459. return false;
  49460. }
  49461. if (this._currentRefreshId === -1) {
  49462. this._currentRefreshId = 1;
  49463. return true;
  49464. }
  49465. if (this.refreshRate === this._currentRefreshId) {
  49466. this._currentRefreshId = 1;
  49467. return true;
  49468. }
  49469. this._currentRefreshId++;
  49470. return false;
  49471. };
  49472. ProceduralTexture.prototype.getRenderSize = function () {
  49473. return this._size;
  49474. };
  49475. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  49476. if (this._fallbackTextureUsed) {
  49477. return;
  49478. }
  49479. this.releaseInternalTexture();
  49480. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  49481. };
  49482. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  49483. if (this._uniforms.indexOf(uniformName) === -1) {
  49484. this._uniforms.push(uniformName);
  49485. }
  49486. };
  49487. ProceduralTexture.prototype.setTexture = function (name, texture) {
  49488. if (this._samplers.indexOf(name) === -1) {
  49489. this._samplers.push(name);
  49490. }
  49491. this._textures[name] = texture;
  49492. return this;
  49493. };
  49494. ProceduralTexture.prototype.setFloat = function (name, value) {
  49495. this._checkUniform(name);
  49496. this._floats[name] = value;
  49497. return this;
  49498. };
  49499. ProceduralTexture.prototype.setFloats = function (name, value) {
  49500. this._checkUniform(name);
  49501. this._floatsArrays[name] = value;
  49502. return this;
  49503. };
  49504. ProceduralTexture.prototype.setColor3 = function (name, value) {
  49505. this._checkUniform(name);
  49506. this._colors3[name] = value;
  49507. return this;
  49508. };
  49509. ProceduralTexture.prototype.setColor4 = function (name, value) {
  49510. this._checkUniform(name);
  49511. this._colors4[name] = value;
  49512. return this;
  49513. };
  49514. ProceduralTexture.prototype.setVector2 = function (name, value) {
  49515. this._checkUniform(name);
  49516. this._vectors2[name] = value;
  49517. return this;
  49518. };
  49519. ProceduralTexture.prototype.setVector3 = function (name, value) {
  49520. this._checkUniform(name);
  49521. this._vectors3[name] = value;
  49522. return this;
  49523. };
  49524. ProceduralTexture.prototype.setMatrix = function (name, value) {
  49525. this._checkUniform(name);
  49526. this._matrices[name] = value;
  49527. return this;
  49528. };
  49529. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  49530. var scene = this.getScene();
  49531. var engine = scene.getEngine();
  49532. // Render
  49533. engine.enableEffect(this._effect);
  49534. engine.setState(false);
  49535. // Texture
  49536. for (var name in this._textures) {
  49537. this._effect.setTexture(name, this._textures[name]);
  49538. }
  49539. // Float
  49540. for (name in this._floats) {
  49541. this._effect.setFloat(name, this._floats[name]);
  49542. }
  49543. // Floats
  49544. for (name in this._floatsArrays) {
  49545. this._effect.setArray(name, this._floatsArrays[name]);
  49546. }
  49547. // Color3
  49548. for (name in this._colors3) {
  49549. this._effect.setColor3(name, this._colors3[name]);
  49550. }
  49551. // Color4
  49552. for (name in this._colors4) {
  49553. var color = this._colors4[name];
  49554. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49555. }
  49556. // Vector2
  49557. for (name in this._vectors2) {
  49558. this._effect.setVector2(name, this._vectors2[name]);
  49559. }
  49560. // Vector3
  49561. for (name in this._vectors3) {
  49562. this._effect.setVector3(name, this._vectors3[name]);
  49563. }
  49564. // Matrix
  49565. for (name in this._matrices) {
  49566. this._effect.setMatrix(name, this._matrices[name]);
  49567. }
  49568. if (this.isCube) {
  49569. for (var face = 0; face < 6; face++) {
  49570. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  49571. // VBOs
  49572. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49573. this._effect.setFloat("face", face);
  49574. // Clear
  49575. engine.clear(scene.clearColor, true, true, true);
  49576. // Draw order
  49577. engine.draw(true, 0, 6);
  49578. // Mipmaps
  49579. if (face === 5) {
  49580. engine.generateMipMapsForCubemap(this._texture);
  49581. }
  49582. }
  49583. }
  49584. else {
  49585. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  49586. // VBOs
  49587. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49588. // Clear
  49589. engine.clear(scene.clearColor, true, true, true);
  49590. // Draw order
  49591. engine.draw(true, 0, 6);
  49592. }
  49593. // Unbind
  49594. engine.unBindFramebuffer(this._texture, this.isCube);
  49595. if (this.onGenerated) {
  49596. this.onGenerated();
  49597. }
  49598. };
  49599. ProceduralTexture.prototype.clone = function () {
  49600. var textureSize = this.getSize();
  49601. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  49602. // Base texture
  49603. newTexture.hasAlpha = this.hasAlpha;
  49604. newTexture.level = this.level;
  49605. // RenderTarget Texture
  49606. newTexture.coordinatesMode = this.coordinatesMode;
  49607. return newTexture;
  49608. };
  49609. ProceduralTexture.prototype.dispose = function () {
  49610. var index = this.getScene()._proceduralTextures.indexOf(this);
  49611. if (index >= 0) {
  49612. this.getScene()._proceduralTextures.splice(index, 1);
  49613. }
  49614. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  49615. if (vertexBuffer) {
  49616. vertexBuffer.dispose();
  49617. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  49618. }
  49619. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  49620. this._indexBuffer = null;
  49621. }
  49622. _super.prototype.dispose.call(this);
  49623. };
  49624. return ProceduralTexture;
  49625. }(BABYLON.Texture));
  49626. BABYLON.ProceduralTexture = ProceduralTexture;
  49627. })(BABYLON || (BABYLON = {}));
  49628. //# sourceMappingURL=babylon.proceduralTexture.js.map
  49629. /// <reference path="babylon.proceduralTexture.ts" />
  49630. var BABYLON;
  49631. (function (BABYLON) {
  49632. var CustomProceduralTexture = (function (_super) {
  49633. __extends(CustomProceduralTexture, _super);
  49634. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  49635. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  49636. _this._animate = true;
  49637. _this._time = 0;
  49638. _this._texturePath = texturePath;
  49639. //Try to load json
  49640. _this.loadJson(texturePath);
  49641. _this.refreshRate = 1;
  49642. return _this;
  49643. }
  49644. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  49645. var _this = this;
  49646. var that = this;
  49647. function noConfigFile() {
  49648. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  49649. try {
  49650. that.setFragment(that._texturePath);
  49651. }
  49652. catch (ex) {
  49653. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  49654. }
  49655. }
  49656. var configFileUrl = jsonUrl + "/config.json";
  49657. var xhr = new XMLHttpRequest();
  49658. xhr.open("GET", configFileUrl, true);
  49659. xhr.addEventListener("load", function () {
  49660. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49661. try {
  49662. _this._config = JSON.parse(xhr.response);
  49663. _this.updateShaderUniforms();
  49664. _this.updateTextures();
  49665. _this.setFragment(_this._texturePath + "/custom");
  49666. _this._animate = _this._config.animate;
  49667. _this.refreshRate = _this._config.refreshrate;
  49668. }
  49669. catch (ex) {
  49670. noConfigFile();
  49671. }
  49672. }
  49673. else {
  49674. noConfigFile();
  49675. }
  49676. }, false);
  49677. xhr.addEventListener("error", function () {
  49678. noConfigFile();
  49679. }, false);
  49680. try {
  49681. xhr.send();
  49682. }
  49683. catch (ex) {
  49684. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  49685. }
  49686. };
  49687. CustomProceduralTexture.prototype.isReady = function () {
  49688. if (!_super.prototype.isReady.call(this)) {
  49689. return false;
  49690. }
  49691. for (var name in this._textures) {
  49692. var texture = this._textures[name];
  49693. if (!texture.isReady()) {
  49694. return false;
  49695. }
  49696. }
  49697. return true;
  49698. };
  49699. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  49700. if (this._animate) {
  49701. this._time += this.getScene().getAnimationRatio() * 0.03;
  49702. this.updateShaderUniforms();
  49703. }
  49704. _super.prototype.render.call(this, useCameraPostProcess);
  49705. };
  49706. CustomProceduralTexture.prototype.updateTextures = function () {
  49707. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  49708. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  49709. }
  49710. };
  49711. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  49712. if (this._config) {
  49713. for (var j = 0; j < this._config.uniforms.length; j++) {
  49714. var uniform = this._config.uniforms[j];
  49715. switch (uniform.type) {
  49716. case "float":
  49717. this.setFloat(uniform.name, uniform.value);
  49718. break;
  49719. case "color3":
  49720. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  49721. break;
  49722. case "color4":
  49723. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  49724. break;
  49725. case "vector2":
  49726. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  49727. break;
  49728. case "vector3":
  49729. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  49730. break;
  49731. }
  49732. }
  49733. }
  49734. this.setFloat("time", this._time);
  49735. };
  49736. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  49737. get: function () {
  49738. return this._animate;
  49739. },
  49740. set: function (value) {
  49741. this._animate = value;
  49742. },
  49743. enumerable: true,
  49744. configurable: true
  49745. });
  49746. return CustomProceduralTexture;
  49747. }(BABYLON.ProceduralTexture));
  49748. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  49749. })(BABYLON || (BABYLON = {}));
  49750. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  49751. var BABYLON;
  49752. (function (BABYLON) {
  49753. var FreeCameraGamepadInput = (function () {
  49754. function FreeCameraGamepadInput() {
  49755. this.gamepadAngularSensibility = 200;
  49756. this.gamepadMoveSensibility = 40;
  49757. // private members
  49758. this._cameraTransform = BABYLON.Matrix.Identity();
  49759. this._deltaTransform = BABYLON.Vector3.Zero();
  49760. this._vector3 = BABYLON.Vector3.Zero();
  49761. this._vector2 = BABYLON.Vector2.Zero();
  49762. }
  49763. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  49764. var _this = this;
  49765. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  49766. };
  49767. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  49768. if (this._gamepads) {
  49769. this._gamepads.dispose();
  49770. }
  49771. this.gamepad = null;
  49772. };
  49773. FreeCameraGamepadInput.prototype.checkInputs = function () {
  49774. if (this.gamepad && this.gamepad.leftStick) {
  49775. var camera = this.camera;
  49776. var LSValues = this.gamepad.leftStick;
  49777. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  49778. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  49779. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  49780. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  49781. var RSValues = this.gamepad.rightStick;
  49782. if (RSValues) {
  49783. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  49784. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  49785. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  49786. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  49787. }
  49788. else {
  49789. RSValues = { x: 0, y: 0 };
  49790. }
  49791. if (!camera.rotationQuaternion) {
  49792. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  49793. }
  49794. else {
  49795. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  49796. }
  49797. var speed = camera._computeLocalCameraSpeed() * 50.0;
  49798. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  49799. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  49800. camera.cameraDirection.addInPlace(this._deltaTransform);
  49801. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  49802. camera.cameraRotation.addInPlace(this._vector2);
  49803. }
  49804. };
  49805. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  49806. // Only the first gamepad found can control the camera
  49807. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  49808. // prioritize XBOX gamepads.
  49809. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  49810. this.gamepad = gamepad;
  49811. }
  49812. }
  49813. };
  49814. FreeCameraGamepadInput.prototype.getClassName = function () {
  49815. return "FreeCameraGamepadInput";
  49816. };
  49817. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  49818. return "gamepad";
  49819. };
  49820. __decorate([
  49821. BABYLON.serialize()
  49822. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  49823. __decorate([
  49824. BABYLON.serialize()
  49825. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  49826. return FreeCameraGamepadInput;
  49827. }());
  49828. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  49829. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  49830. })(BABYLON || (BABYLON = {}));
  49831. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  49832. var BABYLON;
  49833. (function (BABYLON) {
  49834. var ArcRotateCameraGamepadInput = (function () {
  49835. function ArcRotateCameraGamepadInput() {
  49836. this.gamepadRotationSensibility = 80;
  49837. this.gamepadMoveSensibility = 40;
  49838. }
  49839. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  49840. var _this = this;
  49841. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  49842. };
  49843. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  49844. if (this._gamepads) {
  49845. this._gamepads.dispose();
  49846. }
  49847. this.gamepad = null;
  49848. };
  49849. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  49850. if (this.gamepad) {
  49851. var camera = this.camera;
  49852. var RSValues = this.gamepad.rightStick;
  49853. if (RSValues) {
  49854. if (RSValues.x != 0) {
  49855. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  49856. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  49857. camera.inertialAlphaOffset += normalizedRX;
  49858. }
  49859. }
  49860. if (RSValues.y != 0) {
  49861. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  49862. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  49863. camera.inertialBetaOffset += normalizedRY;
  49864. }
  49865. }
  49866. }
  49867. var LSValues = this.gamepad.leftStick;
  49868. if (LSValues && LSValues.y != 0) {
  49869. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  49870. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  49871. this.camera.inertialRadiusOffset -= normalizedLY;
  49872. }
  49873. }
  49874. }
  49875. };
  49876. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  49877. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  49878. // prioritize XBOX gamepads.
  49879. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  49880. this.gamepad = gamepad;
  49881. }
  49882. }
  49883. };
  49884. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  49885. return "ArcRotateCameraGamepadInput";
  49886. };
  49887. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  49888. return "gamepad";
  49889. };
  49890. __decorate([
  49891. BABYLON.serialize()
  49892. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  49893. __decorate([
  49894. BABYLON.serialize()
  49895. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  49896. return ArcRotateCameraGamepadInput;
  49897. }());
  49898. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  49899. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  49900. })(BABYLON || (BABYLON = {}));
  49901. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  49902. var BABYLON;
  49903. (function (BABYLON) {
  49904. var Gamepads = (function () {
  49905. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  49906. var _this = this;
  49907. this.babylonGamepads = [];
  49908. this.oneGamepadConnected = false;
  49909. this.isMonitoring = false;
  49910. this.gamepadEventSupported = 'GamepadEvent' in window;
  49911. this.gamepadSupport = (navigator.getGamepads ||
  49912. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  49913. this._callbackGamepadConnected = ongamedpadconnected;
  49914. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  49915. if (this.gamepadSupport) {
  49916. //first add already-connected gamepads
  49917. this._updateGamepadObjects();
  49918. if (this.babylonGamepads.length) {
  49919. this._startMonitoringGamepads();
  49920. }
  49921. // Checking if the gamepad connected event is supported (like in Firefox)
  49922. if (this.gamepadEventSupported) {
  49923. this._onGamepadConnectedEvent = function (evt) {
  49924. _this._onGamepadConnected(evt.gamepad);
  49925. };
  49926. this._onGamepadDisonnectedEvent = function (evt) {
  49927. _this._onGamepadDisconnected(evt.gamepad);
  49928. };
  49929. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49930. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49931. }
  49932. else {
  49933. this._startMonitoringGamepads();
  49934. }
  49935. }
  49936. }
  49937. Gamepads.prototype.dispose = function () {
  49938. if (this._onGamepadConnectedEvent) {
  49939. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49940. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49941. this._onGamepadConnectedEvent = null;
  49942. this._onGamepadDisonnectedEvent = null;
  49943. }
  49944. this.oneGamepadConnected = false;
  49945. this._stopMonitoringGamepads();
  49946. this.babylonGamepads = [];
  49947. };
  49948. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  49949. // Protection code for Chrome which has a very buggy gamepad implementation...
  49950. // And raises a connected event on disconnection for instance
  49951. if (gamepad.index in this.babylonGamepads) {
  49952. return;
  49953. }
  49954. var newGamepad = this._addNewGamepad(gamepad);
  49955. if (this._callbackGamepadConnected)
  49956. this._callbackGamepadConnected(newGamepad);
  49957. this._startMonitoringGamepads();
  49958. };
  49959. Gamepads.prototype._addNewGamepad = function (gamepad) {
  49960. if (!this.oneGamepadConnected) {
  49961. this.oneGamepadConnected = true;
  49962. }
  49963. var newGamepad;
  49964. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  49965. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  49966. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  49967. }
  49968. else if (gamepad.pose) {
  49969. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  49970. }
  49971. else {
  49972. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  49973. }
  49974. this.babylonGamepads.push(newGamepad);
  49975. return newGamepad;
  49976. };
  49977. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  49978. // Remove the gamepad from the list of gamepads to monitor.
  49979. for (var i in this.babylonGamepads) {
  49980. if (this.babylonGamepads[i].index == gamepad.index) {
  49981. this.babylonGamepads.splice(+i, 1);
  49982. break;
  49983. }
  49984. }
  49985. // If no gamepads are left, stop the polling loop.
  49986. if (this.babylonGamepads.length == 0) {
  49987. this._stopMonitoringGamepads();
  49988. this.oneGamepadConnected = false;
  49989. }
  49990. if (this._callbackGamepadDisconnected)
  49991. this._callbackGamepadDisconnected(gamepad);
  49992. };
  49993. Gamepads.prototype._startMonitoringGamepads = function () {
  49994. if (!this.isMonitoring) {
  49995. this.isMonitoring = true;
  49996. this._checkGamepadsStatus();
  49997. }
  49998. };
  49999. Gamepads.prototype._stopMonitoringGamepads = function () {
  50000. this.isMonitoring = false;
  50001. };
  50002. Gamepads.prototype._checkGamepadsStatus = function () {
  50003. var _this = this;
  50004. // Hack to be compatible Chrome
  50005. this._updateGamepadObjects();
  50006. for (var i in this.babylonGamepads) {
  50007. this.babylonGamepads[i].update();
  50008. }
  50009. if (this.isMonitoring) {
  50010. if (window.requestAnimationFrame) {
  50011. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50012. }
  50013. else if (window.mozRequestAnimationFrame) {
  50014. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50015. }
  50016. else if (window.webkitRequestAnimationFrame) {
  50017. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50018. }
  50019. }
  50020. };
  50021. // This function is called only on Chrome, which does not properly support
  50022. // connection/disconnection events and forces you to recopy again the gamepad object
  50023. Gamepads.prototype._updateGamepadObjects = function () {
  50024. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50025. for (var i = 0; i < gamepads.length; i++) {
  50026. if (gamepads[i]) {
  50027. if (!(gamepads[i].index in this.babylonGamepads)) {
  50028. var newGamepad = this._addNewGamepad(gamepads[i]);
  50029. if (this._callbackGamepadConnected) {
  50030. this._callbackGamepadConnected(newGamepad);
  50031. }
  50032. }
  50033. else {
  50034. // Forced to copy again this object for Chrome for unknown reason
  50035. this.babylonGamepads[i].browserGamepad = gamepads[i];
  50036. }
  50037. }
  50038. }
  50039. };
  50040. return Gamepads;
  50041. }());
  50042. BABYLON.Gamepads = Gamepads;
  50043. var StickValues = (function () {
  50044. function StickValues(x, y) {
  50045. this.x = x;
  50046. this.y = y;
  50047. }
  50048. return StickValues;
  50049. }());
  50050. BABYLON.StickValues = StickValues;
  50051. var Gamepad = (function () {
  50052. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  50053. if (leftStickX === void 0) { leftStickX = 0; }
  50054. if (leftStickY === void 0) { leftStickY = 1; }
  50055. if (rightStickX === void 0) { rightStickX = 2; }
  50056. if (rightStickY === void 0) { rightStickY = 3; }
  50057. this.id = id;
  50058. this.index = index;
  50059. this.browserGamepad = browserGamepad;
  50060. this.type = Gamepad.GAMEPAD;
  50061. this._leftStickAxisX = leftStickX;
  50062. this._leftStickAxisY = leftStickY;
  50063. this._rightStickAxisX = rightStickX;
  50064. this._rightStickAxisY = rightStickY;
  50065. if (this.browserGamepad.axes.length >= 2) {
  50066. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50067. }
  50068. if (this.browserGamepad.axes.length >= 4) {
  50069. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50070. }
  50071. }
  50072. Gamepad.prototype.onleftstickchanged = function (callback) {
  50073. this._onleftstickchanged = callback;
  50074. };
  50075. Gamepad.prototype.onrightstickchanged = function (callback) {
  50076. this._onrightstickchanged = callback;
  50077. };
  50078. Object.defineProperty(Gamepad.prototype, "leftStick", {
  50079. get: function () {
  50080. return this._leftStick;
  50081. },
  50082. set: function (newValues) {
  50083. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  50084. this._onleftstickchanged(newValues);
  50085. }
  50086. this._leftStick = newValues;
  50087. },
  50088. enumerable: true,
  50089. configurable: true
  50090. });
  50091. Object.defineProperty(Gamepad.prototype, "rightStick", {
  50092. get: function () {
  50093. return this._rightStick;
  50094. },
  50095. set: function (newValues) {
  50096. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  50097. this._onrightstickchanged(newValues);
  50098. }
  50099. this._rightStick = newValues;
  50100. },
  50101. enumerable: true,
  50102. configurable: true
  50103. });
  50104. Gamepad.prototype.update = function () {
  50105. if (this._leftStick) {
  50106. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50107. }
  50108. if (this._rightStick) {
  50109. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50110. }
  50111. };
  50112. Gamepad.GAMEPAD = 0;
  50113. Gamepad.GENERIC = 1;
  50114. Gamepad.XBOX = 2;
  50115. Gamepad.POSE_ENABLED = 3;
  50116. return Gamepad;
  50117. }());
  50118. BABYLON.Gamepad = Gamepad;
  50119. var GenericPad = (function (_super) {
  50120. __extends(GenericPad, _super);
  50121. function GenericPad(id, index, browserGamepad) {
  50122. var _this = _super.call(this, id, index, browserGamepad) || this;
  50123. _this.type = Gamepad.GENERIC;
  50124. _this._buttons = new Array(browserGamepad.buttons.length);
  50125. return _this;
  50126. }
  50127. GenericPad.prototype.onbuttondown = function (callback) {
  50128. this._onbuttondown = callback;
  50129. };
  50130. GenericPad.prototype.onbuttonup = function (callback) {
  50131. this._onbuttonup = callback;
  50132. };
  50133. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  50134. if (newValue !== currentValue) {
  50135. if (this._onbuttondown && newValue === 1) {
  50136. this._onbuttondown(buttonIndex);
  50137. }
  50138. if (this._onbuttonup && newValue === 0) {
  50139. this._onbuttonup(buttonIndex);
  50140. }
  50141. }
  50142. return newValue;
  50143. };
  50144. GenericPad.prototype.update = function () {
  50145. _super.prototype.update.call(this);
  50146. for (var index = 0; index < this._buttons.length; index++) {
  50147. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  50148. }
  50149. };
  50150. return GenericPad;
  50151. }(Gamepad));
  50152. BABYLON.GenericPad = GenericPad;
  50153. var Xbox360Button;
  50154. (function (Xbox360Button) {
  50155. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  50156. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  50157. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  50158. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  50159. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  50160. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  50161. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  50162. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  50163. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  50164. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  50165. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  50166. var Xbox360Dpad;
  50167. (function (Xbox360Dpad) {
  50168. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  50169. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  50170. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  50171. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  50172. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  50173. var Xbox360Pad = (function (_super) {
  50174. __extends(Xbox360Pad, _super);
  50175. function Xbox360Pad(id, index, gamepad, xboxOne) {
  50176. if (xboxOne === void 0) { xboxOne = false; }
  50177. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  50178. _this._leftTrigger = 0;
  50179. _this._rightTrigger = 0;
  50180. _this._buttonA = 0;
  50181. _this._buttonB = 0;
  50182. _this._buttonX = 0;
  50183. _this._buttonY = 0;
  50184. _this._buttonBack = 0;
  50185. _this._buttonStart = 0;
  50186. _this._buttonLB = 0;
  50187. _this._buttonRB = 0;
  50188. _this._buttonLeftStick = 0;
  50189. _this._buttonRightStick = 0;
  50190. _this._dPadUp = 0;
  50191. _this._dPadDown = 0;
  50192. _this._dPadLeft = 0;
  50193. _this._dPadRight = 0;
  50194. _this._isXboxOnePad = false;
  50195. _this.type = Gamepad.XBOX;
  50196. _this._isXboxOnePad = xboxOne;
  50197. return _this;
  50198. }
  50199. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  50200. this._onlefttriggerchanged = callback;
  50201. };
  50202. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  50203. this._onrighttriggerchanged = callback;
  50204. };
  50205. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  50206. get: function () {
  50207. return this._leftTrigger;
  50208. },
  50209. set: function (newValue) {
  50210. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  50211. this._onlefttriggerchanged(newValue);
  50212. }
  50213. this._leftTrigger = newValue;
  50214. },
  50215. enumerable: true,
  50216. configurable: true
  50217. });
  50218. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  50219. get: function () {
  50220. return this._rightTrigger;
  50221. },
  50222. set: function (newValue) {
  50223. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  50224. this._onrighttriggerchanged(newValue);
  50225. }
  50226. this._rightTrigger = newValue;
  50227. },
  50228. enumerable: true,
  50229. configurable: true
  50230. });
  50231. Xbox360Pad.prototype.onbuttondown = function (callback) {
  50232. this._onbuttondown = callback;
  50233. };
  50234. Xbox360Pad.prototype.onbuttonup = function (callback) {
  50235. this._onbuttonup = callback;
  50236. };
  50237. Xbox360Pad.prototype.ondpaddown = function (callback) {
  50238. this._ondpaddown = callback;
  50239. };
  50240. Xbox360Pad.prototype.ondpadup = function (callback) {
  50241. this._ondpadup = callback;
  50242. };
  50243. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  50244. if (newValue !== currentValue) {
  50245. if (this._onbuttondown && newValue === 1) {
  50246. this._onbuttondown(buttonType);
  50247. }
  50248. if (this._onbuttonup && newValue === 0) {
  50249. this._onbuttonup(buttonType);
  50250. }
  50251. }
  50252. return newValue;
  50253. };
  50254. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  50255. if (newValue !== currentValue) {
  50256. if (this._ondpaddown && newValue === 1) {
  50257. this._ondpaddown(buttonType);
  50258. }
  50259. if (this._ondpadup && newValue === 0) {
  50260. this._ondpadup(buttonType);
  50261. }
  50262. }
  50263. return newValue;
  50264. };
  50265. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  50266. get: function () {
  50267. return this._buttonA;
  50268. },
  50269. set: function (value) {
  50270. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  50271. },
  50272. enumerable: true,
  50273. configurable: true
  50274. });
  50275. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  50276. get: function () {
  50277. return this._buttonB;
  50278. },
  50279. set: function (value) {
  50280. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  50281. },
  50282. enumerable: true,
  50283. configurable: true
  50284. });
  50285. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  50286. get: function () {
  50287. return this._buttonX;
  50288. },
  50289. set: function (value) {
  50290. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  50291. },
  50292. enumerable: true,
  50293. configurable: true
  50294. });
  50295. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  50296. get: function () {
  50297. return this._buttonY;
  50298. },
  50299. set: function (value) {
  50300. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  50301. },
  50302. enumerable: true,
  50303. configurable: true
  50304. });
  50305. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  50306. get: function () {
  50307. return this._buttonStart;
  50308. },
  50309. set: function (value) {
  50310. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  50311. },
  50312. enumerable: true,
  50313. configurable: true
  50314. });
  50315. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  50316. get: function () {
  50317. return this._buttonBack;
  50318. },
  50319. set: function (value) {
  50320. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  50321. },
  50322. enumerable: true,
  50323. configurable: true
  50324. });
  50325. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  50326. get: function () {
  50327. return this._buttonLB;
  50328. },
  50329. set: function (value) {
  50330. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  50331. },
  50332. enumerable: true,
  50333. configurable: true
  50334. });
  50335. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  50336. get: function () {
  50337. return this._buttonRB;
  50338. },
  50339. set: function (value) {
  50340. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  50341. },
  50342. enumerable: true,
  50343. configurable: true
  50344. });
  50345. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  50346. get: function () {
  50347. return this._buttonLeftStick;
  50348. },
  50349. set: function (value) {
  50350. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  50351. },
  50352. enumerable: true,
  50353. configurable: true
  50354. });
  50355. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  50356. get: function () {
  50357. return this._buttonRightStick;
  50358. },
  50359. set: function (value) {
  50360. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  50361. },
  50362. enumerable: true,
  50363. configurable: true
  50364. });
  50365. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  50366. get: function () {
  50367. return this._dPadUp;
  50368. },
  50369. set: function (value) {
  50370. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  50371. },
  50372. enumerable: true,
  50373. configurable: true
  50374. });
  50375. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  50376. get: function () {
  50377. return this._dPadDown;
  50378. },
  50379. set: function (value) {
  50380. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  50381. },
  50382. enumerable: true,
  50383. configurable: true
  50384. });
  50385. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  50386. get: function () {
  50387. return this._dPadLeft;
  50388. },
  50389. set: function (value) {
  50390. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  50391. },
  50392. enumerable: true,
  50393. configurable: true
  50394. });
  50395. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  50396. get: function () {
  50397. return this._dPadRight;
  50398. },
  50399. set: function (value) {
  50400. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  50401. },
  50402. enumerable: true,
  50403. configurable: true
  50404. });
  50405. Xbox360Pad.prototype.update = function () {
  50406. _super.prototype.update.call(this);
  50407. if (this._isXboxOnePad) {
  50408. this.buttonA = this.browserGamepad.buttons[0].value;
  50409. this.buttonB = this.browserGamepad.buttons[1].value;
  50410. this.buttonX = this.browserGamepad.buttons[2].value;
  50411. this.buttonY = this.browserGamepad.buttons[3].value;
  50412. this.buttonLB = this.browserGamepad.buttons[4].value;
  50413. this.buttonRB = this.browserGamepad.buttons[5].value;
  50414. this.leftTrigger = this.browserGamepad.axes[2];
  50415. this.rightTrigger = this.browserGamepad.axes[5];
  50416. this.buttonBack = this.browserGamepad.buttons[9].value;
  50417. this.buttonStart = this.browserGamepad.buttons[8].value;
  50418. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  50419. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  50420. this.dPadUp = this.browserGamepad.buttons[11].value;
  50421. this.dPadDown = this.browserGamepad.buttons[12].value;
  50422. this.dPadLeft = this.browserGamepad.buttons[13].value;
  50423. this.dPadRight = this.browserGamepad.buttons[14].value;
  50424. }
  50425. else {
  50426. this.buttonA = this.browserGamepad.buttons[0].value;
  50427. this.buttonB = this.browserGamepad.buttons[1].value;
  50428. this.buttonX = this.browserGamepad.buttons[2].value;
  50429. this.buttonY = this.browserGamepad.buttons[3].value;
  50430. this.buttonLB = this.browserGamepad.buttons[4].value;
  50431. this.buttonRB = this.browserGamepad.buttons[5].value;
  50432. this.leftTrigger = this.browserGamepad.buttons[6].value;
  50433. this.rightTrigger = this.browserGamepad.buttons[7].value;
  50434. this.buttonBack = this.browserGamepad.buttons[8].value;
  50435. this.buttonStart = this.browserGamepad.buttons[9].value;
  50436. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  50437. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  50438. this.dPadUp = this.browserGamepad.buttons[12].value;
  50439. this.dPadDown = this.browserGamepad.buttons[13].value;
  50440. this.dPadLeft = this.browserGamepad.buttons[14].value;
  50441. this.dPadRight = this.browserGamepad.buttons[15].value;
  50442. }
  50443. };
  50444. return Xbox360Pad;
  50445. }(Gamepad));
  50446. BABYLON.Xbox360Pad = Xbox360Pad;
  50447. })(BABYLON || (BABYLON = {}));
  50448. //# sourceMappingURL=babylon.gamepads.js.map
  50449. var BABYLON;
  50450. (function (BABYLON) {
  50451. var PoseEnabledControllerType;
  50452. (function (PoseEnabledControllerType) {
  50453. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  50454. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  50455. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  50456. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  50457. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  50458. var PoseEnabledControllerHelper = (function () {
  50459. function PoseEnabledControllerHelper() {
  50460. }
  50461. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  50462. // Oculus Touch
  50463. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  50464. return new OculusTouchController(vrGamepad);
  50465. }
  50466. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  50467. return new ViveController(vrGamepad);
  50468. }
  50469. else {
  50470. return new GenericController(vrGamepad);
  50471. }
  50472. };
  50473. return PoseEnabledControllerHelper;
  50474. }());
  50475. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  50476. var PoseEnabledController = (function (_super) {
  50477. __extends(PoseEnabledController, _super);
  50478. function PoseEnabledController(vrGamepad) {
  50479. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  50480. _this.vrGamepad = vrGamepad;
  50481. _this.deviceScaleFactor = 1;
  50482. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  50483. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  50484. _this.controllerType = PoseEnabledControllerType.GENERIC;
  50485. _this.position = BABYLON.Vector3.Zero();
  50486. _this.rotationQuaternion = new BABYLON.Quaternion();
  50487. _this.devicePosition = BABYLON.Vector3.Zero();
  50488. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50489. _this._calculatedPosition = BABYLON.Vector3.Zero();
  50490. _this._calculatedRotation = new BABYLON.Quaternion();
  50491. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  50492. return _this;
  50493. }
  50494. PoseEnabledController.prototype.update = function () {
  50495. _super.prototype.update.call(this);
  50496. var pose = this.vrGamepad.pose;
  50497. this.updateFromDevice(pose);
  50498. if (this._mesh) {
  50499. this._mesh.position.copyFrom(this._calculatedPosition);
  50500. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  50501. }
  50502. };
  50503. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  50504. if (poseData) {
  50505. this.rawPose = poseData;
  50506. if (poseData.position) {
  50507. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  50508. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  50509. this.devicePosition.z *= -1;
  50510. }
  50511. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  50512. this._calculatedPosition.addInPlace(this.position);
  50513. }
  50514. if (poseData.orientation) {
  50515. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50516. if (this._mesh) {
  50517. if (this._mesh.getScene().useRightHandedSystem) {
  50518. this.deviceRotationQuaternion.z *= -1;
  50519. this.deviceRotationQuaternion.w *= -1;
  50520. }
  50521. else {
  50522. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  50523. }
  50524. }
  50525. // if the camera is set, rotate to the camera's rotation
  50526. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  50527. }
  50528. }
  50529. };
  50530. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  50531. if (this._mesh) {
  50532. this._mesh.parent = undefined;
  50533. }
  50534. this._mesh = mesh;
  50535. if (this._poseControlledCamera) {
  50536. this._mesh.parent = this._poseControlledCamera;
  50537. }
  50538. if (!this._mesh.rotationQuaternion) {
  50539. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  50540. }
  50541. };
  50542. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  50543. this._poseControlledCamera = camera;
  50544. if (this._mesh) {
  50545. this._mesh.parent = this._poseControlledCamera;
  50546. }
  50547. };
  50548. PoseEnabledController.prototype.detachMesh = function () {
  50549. this._mesh = undefined;
  50550. };
  50551. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  50552. get: function () {
  50553. return this._mesh;
  50554. },
  50555. enumerable: true,
  50556. configurable: true
  50557. });
  50558. PoseEnabledController.prototype.getForwardRay = function (length) {
  50559. if (length === void 0) { length = 100; }
  50560. if (!this.mesh) {
  50561. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  50562. }
  50563. var m = this.mesh.getWorldMatrix();
  50564. var origin = m.getTranslation();
  50565. var forward = new BABYLON.Vector3(0, 0, -1);
  50566. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  50567. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  50568. return new BABYLON.Ray(origin, direction, length);
  50569. };
  50570. return PoseEnabledController;
  50571. }(BABYLON.Gamepad));
  50572. BABYLON.PoseEnabledController = PoseEnabledController;
  50573. var WebVRController = (function (_super) {
  50574. __extends(WebVRController, _super);
  50575. function WebVRController(vrGamepad) {
  50576. var _this = _super.call(this, vrGamepad) || this;
  50577. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  50578. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  50579. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  50580. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  50581. _this.onPadStateChangedObservable = new BABYLON.Observable();
  50582. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  50583. _this.pad = { x: 0, y: 0 };
  50584. // avoid GC, store state in a tmp object
  50585. _this._changes = {
  50586. pressChanged: false,
  50587. touchChanged: false,
  50588. valueChanged: false,
  50589. changed: false
  50590. };
  50591. _this._buttons = new Array(vrGamepad.buttons.length);
  50592. _this.hand = vrGamepad.hand;
  50593. return _this;
  50594. }
  50595. WebVRController.prototype.onButtonStateChange = function (callback) {
  50596. this._onButtonStateChange = callback;
  50597. };
  50598. WebVRController.prototype.update = function () {
  50599. _super.prototype.update.call(this);
  50600. for (var index = 0; index < this._buttons.length; index++) {
  50601. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  50602. }
  50603. ;
  50604. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  50605. this.pad.x = this.leftStick.x;
  50606. this.pad.y = this.leftStick.y;
  50607. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  50608. }
  50609. };
  50610. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  50611. if (!newState) {
  50612. newState = {
  50613. pressed: false,
  50614. touched: false,
  50615. value: 0
  50616. };
  50617. }
  50618. if (!currentState) {
  50619. this._buttons[buttonIndex] = {
  50620. pressed: newState.pressed,
  50621. touched: newState.touched,
  50622. value: newState.value
  50623. };
  50624. return;
  50625. }
  50626. this._checkChanges(newState, currentState);
  50627. if (this._changes.changed) {
  50628. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  50629. this.handleButtonChange(buttonIndex, newState, this._changes);
  50630. }
  50631. this._buttons[buttonIndex].pressed = newState.pressed;
  50632. this._buttons[buttonIndex].touched = newState.touched;
  50633. // oculus triggers are never 0, thou not touched.
  50634. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  50635. };
  50636. WebVRController.prototype._checkChanges = function (newState, currentState) {
  50637. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  50638. this._changes.touchChanged = newState.touched !== currentState.touched;
  50639. this._changes.valueChanged = newState.value !== currentState.value;
  50640. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  50641. return this._changes;
  50642. };
  50643. return WebVRController;
  50644. }(PoseEnabledController));
  50645. BABYLON.WebVRController = WebVRController;
  50646. var OculusTouchController = (function (_super) {
  50647. __extends(OculusTouchController, _super);
  50648. function OculusTouchController(vrGamepad) {
  50649. var _this = _super.call(this, vrGamepad) || this;
  50650. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  50651. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  50652. _this.controllerType = PoseEnabledControllerType.OCULUS;
  50653. return _this;
  50654. }
  50655. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50656. var _this = this;
  50657. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  50658. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  50659. /*
  50660. Parent Mesh name: oculus_touch_left
  50661. - body
  50662. - trigger
  50663. - thumbstick
  50664. - grip
  50665. - button_y
  50666. - button_x
  50667. - button_enter
  50668. */
  50669. _this._defaultModel = newMeshes[1];
  50670. if (meshLoaded) {
  50671. meshLoaded(_this._defaultModel);
  50672. }
  50673. _this.attachToMesh(_this._defaultModel);
  50674. });
  50675. };
  50676. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  50677. // helper getters for left and right hand.
  50678. get: function () {
  50679. if (this.hand === 'right') {
  50680. return this.onMainButtonStateChangedObservable;
  50681. }
  50682. else {
  50683. throw new Error('No A button on left hand');
  50684. }
  50685. },
  50686. enumerable: true,
  50687. configurable: true
  50688. });
  50689. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  50690. get: function () {
  50691. if (this.hand === 'right') {
  50692. return this.onSecondaryButtonStateChangedObservable;
  50693. }
  50694. else {
  50695. throw new Error('No B button on left hand');
  50696. }
  50697. },
  50698. enumerable: true,
  50699. configurable: true
  50700. });
  50701. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  50702. get: function () {
  50703. if (this.hand === 'left') {
  50704. return this.onMainButtonStateChangedObservable;
  50705. }
  50706. else {
  50707. throw new Error('No X button on right hand');
  50708. }
  50709. },
  50710. enumerable: true,
  50711. configurable: true
  50712. });
  50713. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  50714. get: function () {
  50715. if (this.hand === 'left') {
  50716. return this.onSecondaryButtonStateChangedObservable;
  50717. }
  50718. else {
  50719. throw new Error('No Y button on right hand');
  50720. }
  50721. },
  50722. enumerable: true,
  50723. configurable: true
  50724. });
  50725. /*
  50726. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  50727. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  50728. 2) secondary trigger (same)
  50729. 3) A (right) X (left), touch, pressed = value
  50730. 4) B / Y
  50731. 5) thumb rest
  50732. */
  50733. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50734. var notifyObject = state; //{ state: state, changes: changes };
  50735. var triggerDirection = this.hand === 'right' ? -1 : 1;
  50736. switch (buttonIdx) {
  50737. case 0:
  50738. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  50739. return;
  50740. case 1:// index trigger
  50741. if (this._defaultModel) {
  50742. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  50743. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  50744. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  50745. }
  50746. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  50747. return;
  50748. case 2:// secondary trigger
  50749. if (this._defaultModel) {
  50750. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  50751. }
  50752. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  50753. return;
  50754. case 3:
  50755. if (this._defaultModel) {
  50756. if (notifyObject.pressed) {
  50757. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  50758. }
  50759. else {
  50760. (this._defaultModel.getChildren()[1]).position.y = 0;
  50761. }
  50762. }
  50763. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  50764. return;
  50765. case 4:
  50766. if (this._defaultModel) {
  50767. if (notifyObject.pressed) {
  50768. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  50769. }
  50770. else {
  50771. (this._defaultModel.getChildren()[2]).position.y = 0;
  50772. }
  50773. }
  50774. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  50775. return;
  50776. case 5:
  50777. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  50778. return;
  50779. }
  50780. };
  50781. return OculusTouchController;
  50782. }(WebVRController));
  50783. BABYLON.OculusTouchController = OculusTouchController;
  50784. var ViveController = (function (_super) {
  50785. __extends(ViveController, _super);
  50786. function ViveController(vrGamepad) {
  50787. var _this = _super.call(this, vrGamepad) || this;
  50788. _this.controllerType = PoseEnabledControllerType.VIVE;
  50789. return _this;
  50790. }
  50791. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50792. var _this = this;
  50793. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  50794. /*
  50795. Parent Mesh name: ViveWand
  50796. - body
  50797. - r_gripper
  50798. - l_gripper
  50799. - menu_button
  50800. - system_button
  50801. - trackpad
  50802. - trigger
  50803. - LED
  50804. */
  50805. _this._defaultModel = newMeshes[1];
  50806. if (meshLoaded) {
  50807. meshLoaded(_this._defaultModel);
  50808. }
  50809. _this.attachToMesh(_this._defaultModel);
  50810. });
  50811. };
  50812. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  50813. get: function () {
  50814. return this.onMainButtonStateChangedObservable;
  50815. },
  50816. enumerable: true,
  50817. configurable: true
  50818. });
  50819. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  50820. get: function () {
  50821. return this.onMainButtonStateChangedObservable;
  50822. },
  50823. enumerable: true,
  50824. configurable: true
  50825. });
  50826. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  50827. get: function () {
  50828. return this.onSecondaryButtonStateChangedObservable;
  50829. },
  50830. enumerable: true,
  50831. configurable: true
  50832. });
  50833. /**
  50834. * Vive mapping:
  50835. * 0: touchpad
  50836. * 1: trigger
  50837. * 2: left AND right buttons
  50838. * 3: menu button
  50839. */
  50840. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50841. var notifyObject = state; //{ state: state, changes: changes };
  50842. switch (buttonIdx) {
  50843. case 0:
  50844. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  50845. return;
  50846. case 1:// index trigger
  50847. if (this._defaultModel) {
  50848. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  50849. }
  50850. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  50851. return;
  50852. case 2:// left AND right button
  50853. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  50854. return;
  50855. case 3:
  50856. if (this._defaultModel) {
  50857. if (notifyObject.pressed) {
  50858. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  50859. }
  50860. else {
  50861. (this._defaultModel.getChildren()[2]).position.y = 0;
  50862. }
  50863. }
  50864. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  50865. return;
  50866. }
  50867. };
  50868. return ViveController;
  50869. }(WebVRController));
  50870. BABYLON.ViveController = ViveController;
  50871. var GenericController = (function (_super) {
  50872. __extends(GenericController, _super);
  50873. function GenericController(vrGamepad) {
  50874. return _super.call(this, vrGamepad) || this;
  50875. }
  50876. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  50877. var _this = this;
  50878. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "genericvrcontroller.babylon", scene, function (newMeshes) {
  50879. _this._defaultModel = newMeshes[1];
  50880. if (meshLoaded) {
  50881. meshLoaded(_this._defaultModel);
  50882. }
  50883. _this.attachToMesh(_this._defaultModel);
  50884. });
  50885. };
  50886. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50887. console.log("Button id: " + buttonIdx + "state: ");
  50888. console.dir(state);
  50889. };
  50890. return GenericController;
  50891. }(WebVRController));
  50892. BABYLON.GenericController = GenericController;
  50893. })(BABYLON || (BABYLON = {}));
  50894. //# sourceMappingURL=babylon.extendedGamepad.js.map
  50895. /// <reference path="babylon.targetCamera.ts" />
  50896. var BABYLON;
  50897. (function (BABYLON) {
  50898. var FollowCamera = (function (_super) {
  50899. __extends(FollowCamera, _super);
  50900. function FollowCamera(name, position, scene, lockedTarget) {
  50901. var _this = _super.call(this, name, position, scene) || this;
  50902. _this.radius = 12;
  50903. _this.rotationOffset = 0;
  50904. _this.heightOffset = 4;
  50905. _this.cameraAcceleration = 0.05;
  50906. _this.maxCameraSpeed = 20;
  50907. _this.lockedTarget = lockedTarget;
  50908. return _this;
  50909. }
  50910. FollowCamera.prototype.getRadians = function (degrees) {
  50911. return degrees * Math.PI / 180;
  50912. };
  50913. FollowCamera.prototype.follow = function (cameraTarget) {
  50914. if (!cameraTarget)
  50915. return;
  50916. var yRotation;
  50917. if (cameraTarget.rotationQuaternion) {
  50918. var rotMatrix = new BABYLON.Matrix();
  50919. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  50920. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  50921. }
  50922. else {
  50923. yRotation = cameraTarget.rotation.y;
  50924. }
  50925. var radians = this.getRadians(this.rotationOffset) + yRotation;
  50926. var targetPosition = cameraTarget.getAbsolutePosition();
  50927. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  50928. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  50929. var dx = targetX - this.position.x;
  50930. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  50931. var dz = (targetZ) - this.position.z;
  50932. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  50933. var vy = dy * this.cameraAcceleration;
  50934. var vz = dz * this.cameraAcceleration * 2;
  50935. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  50936. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50937. }
  50938. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  50939. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50940. }
  50941. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  50942. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  50943. }
  50944. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  50945. this.setTarget(targetPosition);
  50946. };
  50947. FollowCamera.prototype._checkInputs = function () {
  50948. _super.prototype._checkInputs.call(this);
  50949. this.follow(this.lockedTarget);
  50950. };
  50951. FollowCamera.prototype.getClassName = function () {
  50952. return "FollowCamera";
  50953. };
  50954. __decorate([
  50955. BABYLON.serialize()
  50956. ], FollowCamera.prototype, "radius", void 0);
  50957. __decorate([
  50958. BABYLON.serialize()
  50959. ], FollowCamera.prototype, "rotationOffset", void 0);
  50960. __decorate([
  50961. BABYLON.serialize()
  50962. ], FollowCamera.prototype, "heightOffset", void 0);
  50963. __decorate([
  50964. BABYLON.serialize()
  50965. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  50966. __decorate([
  50967. BABYLON.serialize()
  50968. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  50969. __decorate([
  50970. BABYLON.serializeAsMeshReference("lockedTargetId")
  50971. ], FollowCamera.prototype, "lockedTarget", void 0);
  50972. return FollowCamera;
  50973. }(BABYLON.TargetCamera));
  50974. BABYLON.FollowCamera = FollowCamera;
  50975. var ArcFollowCamera = (function (_super) {
  50976. __extends(ArcFollowCamera, _super);
  50977. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  50978. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  50979. _this.alpha = alpha;
  50980. _this.beta = beta;
  50981. _this.radius = radius;
  50982. _this.target = target;
  50983. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  50984. _this.follow();
  50985. return _this;
  50986. }
  50987. ArcFollowCamera.prototype.follow = function () {
  50988. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  50989. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  50990. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  50991. var targetPosition = this.target.getAbsolutePosition();
  50992. this.position = targetPosition.add(this._cartesianCoordinates);
  50993. this.setTarget(targetPosition);
  50994. };
  50995. ArcFollowCamera.prototype._checkInputs = function () {
  50996. _super.prototype._checkInputs.call(this);
  50997. this.follow();
  50998. };
  50999. ArcFollowCamera.prototype.getClassName = function () {
  51000. return "ArcFollowCamera";
  51001. };
  51002. return ArcFollowCamera;
  51003. }(BABYLON.TargetCamera));
  51004. BABYLON.ArcFollowCamera = ArcFollowCamera;
  51005. })(BABYLON || (BABYLON = {}));
  51006. //# sourceMappingURL=babylon.followCamera.js.map
  51007. /// <reference path="babylon.touchCamera.ts" />
  51008. var BABYLON;
  51009. (function (BABYLON) {
  51010. // We're mainly based on the logic defined into the FreeCamera code
  51011. var UniversalCamera = (function (_super) {
  51012. __extends(UniversalCamera, _super);
  51013. //-- end properties for backward compatibility for inputs
  51014. function UniversalCamera(name, position, scene) {
  51015. var _this = _super.call(this, name, position, scene) || this;
  51016. _this.inputs.addGamepad();
  51017. return _this;
  51018. }
  51019. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  51020. //-- Begin properties for backward compatibility for inputs
  51021. get: function () {
  51022. var gamepad = this.inputs.attached["gamepad"];
  51023. if (gamepad)
  51024. return gamepad.gamepadAngularSensibility;
  51025. },
  51026. set: function (value) {
  51027. var gamepad = this.inputs.attached["gamepad"];
  51028. if (gamepad)
  51029. gamepad.gamepadAngularSensibility = value;
  51030. },
  51031. enumerable: true,
  51032. configurable: true
  51033. });
  51034. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  51035. get: function () {
  51036. var gamepad = this.inputs.attached["gamepad"];
  51037. if (gamepad)
  51038. return gamepad.gamepadMoveSensibility;
  51039. },
  51040. set: function (value) {
  51041. var gamepad = this.inputs.attached["gamepad"];
  51042. if (gamepad)
  51043. gamepad.gamepadMoveSensibility = value;
  51044. },
  51045. enumerable: true,
  51046. configurable: true
  51047. });
  51048. UniversalCamera.prototype.getClassName = function () {
  51049. return "UniversalCamera";
  51050. };
  51051. return UniversalCamera;
  51052. }(BABYLON.TouchCamera));
  51053. BABYLON.UniversalCamera = UniversalCamera;
  51054. })(BABYLON || (BABYLON = {}));
  51055. //# sourceMappingURL=babylon.universalCamera.js.map
  51056. /// <reference path="babylon.universalCamera.ts" />
  51057. var BABYLON;
  51058. (function (BABYLON) {
  51059. // We're mainly based on the logic defined into the FreeCamera code
  51060. var GamepadCamera = (function (_super) {
  51061. __extends(GamepadCamera, _super);
  51062. //-- end properties for backward compatibility for inputs
  51063. function GamepadCamera(name, position, scene) {
  51064. return _super.call(this, name, position, scene) || this;
  51065. }
  51066. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51067. //-- Begin properties for backward compatibility for inputs
  51068. get: function () {
  51069. var gamepad = this.inputs.attached["gamepad"];
  51070. if (gamepad)
  51071. return gamepad.gamepadAngularSensibility;
  51072. },
  51073. set: function (value) {
  51074. var gamepad = this.inputs.attached["gamepad"];
  51075. if (gamepad)
  51076. gamepad.gamepadAngularSensibility = value;
  51077. },
  51078. enumerable: true,
  51079. configurable: true
  51080. });
  51081. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51082. get: function () {
  51083. var gamepad = this.inputs.attached["gamepad"];
  51084. if (gamepad)
  51085. return gamepad.gamepadMoveSensibility;
  51086. },
  51087. set: function (value) {
  51088. var gamepad = this.inputs.attached["gamepad"];
  51089. if (gamepad)
  51090. gamepad.gamepadMoveSensibility = value;
  51091. },
  51092. enumerable: true,
  51093. configurable: true
  51094. });
  51095. GamepadCamera.prototype.getClassName = function () {
  51096. return "GamepadCamera";
  51097. };
  51098. return GamepadCamera;
  51099. }(BABYLON.UniversalCamera));
  51100. BABYLON.GamepadCamera = GamepadCamera;
  51101. })(BABYLON || (BABYLON = {}));
  51102. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51103. var BABYLON;
  51104. (function (BABYLON) {
  51105. var PostProcessRenderPipelineManager = (function () {
  51106. function PostProcessRenderPipelineManager() {
  51107. this._renderPipelines = {};
  51108. }
  51109. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  51110. this._renderPipelines[renderPipeline._name] = renderPipeline;
  51111. };
  51112. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  51113. var renderPipeline = this._renderPipelines[renderPipelineName];
  51114. if (!renderPipeline) {
  51115. return;
  51116. }
  51117. renderPipeline._attachCameras(cameras, unique);
  51118. };
  51119. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  51120. var renderPipeline = this._renderPipelines[renderPipelineName];
  51121. if (!renderPipeline) {
  51122. return;
  51123. }
  51124. renderPipeline._detachCameras(cameras);
  51125. };
  51126. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  51127. var renderPipeline = this._renderPipelines[renderPipelineName];
  51128. if (!renderPipeline) {
  51129. return;
  51130. }
  51131. renderPipeline._enableEffect(renderEffectName, cameras);
  51132. };
  51133. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  51134. var renderPipeline = this._renderPipelines[renderPipelineName];
  51135. if (!renderPipeline) {
  51136. return;
  51137. }
  51138. renderPipeline._disableEffect(renderEffectName, cameras);
  51139. };
  51140. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  51141. var renderPipeline = this._renderPipelines[renderPipelineName];
  51142. if (!renderPipeline) {
  51143. return;
  51144. }
  51145. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  51146. };
  51147. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  51148. var renderPipeline = this._renderPipelines[renderPipelineName];
  51149. if (!renderPipeline) {
  51150. return;
  51151. }
  51152. renderPipeline._disableDisplayOnlyPass(cameras);
  51153. };
  51154. PostProcessRenderPipelineManager.prototype.update = function () {
  51155. for (var renderPipelineName in this._renderPipelines) {
  51156. var pipeline = this._renderPipelines[renderPipelineName];
  51157. if (!pipeline.isSupported) {
  51158. pipeline.dispose();
  51159. delete this._renderPipelines[renderPipelineName];
  51160. }
  51161. else {
  51162. pipeline._update();
  51163. }
  51164. }
  51165. };
  51166. return PostProcessRenderPipelineManager;
  51167. }());
  51168. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  51169. })(BABYLON || (BABYLON = {}));
  51170. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  51171. var BABYLON;
  51172. (function (BABYLON) {
  51173. var PostProcessRenderPass = (function () {
  51174. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  51175. this._enabled = true;
  51176. this._refCount = 0;
  51177. this._name = name;
  51178. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  51179. this.setRenderList(renderList);
  51180. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  51181. this._renderTexture.onAfterRenderObservable.add(afterRender);
  51182. this._scene = scene;
  51183. this._renderList = renderList;
  51184. }
  51185. // private
  51186. PostProcessRenderPass.prototype._incRefCount = function () {
  51187. if (this._refCount === 0) {
  51188. this._scene.customRenderTargets.push(this._renderTexture);
  51189. }
  51190. return ++this._refCount;
  51191. };
  51192. PostProcessRenderPass.prototype._decRefCount = function () {
  51193. this._refCount--;
  51194. if (this._refCount <= 0) {
  51195. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  51196. }
  51197. return this._refCount;
  51198. };
  51199. PostProcessRenderPass.prototype._update = function () {
  51200. this.setRenderList(this._renderList);
  51201. };
  51202. // public
  51203. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  51204. this._renderTexture.renderList = renderList;
  51205. };
  51206. PostProcessRenderPass.prototype.getRenderTexture = function () {
  51207. return this._renderTexture;
  51208. };
  51209. return PostProcessRenderPass;
  51210. }());
  51211. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  51212. })(BABYLON || (BABYLON = {}));
  51213. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  51214. var BABYLON;
  51215. (function (BABYLON) {
  51216. var PostProcessRenderEffect = (function () {
  51217. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  51218. this._engine = engine;
  51219. this._name = name;
  51220. this._singleInstance = singleInstance || true;
  51221. this._getPostProcess = getPostProcess;
  51222. this._cameras = [];
  51223. this._indicesForCamera = [];
  51224. this._postProcesses = {};
  51225. this._renderPasses = {};
  51226. this._renderEffectAsPasses = {};
  51227. }
  51228. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  51229. get: function () {
  51230. for (var index in this._postProcesses) {
  51231. if (!this._postProcesses[index].isSupported) {
  51232. return false;
  51233. }
  51234. }
  51235. return true;
  51236. },
  51237. enumerable: true,
  51238. configurable: true
  51239. });
  51240. PostProcessRenderEffect.prototype._update = function () {
  51241. for (var renderPassName in this._renderPasses) {
  51242. this._renderPasses[renderPassName]._update();
  51243. }
  51244. };
  51245. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  51246. this._renderPasses[renderPass._name] = renderPass;
  51247. this._linkParameters();
  51248. };
  51249. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  51250. delete this._renderPasses[renderPass._name];
  51251. this._linkParameters();
  51252. };
  51253. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  51254. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  51255. this._linkParameters();
  51256. };
  51257. PostProcessRenderEffect.prototype.getPass = function (passName) {
  51258. for (var renderPassName in this._renderPasses) {
  51259. if (renderPassName === passName) {
  51260. return this._renderPasses[passName];
  51261. }
  51262. }
  51263. };
  51264. PostProcessRenderEffect.prototype.emptyPasses = function () {
  51265. this._renderPasses = {};
  51266. this._linkParameters();
  51267. };
  51268. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  51269. var cameraKey;
  51270. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51271. for (var i = 0; i < _cam.length; i++) {
  51272. var camera = _cam[i];
  51273. var cameraName = camera.name;
  51274. if (this._singleInstance) {
  51275. cameraKey = 0;
  51276. }
  51277. else {
  51278. cameraKey = cameraName;
  51279. }
  51280. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  51281. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  51282. if (!this._indicesForCamera[cameraName]) {
  51283. this._indicesForCamera[cameraName] = [];
  51284. }
  51285. this._indicesForCamera[cameraName].push(index);
  51286. if (this._cameras.indexOf(camera) === -1) {
  51287. this._cameras[cameraName] = camera;
  51288. }
  51289. for (var passName in this._renderPasses) {
  51290. this._renderPasses[passName]._incRefCount();
  51291. }
  51292. }
  51293. this._linkParameters();
  51294. };
  51295. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  51296. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51297. for (var i = 0; i < _cam.length; i++) {
  51298. var camera = _cam[i];
  51299. var cameraName = camera.name;
  51300. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51301. var index = this._cameras.indexOf(cameraName);
  51302. this._indicesForCamera.splice(index, 1);
  51303. this._cameras.splice(index, 1);
  51304. for (var passName in this._renderPasses) {
  51305. this._renderPasses[passName]._decRefCount();
  51306. }
  51307. }
  51308. };
  51309. PostProcessRenderEffect.prototype._enable = function (cameras) {
  51310. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51311. for (var i = 0; i < _cam.length; i++) {
  51312. var camera = _cam[i];
  51313. var cameraName = camera.name;
  51314. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  51315. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  51316. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  51317. }
  51318. }
  51319. for (var passName in this._renderPasses) {
  51320. this._renderPasses[passName]._incRefCount();
  51321. }
  51322. }
  51323. };
  51324. PostProcessRenderEffect.prototype._disable = function (cameras) {
  51325. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51326. for (var i = 0; i < _cam.length; i++) {
  51327. var camera = _cam[i];
  51328. var cameraName = camera.Name;
  51329. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51330. for (var passName in this._renderPasses) {
  51331. this._renderPasses[passName]._decRefCount();
  51332. }
  51333. }
  51334. };
  51335. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  51336. if (this._singleInstance) {
  51337. return this._postProcesses[0];
  51338. }
  51339. else {
  51340. return this._postProcesses[camera.name];
  51341. }
  51342. };
  51343. PostProcessRenderEffect.prototype._linkParameters = function () {
  51344. var _this = this;
  51345. for (var index in this._postProcesses) {
  51346. if (this.applyParameters) {
  51347. this.applyParameters(this._postProcesses[index]);
  51348. }
  51349. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  51350. _this._linkTextures(effect);
  51351. });
  51352. }
  51353. };
  51354. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  51355. for (var renderPassName in this._renderPasses) {
  51356. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  51357. }
  51358. for (var renderEffectName in this._renderEffectAsPasses) {
  51359. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  51360. }
  51361. };
  51362. return PostProcessRenderEffect;
  51363. }());
  51364. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  51365. })(BABYLON || (BABYLON = {}));
  51366. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  51367. var BABYLON;
  51368. (function (BABYLON) {
  51369. var PostProcessRenderPipeline = (function () {
  51370. function PostProcessRenderPipeline(engine, name) {
  51371. this._engine = engine;
  51372. this._name = name;
  51373. this._renderEffects = new Array();
  51374. this._renderEffectsForIsolatedPass = new Array();
  51375. this._cameras = [];
  51376. }
  51377. PostProcessRenderPipeline.prototype.getClassName = function () {
  51378. return "PostProcessRenderPipeline";
  51379. };
  51380. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  51381. get: function () {
  51382. for (var renderEffectName in this._renderEffects) {
  51383. if (!this._renderEffects[renderEffectName].isSupported) {
  51384. return false;
  51385. }
  51386. }
  51387. return true;
  51388. },
  51389. enumerable: true,
  51390. configurable: true
  51391. });
  51392. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  51393. this._renderEffects[renderEffect._name] = renderEffect;
  51394. };
  51395. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  51396. var renderEffects = this._renderEffects[renderEffectName];
  51397. if (!renderEffects) {
  51398. return;
  51399. }
  51400. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  51401. };
  51402. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  51403. var renderEffects = this._renderEffects[renderEffectName];
  51404. if (!renderEffects) {
  51405. return;
  51406. }
  51407. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  51408. };
  51409. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  51410. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51411. var indicesToDelete = [];
  51412. var i;
  51413. for (i = 0; i < _cam.length; i++) {
  51414. var camera = _cam[i];
  51415. var cameraName = camera.name;
  51416. if (this._cameras.indexOf(camera) === -1) {
  51417. this._cameras[cameraName] = camera;
  51418. }
  51419. else if (unique) {
  51420. indicesToDelete.push(i);
  51421. }
  51422. }
  51423. for (i = 0; i < indicesToDelete.length; i++) {
  51424. cameras.splice(indicesToDelete[i], 1);
  51425. }
  51426. for (var renderEffectName in this._renderEffects) {
  51427. this._renderEffects[renderEffectName]._attachCameras(_cam);
  51428. }
  51429. };
  51430. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  51431. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51432. for (var renderEffectName in this._renderEffects) {
  51433. this._renderEffects[renderEffectName]._detachCameras(_cam);
  51434. }
  51435. for (var i = 0; i < _cam.length; i++) {
  51436. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  51437. }
  51438. };
  51439. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  51440. var _this = this;
  51441. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51442. var pass = null;
  51443. var renderEffectName;
  51444. for (renderEffectName in this._renderEffects) {
  51445. pass = this._renderEffects[renderEffectName].getPass(passName);
  51446. if (pass != null) {
  51447. break;
  51448. }
  51449. }
  51450. if (pass === null) {
  51451. return;
  51452. }
  51453. for (renderEffectName in this._renderEffects) {
  51454. this._renderEffects[renderEffectName]._disable(_cam);
  51455. }
  51456. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  51457. for (var i = 0; i < _cam.length; i++) {
  51458. var camera = _cam[i];
  51459. var cameraName = camera.name;
  51460. 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); });
  51461. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  51462. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  51463. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  51464. }
  51465. };
  51466. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  51467. var _this = this;
  51468. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51469. for (var i = 0; i < _cam.length; i++) {
  51470. var camera = _cam[i];
  51471. var cameraName = camera.name;
  51472. 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); });
  51473. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  51474. }
  51475. for (var renderEffectName in this._renderEffects) {
  51476. this._renderEffects[renderEffectName]._enable(_cam);
  51477. }
  51478. };
  51479. PostProcessRenderPipeline.prototype._update = function () {
  51480. for (var renderEffectName in this._renderEffects) {
  51481. this._renderEffects[renderEffectName]._update();
  51482. }
  51483. for (var i = 0; i < this._cameras.length; i++) {
  51484. var cameraName = this._cameras[i].name;
  51485. if (this._renderEffectsForIsolatedPass[cameraName]) {
  51486. this._renderEffectsForIsolatedPass[cameraName]._update();
  51487. }
  51488. }
  51489. };
  51490. PostProcessRenderPipeline.prototype._reset = function () {
  51491. this._renderEffects = new Array();
  51492. this._renderEffectsForIsolatedPass = new Array();
  51493. };
  51494. PostProcessRenderPipeline.prototype.dispose = function () {
  51495. // Must be implemented by children
  51496. };
  51497. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  51498. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  51499. __decorate([
  51500. BABYLON.serialize()
  51501. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  51502. return PostProcessRenderPipeline;
  51503. }());
  51504. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  51505. })(BABYLON || (BABYLON = {}));
  51506. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  51507. var BABYLON;
  51508. (function (BABYLON) {
  51509. var DepthRenderer = (function () {
  51510. function DepthRenderer(scene, type) {
  51511. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51512. var _this = this;
  51513. this._viewMatrix = BABYLON.Matrix.Zero();
  51514. this._projectionMatrix = BABYLON.Matrix.Zero();
  51515. this._transformMatrix = BABYLON.Matrix.Zero();
  51516. this._worldViewProjection = BABYLON.Matrix.Zero();
  51517. this._scene = scene;
  51518. var engine = scene.getEngine();
  51519. // Render target
  51520. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51521. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51522. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51523. this._depthMap.refreshRate = 1;
  51524. this._depthMap.renderParticles = false;
  51525. this._depthMap.renderList = null;
  51526. // set default depth value to 1.0 (far away)
  51527. this._depthMap.onClearObservable.add(function (engine) {
  51528. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51529. });
  51530. // Custom render function
  51531. var renderSubMesh = function (subMesh) {
  51532. var mesh = subMesh.getRenderingMesh();
  51533. var scene = _this._scene;
  51534. var engine = scene.getEngine();
  51535. // Culling
  51536. engine.setState(subMesh.getMaterial().backFaceCulling);
  51537. // Managing instances
  51538. var batch = mesh._getInstancesRenderList(subMesh._id);
  51539. if (batch.mustReturn) {
  51540. return;
  51541. }
  51542. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  51543. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51544. engine.enableEffect(_this._effect);
  51545. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51546. var material = subMesh.getMaterial();
  51547. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51548. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  51549. // Alpha test
  51550. if (material && material.needAlphaTesting()) {
  51551. var alphaTexture = material.getAlphaTestTexture();
  51552. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51553. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51554. }
  51555. // Bones
  51556. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51557. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51558. }
  51559. // Draw
  51560. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51561. }
  51562. };
  51563. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51564. var index;
  51565. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51566. renderSubMesh(opaqueSubMeshes.data[index]);
  51567. }
  51568. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51569. renderSubMesh(alphaTestSubMeshes.data[index]);
  51570. }
  51571. };
  51572. }
  51573. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  51574. var material = subMesh.getMaterial();
  51575. if (material.disableDepthWrite) {
  51576. return false;
  51577. }
  51578. var defines = [];
  51579. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51580. var mesh = subMesh.getMesh();
  51581. var scene = mesh.getScene();
  51582. // Alpha test
  51583. if (material && material.needAlphaTesting()) {
  51584. defines.push("#define ALPHATEST");
  51585. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51586. attribs.push(BABYLON.VertexBuffer.UVKind);
  51587. defines.push("#define UV1");
  51588. }
  51589. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51590. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51591. defines.push("#define UV2");
  51592. }
  51593. }
  51594. // Bones
  51595. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51596. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51597. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51598. if (mesh.numBoneInfluencers > 4) {
  51599. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51600. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51601. }
  51602. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51603. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51604. }
  51605. else {
  51606. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51607. }
  51608. // Instances
  51609. if (useInstances) {
  51610. defines.push("#define INSTANCES");
  51611. attribs.push("world0");
  51612. attribs.push("world1");
  51613. attribs.push("world2");
  51614. attribs.push("world3");
  51615. }
  51616. // Get correct effect
  51617. var join = defines.join("\n");
  51618. if (this._cachedDefines !== join) {
  51619. this._cachedDefines = join;
  51620. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  51621. }
  51622. return this._effect.isReady();
  51623. };
  51624. DepthRenderer.prototype.getDepthMap = function () {
  51625. return this._depthMap;
  51626. };
  51627. // Methods
  51628. DepthRenderer.prototype.dispose = function () {
  51629. this._depthMap.dispose();
  51630. };
  51631. return DepthRenderer;
  51632. }());
  51633. BABYLON.DepthRenderer = DepthRenderer;
  51634. })(BABYLON || (BABYLON = {}));
  51635. //# sourceMappingURL=babylon.depthRenderer.js.map
  51636. var BABYLON;
  51637. (function (BABYLON) {
  51638. var SSAORenderingPipeline = (function (_super) {
  51639. __extends(SSAORenderingPipeline, _super);
  51640. /**
  51641. * @constructor
  51642. * @param {string} name - The rendering pipeline name
  51643. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51644. * @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 }
  51645. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51646. */
  51647. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  51648. var _this = _super.call(this, scene.getEngine(), name) || this;
  51649. // Members
  51650. /**
  51651. * The PassPostProcess id in the pipeline that contains the original scene color
  51652. * @type {string}
  51653. */
  51654. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  51655. /**
  51656. * The SSAO PostProcess id in the pipeline
  51657. * @type {string}
  51658. */
  51659. _this.SSAORenderEffect = "SSAORenderEffect";
  51660. /**
  51661. * The horizontal blur PostProcess id in the pipeline
  51662. * @type {string}
  51663. */
  51664. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  51665. /**
  51666. * The vertical blur PostProcess id in the pipeline
  51667. * @type {string}
  51668. */
  51669. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  51670. /**
  51671. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  51672. * @type {string}
  51673. */
  51674. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  51675. /**
  51676. * The output strength of the SSAO post-process. Default value is 1.0.
  51677. * @type {number}
  51678. */
  51679. _this.totalStrength = 1.0;
  51680. /**
  51681. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  51682. * @type {number}
  51683. */
  51684. _this.radius = 0.0001;
  51685. /**
  51686. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  51687. * Must not be equal to fallOff and superior to fallOff.
  51688. * Default value is 0.975
  51689. * @type {number}
  51690. */
  51691. _this.area = 0.0075;
  51692. /**
  51693. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  51694. * Must not be equal to area and inferior to area.
  51695. * Default value is 0.0
  51696. * @type {number}
  51697. */
  51698. _this.fallOff = 0.000001;
  51699. /**
  51700. * The base color of the SSAO post-process
  51701. * The final result is "base + ssao" between [0, 1]
  51702. * @type {number}
  51703. */
  51704. _this.base = 0.5;
  51705. _this._firstUpdate = true;
  51706. _this._scene = scene;
  51707. // Set up assets
  51708. _this._createRandomTexture();
  51709. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51710. var ssaoRatio = ratio.ssaoRatio || ratio;
  51711. var combineRatio = ratio.combineRatio || ratio;
  51712. _this._ratio = {
  51713. ssaoRatio: ssaoRatio,
  51714. combineRatio: combineRatio
  51715. };
  51716. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51717. _this._createSSAOPostProcess(ssaoRatio);
  51718. _this._createBlurPostProcess(ssaoRatio);
  51719. _this._createSSAOCombinePostProcess(combineRatio);
  51720. // Set up pipeline
  51721. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  51722. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  51723. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  51724. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  51725. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  51726. // Finish
  51727. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51728. if (cameras)
  51729. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51730. return _this;
  51731. }
  51732. // Public Methods
  51733. /**
  51734. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  51735. */
  51736. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51737. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51738. for (var i = 0; i < this._scene.cameras.length; i++) {
  51739. var camera = this._scene.cameras[i];
  51740. this._originalColorPostProcess.dispose(camera);
  51741. this._ssaoPostProcess.dispose(camera);
  51742. this._blurHPostProcess.dispose(camera);
  51743. this._blurVPostProcess.dispose(camera);
  51744. this._ssaoCombinePostProcess.dispose(camera);
  51745. }
  51746. this._randomTexture.dispose();
  51747. if (disableDepthRender)
  51748. this._scene.disableDepthRenderer();
  51749. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51750. _super.prototype.dispose.call(this);
  51751. };
  51752. // Private Methods
  51753. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  51754. var _this = this;
  51755. /*
  51756. var samplerOffsets = [
  51757. -8.0, -6.0, -4.0, -2.0,
  51758. 0.0,
  51759. 2.0, 4.0, 6.0, 8.0
  51760. ];
  51761. */
  51762. var samples = 16;
  51763. var samplerOffsets = [];
  51764. for (var i = -8; i < 8; i++) {
  51765. samplerOffsets.push(i * 2);
  51766. }
  51767. 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");
  51768. this._blurHPostProcess.onApply = function (effect) {
  51769. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  51770. effect.setTexture("depthSampler", _this._depthTexture);
  51771. if (_this._firstUpdate) {
  51772. effect.setArray("samplerOffsets", samplerOffsets);
  51773. }
  51774. };
  51775. 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");
  51776. this._blurVPostProcess.onApply = function (effect) {
  51777. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  51778. effect.setTexture("depthSampler", _this._depthTexture);
  51779. if (_this._firstUpdate) {
  51780. effect.setArray("samplerOffsets", samplerOffsets);
  51781. _this._firstUpdate = false;
  51782. }
  51783. };
  51784. };
  51785. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  51786. var _this = this;
  51787. var numSamples = 16;
  51788. var sampleSphere = [
  51789. 0.5381, 0.1856, -0.4319,
  51790. 0.1379, 0.2486, 0.4430,
  51791. 0.3371, 0.5679, -0.0057,
  51792. -0.6999, -0.0451, -0.0019,
  51793. 0.0689, -0.1598, -0.8547,
  51794. 0.0560, 0.0069, -0.1843,
  51795. -0.0146, 0.1402, 0.0762,
  51796. 0.0100, -0.1924, -0.0344,
  51797. -0.3577, -0.5301, -0.4358,
  51798. -0.3169, 0.1063, 0.0158,
  51799. 0.0103, -0.5869, 0.0046,
  51800. -0.0897, -0.4940, 0.3287,
  51801. 0.7119, -0.0154, -0.0918,
  51802. -0.0533, 0.0596, -0.5411,
  51803. 0.0352, -0.0631, 0.5460,
  51804. -0.4776, 0.2847, -0.0271
  51805. ];
  51806. var samplesFactor = 1.0 / numSamples;
  51807. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  51808. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  51809. "area", "fallOff", "base", "range", "viewport"
  51810. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  51811. var viewport = new BABYLON.Vector2(0, 0);
  51812. this._ssaoPostProcess.onApply = function (effect) {
  51813. if (_this._firstUpdate) {
  51814. effect.setArray3("sampleSphere", sampleSphere);
  51815. effect.setFloat("samplesFactor", samplesFactor);
  51816. effect.setFloat("randTextureTiles", 4.0);
  51817. }
  51818. effect.setFloat("totalStrength", _this.totalStrength);
  51819. effect.setFloat("radius", _this.radius);
  51820. effect.setFloat("area", _this.area);
  51821. effect.setFloat("fallOff", _this.fallOff);
  51822. effect.setFloat("base", _this.base);
  51823. effect.setTexture("textureSampler", _this._depthTexture);
  51824. effect.setTexture("randomSampler", _this._randomTexture);
  51825. };
  51826. };
  51827. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  51828. var _this = this;
  51829. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51830. this._ssaoCombinePostProcess.onApply = function (effect) {
  51831. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  51832. };
  51833. };
  51834. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  51835. var size = 512;
  51836. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51837. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51838. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51839. var context = this._randomTexture.getContext();
  51840. var rand = function (min, max) {
  51841. return Math.random() * (max - min) + min;
  51842. };
  51843. var randVector = BABYLON.Vector3.Zero();
  51844. for (var x = 0; x < size; x++) {
  51845. for (var y = 0; y < size; y++) {
  51846. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  51847. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  51848. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  51849. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  51850. context.fillRect(x, y, 1, 1);
  51851. }
  51852. }
  51853. this._randomTexture.update(false);
  51854. };
  51855. __decorate([
  51856. BABYLON.serialize()
  51857. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  51858. __decorate([
  51859. BABYLON.serialize()
  51860. ], SSAORenderingPipeline.prototype, "radius", void 0);
  51861. __decorate([
  51862. BABYLON.serialize()
  51863. ], SSAORenderingPipeline.prototype, "area", void 0);
  51864. __decorate([
  51865. BABYLON.serialize()
  51866. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  51867. __decorate([
  51868. BABYLON.serialize()
  51869. ], SSAORenderingPipeline.prototype, "base", void 0);
  51870. __decorate([
  51871. BABYLON.serialize()
  51872. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  51873. return SSAORenderingPipeline;
  51874. }(BABYLON.PostProcessRenderPipeline));
  51875. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  51876. })(BABYLON || (BABYLON = {}));
  51877. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  51878. var BABYLON;
  51879. (function (BABYLON) {
  51880. var SSAO2RenderingPipeline = (function (_super) {
  51881. __extends(SSAO2RenderingPipeline, _super);
  51882. /**
  51883. * @constructor
  51884. * @param {string} name - The rendering pipeline name
  51885. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51886. * @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 }
  51887. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51888. */
  51889. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  51890. var _this = _super.call(this, scene.getEngine(), name) || this;
  51891. // Members
  51892. /**
  51893. * The PassPostProcess id in the pipeline that contains the original scene color
  51894. * @type {string}
  51895. */
  51896. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  51897. /**
  51898. * The SSAO PostProcess id in the pipeline
  51899. * @type {string}
  51900. */
  51901. _this.SSAORenderEffect = "SSAORenderEffect";
  51902. /**
  51903. * The horizontal blur PostProcess id in the pipeline
  51904. * @type {string}
  51905. */
  51906. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  51907. /**
  51908. * The vertical blur PostProcess id in the pipeline
  51909. * @type {string}
  51910. */
  51911. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  51912. /**
  51913. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  51914. * @type {string}
  51915. */
  51916. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  51917. /**
  51918. * The output strength of the SSAO post-process. Default value is 1.0.
  51919. * @type {number}
  51920. */
  51921. _this.totalStrength = 1.0;
  51922. /**
  51923. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  51924. * @type {number}
  51925. */
  51926. _this.maxZ = 100.0;
  51927. /**
  51928. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  51929. * @type {number}
  51930. */
  51931. _this.minZAspect = 0.2;
  51932. /**
  51933. * Number of samples used for the SSAO calculations. Default value is 8
  51934. * @type {number}
  51935. */
  51936. _this._samples = 8;
  51937. /**
  51938. * Are we using bilateral blur ?
  51939. * @type {boolean}
  51940. */
  51941. _this._expensiveBlur = true;
  51942. /**
  51943. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  51944. * @type {number}
  51945. */
  51946. _this.radius = 2.0;
  51947. /**
  51948. * The base color of the SSAO post-process
  51949. * The final result is "base + ssao" between [0, 1]
  51950. * @type {number}
  51951. */
  51952. _this.base = 0.1;
  51953. _this._firstUpdate = true;
  51954. _this._scene = scene;
  51955. if (!_this.isSupported) {
  51956. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  51957. return _this;
  51958. }
  51959. var ssaoRatio = ratio.ssaoRatio || ratio;
  51960. var blurRatio = ratio.blurRatio || ratio;
  51961. _this._ratio = {
  51962. ssaoRatio: ssaoRatio,
  51963. blurRatio: blurRatio
  51964. };
  51965. // Set up assets
  51966. _this._createRandomTexture();
  51967. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  51968. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  51969. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51970. _this._createSSAOPostProcess(1.0);
  51971. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  51972. _this._createSSAOCombinePostProcess(blurRatio);
  51973. // Set up pipeline
  51974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  51975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  51976. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  51977. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  51978. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  51979. // Finish
  51980. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51981. if (cameras)
  51982. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51983. return _this;
  51984. }
  51985. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  51986. get: function () {
  51987. return this._samples;
  51988. },
  51989. set: function (n) {
  51990. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  51991. this._samples = n;
  51992. this._sampleSphere = this._generateHemisphere();
  51993. this._firstUpdate = true;
  51994. },
  51995. enumerable: true,
  51996. configurable: true
  51997. });
  51998. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  51999. get: function () {
  52000. return this._expensiveBlur;
  52001. },
  52002. set: function (b) {
  52003. 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"]);
  52004. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  52005. this._expensiveBlur = b;
  52006. this._firstUpdate = true;
  52007. },
  52008. enumerable: true,
  52009. configurable: true
  52010. });
  52011. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  52012. /**
  52013. * Support test.
  52014. * @type {boolean}
  52015. */
  52016. get: function () {
  52017. var engine = BABYLON.Engine.LastCreatedEngine;
  52018. return engine.webGLVersion > 1;
  52019. },
  52020. enumerable: true,
  52021. configurable: true
  52022. });
  52023. // Public Methods
  52024. /**
  52025. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52026. */
  52027. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  52028. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  52029. for (var i = 0; i < this._scene.cameras.length; i++) {
  52030. var camera = this._scene.cameras[i];
  52031. this._originalColorPostProcess.dispose(camera);
  52032. this._ssaoPostProcess.dispose(camera);
  52033. this._blurHPostProcess.dispose(camera);
  52034. this._blurVPostProcess.dispose(camera);
  52035. this._ssaoCombinePostProcess.dispose(camera);
  52036. }
  52037. this._randomTexture.dispose();
  52038. if (disableGeometryBufferRenderer)
  52039. this._scene.disableGeometryBufferRenderer();
  52040. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52041. _super.prototype.dispose.call(this);
  52042. };
  52043. // Private Methods
  52044. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  52045. var _this = this;
  52046. var samples = 16;
  52047. this._samplerOffsets = [];
  52048. var expensive = this.expensiveBlur;
  52049. for (var i = -8; i < 8; i++) {
  52050. this._samplerOffsets.push(i * 2 + 0.5);
  52051. }
  52052. 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");
  52053. this._blurHPostProcess.onApply = function (effect) {
  52054. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52055. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52056. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52057. effect.setFloat("radius", _this.radius);
  52058. effect.setTexture("depthSampler", _this._depthTexture);
  52059. if (_this._firstUpdate) {
  52060. effect.setArray("samplerOffsets", _this._samplerOffsets);
  52061. }
  52062. };
  52063. 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");
  52064. this._blurVPostProcess.onApply = function (effect) {
  52065. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52066. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52067. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52068. effect.setFloat("radius", _this.radius);
  52069. effect.setTexture("depthSampler", _this._depthTexture);
  52070. if (_this._firstUpdate) {
  52071. effect.setArray("samplerOffsets", _this._samplerOffsets);
  52072. _this._firstUpdate = false;
  52073. }
  52074. };
  52075. };
  52076. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  52077. var numSamples = this.samples;
  52078. var result = [];
  52079. var vector, scale;
  52080. var rand = function (min, max) {
  52081. return Math.random() * (max - min) + min;
  52082. };
  52083. var lerp = function (start, end, percent) {
  52084. return (start + percent * (end - start));
  52085. };
  52086. var i = 0;
  52087. var normal = new BABYLON.Vector3(0, 0, 1);
  52088. while (i < numSamples) {
  52089. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  52090. vector.normalize();
  52091. scale = i / numSamples;
  52092. scale = lerp(0.1, 1.0, scale * scale);
  52093. vector.scaleInPlace(scale);
  52094. result.push(vector.x, vector.y, vector.z);
  52095. i++;
  52096. }
  52097. return result;
  52098. };
  52099. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52100. var _this = this;
  52101. var numSamples = this.samples;
  52102. this._sampleSphere = this._generateHemisphere();
  52103. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  52104. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52105. "base", "range", "projection", "near", "far", "texelSize",
  52106. "xViewport", "yViewport", "maxZ", "minZAspect"
  52107. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52108. this._ssaoPostProcess.onApply = function (effect) {
  52109. if (_this._firstUpdate) {
  52110. effect.setArray3("sampleSphere", _this._sampleSphere);
  52111. effect.setFloat("randTextureTiles", 4.0);
  52112. }
  52113. effect.setFloat("samplesFactor", 1 / _this.samples);
  52114. effect.setFloat("totalStrength", _this.totalStrength);
  52115. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  52116. effect.setFloat("radius", _this.radius);
  52117. effect.setFloat("maxZ", _this.maxZ);
  52118. effect.setFloat("minZAspect", _this.minZAspect);
  52119. effect.setFloat("base", _this.base);
  52120. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52121. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52122. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  52123. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  52124. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  52125. effect.setTexture("textureSampler", _this._depthTexture);
  52126. effect.setTexture("normalSampler", _this._normalTexture);
  52127. effect.setTexture("randomSampler", _this._randomTexture);
  52128. };
  52129. };
  52130. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52131. var _this = this;
  52132. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52133. this._ssaoCombinePostProcess.onApply = function (effect) {
  52134. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52135. };
  52136. };
  52137. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  52138. var size = 512;
  52139. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52140. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52141. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52142. var context = this._randomTexture.getContext();
  52143. var rand = function (min, max) {
  52144. return Math.random() * (max - min) + min;
  52145. };
  52146. var randVector = BABYLON.Vector3.Zero();
  52147. for (var x = 0; x < size; x++) {
  52148. for (var y = 0; y < size; y++) {
  52149. randVector.x = rand(0.0, 1.0);
  52150. randVector.y = rand(0.0, 1.0);
  52151. randVector.z = 0.0;
  52152. randVector.normalize();
  52153. randVector.scaleInPlace(255);
  52154. randVector.x = Math.floor(randVector.x);
  52155. randVector.y = Math.floor(randVector.y);
  52156. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52157. context.fillRect(x, y, 1, 1);
  52158. }
  52159. }
  52160. this._randomTexture.update(false);
  52161. };
  52162. __decorate([
  52163. BABYLON.serialize()
  52164. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  52165. __decorate([
  52166. BABYLON.serialize()
  52167. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  52168. __decorate([
  52169. BABYLON.serialize()
  52170. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  52171. __decorate([
  52172. BABYLON.serialize("samples")
  52173. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  52174. __decorate([
  52175. BABYLON.serialize("expensiveBlur")
  52176. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  52177. __decorate([
  52178. BABYLON.serialize()
  52179. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  52180. __decorate([
  52181. BABYLON.serialize()
  52182. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  52183. __decorate([
  52184. BABYLON.serialize()
  52185. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  52186. return SSAO2RenderingPipeline;
  52187. }(BABYLON.PostProcessRenderPipeline));
  52188. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  52189. })(BABYLON || (BABYLON = {}));
  52190. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  52191. // BABYLON.JS Chromatic Aberration GLSL Shader
  52192. // Author: Olivier Guyot
  52193. // Separates very slightly R, G and B colors on the edges of the screen
  52194. // Inspired by Francois Tarlier & Martins Upitis
  52195. var BABYLON;
  52196. (function (BABYLON) {
  52197. var LensRenderingPipeline = (function (_super) {
  52198. __extends(LensRenderingPipeline, _super);
  52199. /**
  52200. * @constructor
  52201. *
  52202. * Effect parameters are as follow:
  52203. * {
  52204. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52205. * edge_blur: number; // from 0 to x (1 for realism)
  52206. * distortion: number; // from 0 to x (1 for realism)
  52207. * grain_amount: number; // from 0 to 1
  52208. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52209. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52210. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52211. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52212. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52213. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52214. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52215. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52216. * }
  52217. * Note: if an effect parameter is unset, effect is disabled
  52218. *
  52219. * @param {string} name - The rendering pipeline name
  52220. * @param {object} parameters - An object containing all parameters (see above)
  52221. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52222. * @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)
  52223. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52224. */
  52225. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52226. if (ratio === void 0) { ratio = 1.0; }
  52227. var _this = _super.call(this, scene.getEngine(), name) || this;
  52228. // Lens effects can be of the following:
  52229. // - chromatic aberration (slight shift of RGB colors)
  52230. // - blur on the edge of the lens
  52231. // - lens distortion
  52232. // - depth-of-field blur & highlights enhancing
  52233. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52234. // - grain effect (noise or custom texture)
  52235. // Two additional texture samplers are needed:
  52236. // - depth map (for depth-of-field)
  52237. // - grain texture
  52238. /**
  52239. * The chromatic aberration PostProcess id in the pipeline
  52240. * @type {string}
  52241. */
  52242. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52243. /**
  52244. * The highlights enhancing PostProcess id in the pipeline
  52245. * @type {string}
  52246. */
  52247. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52248. /**
  52249. * The depth-of-field PostProcess id in the pipeline
  52250. * @type {string}
  52251. */
  52252. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52253. _this._scene = scene;
  52254. // Fetch texture samplers
  52255. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52256. if (parameters.grain_texture) {
  52257. _this._grainTexture = parameters.grain_texture;
  52258. }
  52259. else {
  52260. _this._createGrainTexture();
  52261. }
  52262. // save parameters
  52263. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52264. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52265. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52266. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52267. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52268. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52269. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52270. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52271. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52272. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52273. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52274. // Create effects
  52275. _this._createChromaticAberrationPostProcess(ratio);
  52276. _this._createHighlightsPostProcess(ratio);
  52277. _this._createDepthOfFieldPostProcess(ratio / 4);
  52278. // Set up pipeline
  52279. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52280. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52281. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52282. if (_this._highlightsGain === -1) {
  52283. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52284. }
  52285. // Finish
  52286. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52287. if (cameras) {
  52288. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52289. }
  52290. return _this;
  52291. }
  52292. // public methods (self explanatory)
  52293. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52294. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52295. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52296. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52297. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52298. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52299. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52300. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52301. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52302. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52303. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52304. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52305. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52306. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52307. };
  52308. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52309. this._highlightsPostProcess.updateEffect();
  52310. };
  52311. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52312. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52313. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52314. this._highlightsGain = amount;
  52315. };
  52316. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52317. if (this._highlightsGain === -1) {
  52318. this._highlightsGain = 1.0;
  52319. }
  52320. this._highlightsThreshold = amount;
  52321. };
  52322. LensRenderingPipeline.prototype.disableHighlights = function () {
  52323. this._highlightsGain = -1;
  52324. };
  52325. /**
  52326. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52327. */
  52328. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52329. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52330. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52331. this._chromaticAberrationPostProcess = undefined;
  52332. this._highlightsPostProcess = undefined;
  52333. this._depthOfFieldPostProcess = undefined;
  52334. this._grainTexture.dispose();
  52335. if (disableDepthRender)
  52336. this._scene.disableDepthRenderer();
  52337. };
  52338. // colors shifting and distortion
  52339. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52340. var _this = this;
  52341. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52342. [], // samplers
  52343. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52344. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52345. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52346. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52347. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52348. };
  52349. };
  52350. // highlights enhancing
  52351. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52352. var _this = this;
  52353. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52354. [], // samplers
  52355. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52356. this._highlightsPostProcess.onApply = function (effect) {
  52357. effect.setFloat('gain', _this._highlightsGain);
  52358. effect.setFloat('threshold', _this._highlightsThreshold);
  52359. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52360. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52361. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52362. };
  52363. };
  52364. // colors shifting and distortion
  52365. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52366. var _this = this;
  52367. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52368. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52369. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52370. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52371. this._depthOfFieldPostProcess.onApply = function (effect) {
  52372. effect.setTexture("depthSampler", _this._depthTexture);
  52373. effect.setTexture("grainSampler", _this._grainTexture);
  52374. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52375. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52376. effect.setFloat('grain_amount', _this._grainAmount);
  52377. effect.setBool('blur_noise', _this._blurNoise);
  52378. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52379. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52380. effect.setFloat('distortion', _this._distortion);
  52381. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52382. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52383. effect.setFloat('aperture', _this._dofAperture);
  52384. effect.setFloat('darken', _this._dofDarken);
  52385. effect.setFloat('edge_blur', _this._edgeBlur);
  52386. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52387. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52388. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52389. };
  52390. };
  52391. // creates a black and white random noise texture, 512x512
  52392. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52393. var size = 512;
  52394. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52395. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52396. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52397. var context = this._grainTexture.getContext();
  52398. var rand = function (min, max) {
  52399. return Math.random() * (max - min) + min;
  52400. };
  52401. var value;
  52402. for (var x = 0; x < size; x++) {
  52403. for (var y = 0; y < size; y++) {
  52404. value = Math.floor(rand(0.42, 0.58) * 255);
  52405. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52406. context.fillRect(x, y, 1, 1);
  52407. }
  52408. }
  52409. this._grainTexture.update(false);
  52410. };
  52411. return LensRenderingPipeline;
  52412. }(BABYLON.PostProcessRenderPipeline));
  52413. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52414. })(BABYLON || (BABYLON = {}));
  52415. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  52416. var BABYLON;
  52417. (function (BABYLON) {
  52418. var StandardRenderingPipeline = (function (_super) {
  52419. __extends(StandardRenderingPipeline, _super);
  52420. /**
  52421. * @constructor
  52422. * @param {string} name - The rendering pipeline name
  52423. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52424. * @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)
  52425. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  52426. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52427. */
  52428. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  52429. if (originalPostProcess === void 0) { originalPostProcess = null; }
  52430. var _this = _super.call(this, scene.getEngine(), name) || this;
  52431. _this.downSampleX4PostProcess = null;
  52432. _this.brightPassPostProcess = null;
  52433. _this.blurHPostProcesses = [];
  52434. _this.blurVPostProcesses = [];
  52435. _this.textureAdderPostProcess = null;
  52436. _this.volumetricLightPostProcess = null;
  52437. _this.volumetricLightSmoothXPostProcess = null;
  52438. _this.volumetricLightSmoothYPostProcess = null;
  52439. _this.volumetricLightMergePostProces = null;
  52440. _this.volumetricLightFinalPostProcess = null;
  52441. _this.luminancePostProcess = null;
  52442. _this.luminanceDownSamplePostProcesses = [];
  52443. _this.hdrPostProcess = null;
  52444. _this.textureAdderFinalPostProcess = null;
  52445. _this.lensFlareFinalPostProcess = null;
  52446. _this.hdrFinalPostProcess = null;
  52447. _this.lensFlarePostProcess = null;
  52448. _this.lensFlareComposePostProcess = null;
  52449. _this.motionBlurPostProcess = null;
  52450. _this.depthOfFieldPostProcess = null;
  52451. // Values
  52452. _this.brightThreshold = 1.0;
  52453. _this.blurWidth = 512.0;
  52454. _this.horizontalBlur = false;
  52455. _this.exposure = 1.0;
  52456. _this.lensTexture = null;
  52457. _this.volumetricLightCoefficient = 0.2;
  52458. _this.volumetricLightPower = 4.0;
  52459. _this.volumetricLightBlurScale = 64.0;
  52460. _this.sourceLight = null;
  52461. _this.hdrMinimumLuminance = 1.0;
  52462. _this.hdrDecreaseRate = 0.5;
  52463. _this.hdrIncreaseRate = 0.5;
  52464. _this.lensColorTexture = null;
  52465. _this.lensFlareStrength = 20.0;
  52466. _this.lensFlareGhostDispersal = 1.4;
  52467. _this.lensFlareHaloWidth = 0.7;
  52468. _this.lensFlareDistortionStrength = 16.0;
  52469. _this.lensStarTexture = null;
  52470. _this.lensFlareDirtTexture = null;
  52471. _this.depthOfFieldDistance = 10.0;
  52472. _this.depthOfFieldBlurWidth = 64.0;
  52473. _this.motionStrength = 1.0;
  52474. // IAnimatable
  52475. _this.animations = [];
  52476. _this._currentDepthOfFieldSource = null;
  52477. _this._hdrCurrentLuminance = 1.0;
  52478. // Getters and setters
  52479. _this._bloomEnabled = true;
  52480. _this._depthOfFieldEnabled = false;
  52481. _this._vlsEnabled = false;
  52482. _this._lensFlareEnabled = false;
  52483. _this._hdrEnabled = false;
  52484. _this._motionBlurEnabled = false;
  52485. _this._motionBlurSamples = 64.0;
  52486. _this._volumetricLightStepsCount = 50.0;
  52487. _this._cameras = cameras || [];
  52488. // Initialize
  52489. _this._scene = scene;
  52490. _this._basePostProcess = originalPostProcess;
  52491. _this._ratio = ratio;
  52492. // Misc
  52493. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52494. // Finish
  52495. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52496. _this._buildPipeline();
  52497. return _this;
  52498. }
  52499. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  52500. get: function () {
  52501. return this._bloomEnabled;
  52502. },
  52503. set: function (enabled) {
  52504. if (this._bloomEnabled === enabled) {
  52505. return;
  52506. }
  52507. this._bloomEnabled = enabled;
  52508. this._buildPipeline();
  52509. },
  52510. enumerable: true,
  52511. configurable: true
  52512. });
  52513. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  52514. get: function () {
  52515. return this._depthOfFieldEnabled;
  52516. },
  52517. set: function (enabled) {
  52518. if (this._depthOfFieldEnabled === enabled) {
  52519. return;
  52520. }
  52521. this._depthOfFieldEnabled = enabled;
  52522. this._buildPipeline();
  52523. },
  52524. enumerable: true,
  52525. configurable: true
  52526. });
  52527. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  52528. get: function () {
  52529. return this._lensFlareEnabled;
  52530. },
  52531. set: function (enabled) {
  52532. if (this._lensFlareEnabled === enabled) {
  52533. return;
  52534. }
  52535. this._lensFlareEnabled = enabled;
  52536. this._buildPipeline();
  52537. },
  52538. enumerable: true,
  52539. configurable: true
  52540. });
  52541. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  52542. get: function () {
  52543. return this._hdrEnabled;
  52544. },
  52545. set: function (enabled) {
  52546. if (this._hdrEnabled === enabled) {
  52547. return;
  52548. }
  52549. this._hdrEnabled = enabled;
  52550. this._buildPipeline();
  52551. },
  52552. enumerable: true,
  52553. configurable: true
  52554. });
  52555. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  52556. get: function () {
  52557. return this._vlsEnabled;
  52558. },
  52559. set: function (enabled) {
  52560. if (this._vlsEnabled === enabled) {
  52561. return;
  52562. }
  52563. if (enabled) {
  52564. var geometry = this._scene.enableGeometryBufferRenderer();
  52565. if (!geometry) {
  52566. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  52567. return;
  52568. }
  52569. }
  52570. this._vlsEnabled = enabled;
  52571. this._buildPipeline();
  52572. },
  52573. enumerable: true,
  52574. configurable: true
  52575. });
  52576. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  52577. get: function () {
  52578. return this._motionBlurEnabled;
  52579. },
  52580. set: function (enabled) {
  52581. if (this._motionBlurEnabled === enabled) {
  52582. return;
  52583. }
  52584. this._motionBlurEnabled = enabled;
  52585. this._buildPipeline();
  52586. },
  52587. enumerable: true,
  52588. configurable: true
  52589. });
  52590. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  52591. get: function () {
  52592. return this._volumetricLightStepsCount;
  52593. },
  52594. set: function (count) {
  52595. if (this.volumetricLightPostProcess) {
  52596. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  52597. }
  52598. this._volumetricLightStepsCount = count;
  52599. },
  52600. enumerable: true,
  52601. configurable: true
  52602. });
  52603. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  52604. get: function () {
  52605. return this._motionBlurSamples;
  52606. },
  52607. set: function (samples) {
  52608. if (this.motionBlurPostProcess) {
  52609. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  52610. }
  52611. this._motionBlurSamples = samples;
  52612. },
  52613. enumerable: true,
  52614. configurable: true
  52615. });
  52616. StandardRenderingPipeline.prototype._buildPipeline = function () {
  52617. var _this = this;
  52618. var ratio = this._ratio;
  52619. var scene = this._scene;
  52620. this._disposePostProcesses();
  52621. this._reset();
  52622. // Create pass post-process
  52623. if (!this._basePostProcess) {
  52624. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  52625. this.originalPostProcess.onApply = function (effect) {
  52626. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  52627. };
  52628. }
  52629. else {
  52630. this.originalPostProcess = this._basePostProcess;
  52631. }
  52632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  52633. this._currentDepthOfFieldSource = this.originalPostProcess;
  52634. if (this._vlsEnabled) {
  52635. // Create volumetric light
  52636. this._createVolumetricLightPostProcess(scene, ratio);
  52637. // Create volumetric light final post-process
  52638. 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);
  52639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  52640. }
  52641. if (this._bloomEnabled) {
  52642. // Create down sample X4 post-process
  52643. this._createDownSampleX4PostProcess(scene, ratio / 2);
  52644. // Create bright pass post-process
  52645. this._createBrightPassPostProcess(scene, ratio / 2);
  52646. // Create gaussian blur post-processes (down sampling blurs)
  52647. this._createBlurPostProcesses(scene, ratio / 4, 1);
  52648. // Create texture adder post-process
  52649. this._createTextureAdderPostProcess(scene, ratio);
  52650. // Create depth-of-field source post-process
  52651. 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);
  52652. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  52653. }
  52654. if (this._lensFlareEnabled) {
  52655. // Create lens flare post-process
  52656. this._createLensFlarePostProcess(scene, ratio);
  52657. // Create depth-of-field source post-process post lens-flare and disable it now
  52658. 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);
  52659. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  52660. }
  52661. if (this._hdrEnabled) {
  52662. // Create luminance
  52663. this._createLuminancePostProcesses(scene, this._floatTextureType);
  52664. // Create HDR
  52665. this._createHdrPostProcess(scene, ratio);
  52666. // Create depth-of-field source post-process post hdr and disable it now
  52667. 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);
  52668. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  52669. }
  52670. if (this._depthOfFieldEnabled) {
  52671. // Create gaussian blur used by depth-of-field
  52672. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  52673. // Create depth-of-field post-process
  52674. this._createDepthOfFieldPostProcess(scene, ratio);
  52675. }
  52676. if (this._motionBlurEnabled) {
  52677. // Create motion blur post-process
  52678. this._createMotionBlurPostProcess(scene, ratio);
  52679. }
  52680. if (this._cameras !== null) {
  52681. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  52682. }
  52683. };
  52684. // Down Sample X4 Post-Processs
  52685. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  52686. var _this = this;
  52687. var downSampleX4Offsets = new Array(32);
  52688. 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);
  52689. this.downSampleX4PostProcess.onApply = function (effect) {
  52690. var id = 0;
  52691. for (var i = -2; i < 2; i++) {
  52692. for (var j = -2; j < 2; j++) {
  52693. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  52694. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  52695. id += 2;
  52696. }
  52697. }
  52698. effect.setArray2("dsOffsets", downSampleX4Offsets);
  52699. };
  52700. // Add to pipeline
  52701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  52702. };
  52703. // Brightpass Post-Process
  52704. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  52705. var _this = this;
  52706. var brightOffsets = new Array(8);
  52707. 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);
  52708. this.brightPassPostProcess.onApply = function (effect) {
  52709. var sU = (1.0 / _this.brightPassPostProcess.width);
  52710. var sV = (1.0 / _this.brightPassPostProcess.height);
  52711. brightOffsets[0] = -0.5 * sU;
  52712. brightOffsets[1] = 0.5 * sV;
  52713. brightOffsets[2] = 0.5 * sU;
  52714. brightOffsets[3] = 0.5 * sV;
  52715. brightOffsets[4] = -0.5 * sU;
  52716. brightOffsets[5] = -0.5 * sV;
  52717. brightOffsets[6] = 0.5 * sU;
  52718. brightOffsets[7] = -0.5 * sV;
  52719. effect.setArray2("dsOffsets", brightOffsets);
  52720. effect.setFloat("brightThreshold", _this.brightThreshold);
  52721. };
  52722. // Add to pipeline
  52723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  52724. };
  52725. // Create blur H&V post-processes
  52726. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  52727. var _this = this;
  52728. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  52729. var engine = scene.getEngine();
  52730. 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);
  52731. 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);
  52732. blurX.onActivateObservable.add(function () {
  52733. var dw = blurX.width / engine.getRenderingCanvas().width;
  52734. blurX.kernel = _this[blurWidthKey] * dw;
  52735. });
  52736. blurY.onActivateObservable.add(function () {
  52737. var dw = blurY.height / engine.getRenderingCanvas().height;
  52738. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  52739. });
  52740. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  52741. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  52742. this.blurHPostProcesses.push(blurX);
  52743. this.blurVPostProcesses.push(blurY);
  52744. };
  52745. // Create texture adder post-process
  52746. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  52747. var _this = this;
  52748. 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);
  52749. this.textureAdderPostProcess.onApply = function (effect) {
  52750. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  52751. effect.setTexture("lensSampler", _this.lensTexture);
  52752. effect.setFloat("exposure", _this.exposure);
  52753. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  52754. };
  52755. // Add to pipeline
  52756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  52757. };
  52758. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  52759. var _this = this;
  52760. var geometryRenderer = scene.enableGeometryBufferRenderer();
  52761. geometryRenderer.enablePosition = true;
  52762. var geometry = geometryRenderer.getGBuffer();
  52763. // Base post-process
  52764. 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));
  52765. var depthValues = BABYLON.Vector2.Zero();
  52766. this.volumetricLightPostProcess.onApply = function (effect) {
  52767. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  52768. var generator = _this.sourceLight.getShadowGenerator();
  52769. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  52770. effect.setTexture("positionSampler", geometry.textures[2]);
  52771. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  52772. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  52773. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  52774. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  52775. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  52776. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  52777. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  52778. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  52779. effect.setVector2("depthValues", depthValues);
  52780. }
  52781. };
  52782. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  52783. // Smooth
  52784. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  52785. // Merge
  52786. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  52787. this.volumetricLightMergePostProces.onApply = function (effect) {
  52788. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  52789. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  52790. };
  52791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  52792. };
  52793. // Create luminance
  52794. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  52795. var _this = this;
  52796. // Create luminance
  52797. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  52798. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  52799. var offsets = [];
  52800. this.luminancePostProcess.onApply = function (effect) {
  52801. var sU = (1.0 / _this.luminancePostProcess.width);
  52802. var sV = (1.0 / _this.luminancePostProcess.height);
  52803. offsets[0] = -0.5 * sU;
  52804. offsets[1] = 0.5 * sV;
  52805. offsets[2] = 0.5 * sU;
  52806. offsets[3] = 0.5 * sV;
  52807. offsets[4] = -0.5 * sU;
  52808. offsets[5] = -0.5 * sV;
  52809. offsets[6] = 0.5 * sU;
  52810. offsets[7] = -0.5 * sV;
  52811. effect.setArray2("lumOffsets", offsets);
  52812. };
  52813. // Add to pipeline
  52814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  52815. // Create down sample luminance
  52816. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  52817. var size = Math.pow(3, i);
  52818. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  52819. if (i === 0) {
  52820. defines += "#define FINAL_DOWN_SAMPLER";
  52821. }
  52822. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  52823. this.luminanceDownSamplePostProcesses.push(postProcess);
  52824. }
  52825. // Create callbacks and add effects
  52826. var lastLuminance = this.luminancePostProcess;
  52827. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  52828. var downSampleOffsets = new Array(18);
  52829. pp.onApply = function (effect) {
  52830. var id = 0;
  52831. for (var x = -1; x < 2; x++) {
  52832. for (var y = -1; y < 2; y++) {
  52833. downSampleOffsets[id] = x / lastLuminance.width;
  52834. downSampleOffsets[id + 1] = y / lastLuminance.height;
  52835. id += 2;
  52836. }
  52837. }
  52838. effect.setArray2("dsOffsets", downSampleOffsets);
  52839. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  52840. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  52841. lastLuminance = _this.luminancePostProcess;
  52842. }
  52843. else {
  52844. lastLuminance = pp;
  52845. }
  52846. };
  52847. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  52848. pp.onAfterRender = function (effect) {
  52849. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  52850. 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);
  52851. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  52852. };
  52853. }
  52854. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  52855. });
  52856. };
  52857. // Create HDR post-process
  52858. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  52859. var _this = this;
  52860. 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);
  52861. var outputLiminance = 1;
  52862. var time = 0;
  52863. var lastTime = 0;
  52864. this.hdrPostProcess.onApply = function (effect) {
  52865. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  52866. time += scene.getEngine().getDeltaTime();
  52867. if (outputLiminance < 0) {
  52868. outputLiminance = _this._hdrCurrentLuminance;
  52869. }
  52870. else {
  52871. var dt = (lastTime - time) / 1000.0;
  52872. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  52873. outputLiminance += _this.hdrDecreaseRate * dt;
  52874. }
  52875. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  52876. outputLiminance -= _this.hdrIncreaseRate * dt;
  52877. }
  52878. else {
  52879. outputLiminance = _this._hdrCurrentLuminance;
  52880. }
  52881. }
  52882. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  52883. effect.setFloat("averageLuminance", outputLiminance);
  52884. lastTime = time;
  52885. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  52886. };
  52887. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  52888. };
  52889. // Create lens flare post-process
  52890. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  52891. var _this = this;
  52892. 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);
  52893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  52894. this._createBlurPostProcesses(scene, ratio / 4, 2);
  52895. 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);
  52896. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  52897. var resolution = new BABYLON.Vector2(0, 0);
  52898. // Lens flare
  52899. this.lensFlarePostProcess.onApply = function (effect) {
  52900. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  52901. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  52902. effect.setFloat("strength", _this.lensFlareStrength);
  52903. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  52904. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  52905. // Shift
  52906. resolution.x = _this.lensFlarePostProcess.width;
  52907. resolution.y = _this.lensFlarePostProcess.height;
  52908. effect.setVector2("resolution", resolution);
  52909. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  52910. };
  52911. // Compose
  52912. 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);
  52913. 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);
  52914. this.lensFlareComposePostProcess.onApply = function (effect) {
  52915. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  52916. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  52917. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  52918. // Lens start rotation matrix
  52919. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  52920. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  52921. 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));
  52922. camRot *= 4.0;
  52923. 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);
  52924. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  52925. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  52926. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  52927. };
  52928. };
  52929. // Create depth-of-field post-process
  52930. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  52931. var _this = this;
  52932. 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);
  52933. this.depthOfFieldPostProcess.onApply = function (effect) {
  52934. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  52935. effect.setTexture("depthSampler", _this._getDepthTexture());
  52936. effect.setFloat("distance", _this.depthOfFieldDistance);
  52937. };
  52938. // Add to pipeline
  52939. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  52940. };
  52941. // Create motion blur post-process
  52942. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  52943. var _this = this;
  52944. 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);
  52945. var motionScale = 0;
  52946. var prevViewProjection = BABYLON.Matrix.Identity();
  52947. var invViewProjection = BABYLON.Matrix.Identity();
  52948. var viewProjection = BABYLON.Matrix.Identity();
  52949. var screenSize = BABYLON.Vector2.Zero();
  52950. this.motionBlurPostProcess.onApply = function (effect) {
  52951. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  52952. viewProjection.invertToRef(invViewProjection);
  52953. effect.setMatrix("inverseViewProjection", invViewProjection);
  52954. effect.setMatrix("prevViewProjection", prevViewProjection);
  52955. prevViewProjection = viewProjection;
  52956. screenSize.x = _this.motionBlurPostProcess.width;
  52957. screenSize.y = _this.motionBlurPostProcess.height;
  52958. effect.setVector2("screenSize", screenSize);
  52959. motionScale = scene.getEngine().getFps() / 60.0;
  52960. effect.setFloat("motionScale", motionScale);
  52961. effect.setFloat("motionStrength", _this.motionStrength);
  52962. effect.setTexture("depthSampler", _this._getDepthTexture());
  52963. };
  52964. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  52965. };
  52966. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  52967. var geometry = this._scene.enableGeometryBufferRenderer();
  52968. if (geometry) {
  52969. return geometry.getGBuffer().textures[0];
  52970. }
  52971. return this._scene.enableDepthRenderer().getDepthMap();
  52972. };
  52973. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  52974. for (var i = 0; i < this._cameras.length; i++) {
  52975. var camera = this._cameras[i];
  52976. if (this.originalPostProcess) {
  52977. this.originalPostProcess.dispose(camera);
  52978. }
  52979. if (this.downSampleX4PostProcess) {
  52980. this.downSampleX4PostProcess.dispose(camera);
  52981. }
  52982. if (this.brightPassPostProcess) {
  52983. this.brightPassPostProcess.dispose(camera);
  52984. }
  52985. if (this.textureAdderPostProcess) {
  52986. this.textureAdderPostProcess.dispose(camera);
  52987. }
  52988. if (this.textureAdderFinalPostProcess) {
  52989. this.textureAdderFinalPostProcess.dispose(camera);
  52990. }
  52991. if (this.volumetricLightPostProcess) {
  52992. this.volumetricLightPostProcess.dispose(camera);
  52993. }
  52994. if (this.volumetricLightSmoothXPostProcess) {
  52995. this.volumetricLightSmoothXPostProcess.dispose(camera);
  52996. }
  52997. if (this.volumetricLightSmoothYPostProcess) {
  52998. this.volumetricLightSmoothYPostProcess.dispose(camera);
  52999. }
  53000. if (this.volumetricLightMergePostProces) {
  53001. this.volumetricLightMergePostProces.dispose(camera);
  53002. }
  53003. if (this.volumetricLightFinalPostProcess) {
  53004. this.volumetricLightFinalPostProcess.dispose(camera);
  53005. }
  53006. if (this.lensFlarePostProcess) {
  53007. this.lensFlarePostProcess.dispose(camera);
  53008. }
  53009. if (this.lensFlareComposePostProcess) {
  53010. this.lensFlareComposePostProcess.dispose(camera);
  53011. }
  53012. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  53013. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  53014. }
  53015. if (this.luminancePostProcess) {
  53016. this.luminancePostProcess.dispose(camera);
  53017. }
  53018. if (this.hdrPostProcess) {
  53019. this.hdrPostProcess.dispose(camera);
  53020. }
  53021. if (this.hdrFinalPostProcess) {
  53022. this.hdrFinalPostProcess.dispose(camera);
  53023. }
  53024. if (this.depthOfFieldPostProcess) {
  53025. this.depthOfFieldPostProcess.dispose(camera);
  53026. }
  53027. if (this.motionBlurPostProcess) {
  53028. this.motionBlurPostProcess.dispose(camera);
  53029. }
  53030. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  53031. this.blurHPostProcesses[j].dispose(camera);
  53032. }
  53033. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  53034. this.blurVPostProcesses[j].dispose(camera);
  53035. }
  53036. }
  53037. this.originalPostProcess = null;
  53038. this.downSampleX4PostProcess = null;
  53039. this.brightPassPostProcess = null;
  53040. this.textureAdderPostProcess = null;
  53041. this.textureAdderFinalPostProcess = null;
  53042. this.volumetricLightPostProcess = null;
  53043. this.volumetricLightSmoothXPostProcess = null;
  53044. this.volumetricLightSmoothYPostProcess = null;
  53045. this.volumetricLightMergePostProces = null;
  53046. this.volumetricLightFinalPostProcess = null;
  53047. this.lensFlarePostProcess = null;
  53048. this.lensFlareComposePostProcess = null;
  53049. this.luminancePostProcess = null;
  53050. this.hdrPostProcess = null;
  53051. this.hdrFinalPostProcess = null;
  53052. this.depthOfFieldPostProcess = null;
  53053. this.motionBlurPostProcess = null;
  53054. this.luminanceDownSamplePostProcesses = [];
  53055. this.blurHPostProcesses = [];
  53056. this.blurVPostProcesses = [];
  53057. };
  53058. // Dispose
  53059. StandardRenderingPipeline.prototype.dispose = function () {
  53060. this._disposePostProcesses();
  53061. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53062. _super.prototype.dispose.call(this);
  53063. };
  53064. // Serialize rendering pipeline
  53065. StandardRenderingPipeline.prototype.serialize = function () {
  53066. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53067. serializationObject.customType = "StandardRenderingPipeline";
  53068. return serializationObject;
  53069. };
  53070. /**
  53071. * Static members
  53072. */
  53073. // Parse serialized pipeline
  53074. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53075. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  53076. };
  53077. // Luminance steps
  53078. StandardRenderingPipeline.LuminanceSteps = 6;
  53079. __decorate([
  53080. BABYLON.serialize()
  53081. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  53082. __decorate([
  53083. BABYLON.serialize()
  53084. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  53085. __decorate([
  53086. BABYLON.serialize()
  53087. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  53088. __decorate([
  53089. BABYLON.serialize()
  53090. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  53091. __decorate([
  53092. BABYLON.serializeAsTexture("lensTexture")
  53093. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  53094. __decorate([
  53095. BABYLON.serialize()
  53096. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  53097. __decorate([
  53098. BABYLON.serialize()
  53099. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  53100. __decorate([
  53101. BABYLON.serialize()
  53102. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  53103. __decorate([
  53104. BABYLON.serialize()
  53105. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  53106. __decorate([
  53107. BABYLON.serialize()
  53108. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  53109. __decorate([
  53110. BABYLON.serialize()
  53111. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  53112. __decorate([
  53113. BABYLON.serializeAsTexture("lensColorTexture")
  53114. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  53115. __decorate([
  53116. BABYLON.serialize()
  53117. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  53118. __decorate([
  53119. BABYLON.serialize()
  53120. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  53121. __decorate([
  53122. BABYLON.serialize()
  53123. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  53124. __decorate([
  53125. BABYLON.serialize()
  53126. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  53127. __decorate([
  53128. BABYLON.serializeAsTexture("lensStarTexture")
  53129. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  53130. __decorate([
  53131. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  53132. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  53133. __decorate([
  53134. BABYLON.serialize()
  53135. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  53136. __decorate([
  53137. BABYLON.serialize()
  53138. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  53139. __decorate([
  53140. BABYLON.serialize()
  53141. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  53142. __decorate([
  53143. BABYLON.serialize()
  53144. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  53145. __decorate([
  53146. BABYLON.serialize()
  53147. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  53148. __decorate([
  53149. BABYLON.serialize()
  53150. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  53151. __decorate([
  53152. BABYLON.serialize()
  53153. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  53154. __decorate([
  53155. BABYLON.serialize()
  53156. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  53157. __decorate([
  53158. BABYLON.serialize()
  53159. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  53160. __decorate([
  53161. BABYLON.serialize()
  53162. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  53163. __decorate([
  53164. BABYLON.serialize()
  53165. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  53166. return StandardRenderingPipeline;
  53167. }(BABYLON.PostProcessRenderPipeline));
  53168. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  53169. })(BABYLON || (BABYLON = {}));
  53170. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  53171. var BABYLON;
  53172. (function (BABYLON) {
  53173. var FxaaPostProcess = (function (_super) {
  53174. __extends(FxaaPostProcess, _super);
  53175. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53177. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  53178. _this.onApplyObservable.add(function (effect) {
  53179. var texelSize = _this.texelSize;
  53180. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  53181. });
  53182. return _this;
  53183. }
  53184. return FxaaPostProcess;
  53185. }(BABYLON.PostProcess));
  53186. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53187. })(BABYLON || (BABYLON = {}));
  53188. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  53189. var BABYLON;
  53190. (function (BABYLON) {
  53191. var DefaultRenderingPipeline = (function (_super) {
  53192. __extends(DefaultRenderingPipeline, _super);
  53193. /**
  53194. * @constructor
  53195. * @param {string} name - The rendering pipeline name
  53196. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53197. * @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)
  53198. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53199. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  53200. */
  53201. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  53202. if (automaticBuild === void 0) { automaticBuild = true; }
  53203. var _this = _super.call(this, scene.getEngine(), name) || this;
  53204. _this.PassPostProcessId = "PassPostProcessEffect";
  53205. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  53206. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  53207. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  53208. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  53209. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  53210. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  53211. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  53212. // IAnimatable
  53213. _this.animations = [];
  53214. // Values
  53215. _this._bloomEnabled = false;
  53216. _this._fxaaEnabled = false;
  53217. _this._imageProcessingEnabled = true;
  53218. _this._bloomScale = 0.6;
  53219. _this._buildAllowed = true;
  53220. /**
  53221. * Specifies the size of the bloom blur kernel, relative to the final output size
  53222. */
  53223. _this.bloomKernel = 64;
  53224. /**
  53225. * Specifies the weight of the bloom in the final rendering
  53226. */
  53227. _this._bloomWeight = 0.15;
  53228. _this._cameras = cameras || [];
  53229. _this._buildAllowed = automaticBuild;
  53230. // Initialize
  53231. _this._scene = scene;
  53232. var caps = _this._scene.getEngine().getCaps();
  53233. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  53234. // Misc
  53235. if (_this._hdr) {
  53236. if (caps.textureHalfFloatRender) {
  53237. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53238. }
  53239. else if (caps.textureFloatRender) {
  53240. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53241. }
  53242. }
  53243. else {
  53244. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53245. }
  53246. // Attach
  53247. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53248. _this._buildPipeline();
  53249. return _this;
  53250. }
  53251. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  53252. get: function () {
  53253. return this._bloomWeight;
  53254. },
  53255. set: function (value) {
  53256. if (this._bloomWeight === value) {
  53257. return;
  53258. }
  53259. this._bloomWeight = value;
  53260. if (this._hdr && this.copyBack) {
  53261. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  53262. }
  53263. },
  53264. enumerable: true,
  53265. configurable: true
  53266. });
  53267. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  53268. get: function () {
  53269. return this._bloomScale;
  53270. },
  53271. set: function (value) {
  53272. if (this._bloomScale === value) {
  53273. return;
  53274. }
  53275. this._bloomScale = value;
  53276. this._buildPipeline();
  53277. },
  53278. enumerable: true,
  53279. configurable: true
  53280. });
  53281. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  53282. get: function () {
  53283. return this._bloomEnabled;
  53284. },
  53285. set: function (enabled) {
  53286. if (this._bloomEnabled === enabled) {
  53287. return;
  53288. }
  53289. this._bloomEnabled = enabled;
  53290. this._buildPipeline();
  53291. },
  53292. enumerable: true,
  53293. configurable: true
  53294. });
  53295. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  53296. get: function () {
  53297. return this._fxaaEnabled;
  53298. },
  53299. set: function (enabled) {
  53300. if (this._fxaaEnabled === enabled) {
  53301. return;
  53302. }
  53303. this._fxaaEnabled = enabled;
  53304. this._buildPipeline();
  53305. },
  53306. enumerable: true,
  53307. configurable: true
  53308. });
  53309. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  53310. get: function () {
  53311. return this._imageProcessingEnabled;
  53312. },
  53313. set: function (enabled) {
  53314. if (this._imageProcessingEnabled === enabled) {
  53315. return;
  53316. }
  53317. this._imageProcessingEnabled = enabled;
  53318. this._buildPipeline();
  53319. },
  53320. enumerable: true,
  53321. configurable: true
  53322. });
  53323. /**
  53324. * Force the compilation of the entire pipeline.
  53325. */
  53326. DefaultRenderingPipeline.prototype.prepare = function () {
  53327. var previousState = this._buildAllowed;
  53328. this._buildAllowed = true;
  53329. this._buildPipeline();
  53330. this._buildAllowed = previousState;
  53331. };
  53332. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  53333. var _this = this;
  53334. if (!this._buildAllowed) {
  53335. return;
  53336. }
  53337. var engine = this._scene.getEngine();
  53338. this._disposePostProcesses();
  53339. this._reset();
  53340. if (this.bloomEnabled) {
  53341. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53342. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  53343. if (!this._hdr) {
  53344. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53345. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  53346. this.highlights.autoClear = false;
  53347. this.highlights.alwaysForcePOT = true;
  53348. }
  53349. 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);
  53350. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  53351. this.blurX.alwaysForcePOT = true;
  53352. this.blurX.autoClear = false;
  53353. this.blurX.onActivateObservable.add(function () {
  53354. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  53355. _this.blurX.kernel = _this.bloomKernel * dw;
  53356. });
  53357. 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);
  53358. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  53359. this.blurY.alwaysForcePOT = true;
  53360. this.blurY.autoClear = false;
  53361. this.blurY.onActivateObservable.add(function () {
  53362. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  53363. _this.blurY.kernel = _this.bloomKernel * dh;
  53364. });
  53365. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53366. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  53367. this.copyBack.alwaysForcePOT = true;
  53368. if (this._hdr) {
  53369. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  53370. var w = this.bloomWeight;
  53371. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  53372. }
  53373. else {
  53374. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  53375. }
  53376. this.copyBack.autoClear = false;
  53377. }
  53378. if (this._imageProcessingEnabled) {
  53379. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53380. if (this._hdr) {
  53381. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  53382. }
  53383. }
  53384. if (this.fxaaEnabled) {
  53385. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53386. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  53387. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  53388. }
  53389. else {
  53390. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53391. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  53392. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  53393. }
  53394. if (this.bloomEnabled) {
  53395. if (this._hdr) {
  53396. this.copyBack.shareOutputWith(this.blurX);
  53397. if (this.imageProcessing) {
  53398. this.imageProcessing.shareOutputWith(this.pass);
  53399. this.imageProcessing.autoClear = false;
  53400. }
  53401. else if (this.fxaa) {
  53402. this.fxaa.shareOutputWith(this.pass);
  53403. }
  53404. else {
  53405. this.finalMerge.shareOutputWith(this.pass);
  53406. }
  53407. }
  53408. else {
  53409. if (this.fxaa) {
  53410. this.fxaa.shareOutputWith(this.pass);
  53411. }
  53412. else {
  53413. this.finalMerge.shareOutputWith(this.pass);
  53414. }
  53415. }
  53416. }
  53417. if (this._cameras !== null) {
  53418. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53419. }
  53420. };
  53421. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  53422. for (var i = 0; i < this._cameras.length; i++) {
  53423. var camera = this._cameras[i];
  53424. if (this.pass) {
  53425. this.pass.dispose(camera);
  53426. }
  53427. if (this.highlights) {
  53428. this.highlights.dispose(camera);
  53429. }
  53430. if (this.blurX) {
  53431. this.blurX.dispose(camera);
  53432. }
  53433. if (this.blurY) {
  53434. this.blurY.dispose(camera);
  53435. }
  53436. if (this.copyBack) {
  53437. this.copyBack.dispose(camera);
  53438. }
  53439. if (this.imageProcessing) {
  53440. this.imageProcessing.dispose(camera);
  53441. }
  53442. if (this.fxaa) {
  53443. this.fxaa.dispose(camera);
  53444. }
  53445. if (this.finalMerge) {
  53446. this.finalMerge.dispose(camera);
  53447. }
  53448. }
  53449. this.pass = null;
  53450. this.highlights = null;
  53451. this.blurX = null;
  53452. this.blurY = null;
  53453. this.copyBack = null;
  53454. this.imageProcessing = null;
  53455. this.fxaa = null;
  53456. this.finalMerge = null;
  53457. };
  53458. // Dispose
  53459. DefaultRenderingPipeline.prototype.dispose = function () {
  53460. this._disposePostProcesses();
  53461. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53462. _super.prototype.dispose.call(this);
  53463. };
  53464. // Serialize rendering pipeline
  53465. DefaultRenderingPipeline.prototype.serialize = function () {
  53466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53467. serializationObject.customType = "DefaultRenderingPipeline";
  53468. return serializationObject;
  53469. };
  53470. // Parse serialized pipeline
  53471. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53472. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  53473. };
  53474. __decorate([
  53475. BABYLON.serialize()
  53476. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  53477. __decorate([
  53478. BABYLON.serialize()
  53479. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  53480. __decorate([
  53481. BABYLON.serialize()
  53482. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  53483. __decorate([
  53484. BABYLON.serialize()
  53485. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  53486. __decorate([
  53487. BABYLON.serialize()
  53488. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  53489. __decorate([
  53490. BABYLON.serialize()
  53491. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  53492. __decorate([
  53493. BABYLON.serialize()
  53494. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  53495. __decorate([
  53496. BABYLON.serialize()
  53497. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  53498. return DefaultRenderingPipeline;
  53499. }(BABYLON.PostProcessRenderPipeline));
  53500. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  53501. })(BABYLON || (BABYLON = {}));
  53502. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  53503. var BABYLON;
  53504. (function (BABYLON) {
  53505. var GeometryBufferRenderer = (function () {
  53506. function GeometryBufferRenderer(scene, ratio) {
  53507. if (ratio === void 0) { ratio = 1; }
  53508. this._viewMatrix = BABYLON.Matrix.Zero();
  53509. this._projectionMatrix = BABYLON.Matrix.Zero();
  53510. this._transformMatrix = BABYLON.Matrix.Zero();
  53511. this._worldViewProjection = BABYLON.Matrix.Zero();
  53512. this._enablePosition = false;
  53513. this._scene = scene;
  53514. this._ratio = ratio;
  53515. // Render target
  53516. this._createRenderTargets();
  53517. }
  53518. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  53519. set: function (meshes) {
  53520. this._multiRenderTarget.renderList = meshes;
  53521. },
  53522. enumerable: true,
  53523. configurable: true
  53524. });
  53525. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  53526. get: function () {
  53527. return this._multiRenderTarget.isSupported;
  53528. },
  53529. enumerable: true,
  53530. configurable: true
  53531. });
  53532. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  53533. get: function () {
  53534. return this._enablePosition;
  53535. },
  53536. set: function (enable) {
  53537. this._enablePosition = enable;
  53538. this.dispose();
  53539. this._createRenderTargets();
  53540. },
  53541. enumerable: true,
  53542. configurable: true
  53543. });
  53544. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  53545. var material = subMesh.getMaterial();
  53546. if (material && material.disableDepthWrite) {
  53547. return false;
  53548. }
  53549. var defines = [];
  53550. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  53551. var mesh = subMesh.getMesh();
  53552. var scene = mesh.getScene();
  53553. // Alpha test
  53554. if (material && material.needAlphaTesting()) {
  53555. defines.push("#define ALPHATEST");
  53556. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53557. attribs.push(BABYLON.VertexBuffer.UVKind);
  53558. defines.push("#define UV1");
  53559. }
  53560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53561. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53562. defines.push("#define UV2");
  53563. }
  53564. }
  53565. // Buffers
  53566. if (this._enablePosition) {
  53567. defines.push("#define POSITION");
  53568. }
  53569. // Bones
  53570. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53571. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53572. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53573. if (mesh.numBoneInfluencers > 4) {
  53574. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53575. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53576. }
  53577. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53578. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53579. }
  53580. else {
  53581. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53582. }
  53583. // Instances
  53584. if (useInstances) {
  53585. defines.push("#define INSTANCES");
  53586. attribs.push("world0");
  53587. attribs.push("world1");
  53588. attribs.push("world2");
  53589. attribs.push("world3");
  53590. }
  53591. // Get correct effect
  53592. var join = defines.join("\n");
  53593. if (this._cachedDefines !== join) {
  53594. this._cachedDefines = join;
  53595. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  53596. }
  53597. return this._effect.isReady();
  53598. };
  53599. GeometryBufferRenderer.prototype.getGBuffer = function () {
  53600. return this._multiRenderTarget;
  53601. };
  53602. // Methods
  53603. GeometryBufferRenderer.prototype.dispose = function () {
  53604. this.getGBuffer().dispose();
  53605. };
  53606. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  53607. var _this = this;
  53608. var engine = this._scene.getEngine();
  53609. var count = this._enablePosition ? 3 : 2;
  53610. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  53611. if (!this.isSupported) {
  53612. return null;
  53613. }
  53614. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53615. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53616. this._multiRenderTarget.refreshRate = 1;
  53617. this._multiRenderTarget.renderParticles = false;
  53618. this._multiRenderTarget.renderList = null;
  53619. // set default depth value to 1.0 (far away)
  53620. this._multiRenderTarget.onClearObservable.add(function (engine) {
  53621. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  53622. });
  53623. // Custom render function
  53624. var renderSubMesh = function (subMesh) {
  53625. var mesh = subMesh.getRenderingMesh();
  53626. var scene = _this._scene;
  53627. var engine = scene.getEngine();
  53628. // Culling
  53629. engine.setState(subMesh.getMaterial().backFaceCulling);
  53630. // Managing instances
  53631. var batch = mesh._getInstancesRenderList(subMesh._id);
  53632. if (batch.mustReturn) {
  53633. return;
  53634. }
  53635. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53636. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53637. engine.enableEffect(_this._effect);
  53638. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53639. var material = subMesh.getMaterial();
  53640. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53641. _this._effect.setMatrix("view", scene.getViewMatrix());
  53642. // Alpha test
  53643. if (material && material.needAlphaTesting()) {
  53644. var alphaTexture = material.getAlphaTestTexture();
  53645. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53646. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53647. }
  53648. // Bones
  53649. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53650. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53651. }
  53652. // Draw
  53653. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53654. }
  53655. };
  53656. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53657. var index;
  53658. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53659. renderSubMesh(opaqueSubMeshes.data[index]);
  53660. }
  53661. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53662. renderSubMesh(alphaTestSubMeshes.data[index]);
  53663. }
  53664. };
  53665. };
  53666. return GeometryBufferRenderer;
  53667. }());
  53668. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  53669. })(BABYLON || (BABYLON = {}));
  53670. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  53671. var BABYLON;
  53672. (function (BABYLON) {
  53673. var RefractionPostProcess = (function (_super) {
  53674. __extends(RefractionPostProcess, _super);
  53675. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  53676. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  53677. _this.color = color;
  53678. _this.depth = depth;
  53679. _this.colorLevel = colorLevel;
  53680. _this.onActivateObservable.add(function (cam) {
  53681. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  53682. });
  53683. _this.onApplyObservable.add(function (effect) {
  53684. effect.setColor3("baseColor", _this.color);
  53685. effect.setFloat("depth", _this.depth);
  53686. effect.setFloat("colorLevel", _this.colorLevel);
  53687. effect.setTexture("refractionSampler", _this._refRexture);
  53688. });
  53689. return _this;
  53690. }
  53691. // Methods
  53692. RefractionPostProcess.prototype.dispose = function (camera) {
  53693. if (this._refRexture) {
  53694. this._refRexture.dispose();
  53695. }
  53696. _super.prototype.dispose.call(this, camera);
  53697. };
  53698. return RefractionPostProcess;
  53699. }(BABYLON.PostProcess));
  53700. BABYLON.RefractionPostProcess = RefractionPostProcess;
  53701. })(BABYLON || (BABYLON = {}));
  53702. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  53703. var BABYLON;
  53704. (function (BABYLON) {
  53705. var BlackAndWhitePostProcess = (function (_super) {
  53706. __extends(BlackAndWhitePostProcess, _super);
  53707. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  53708. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  53709. _this.degree = 1;
  53710. _this.onApplyObservable.add(function (effect) {
  53711. effect.setFloat("degree", _this.degree);
  53712. });
  53713. return _this;
  53714. }
  53715. return BlackAndWhitePostProcess;
  53716. }(BABYLON.PostProcess));
  53717. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  53718. })(BABYLON || (BABYLON = {}));
  53719. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  53720. var BABYLON;
  53721. (function (BABYLON) {
  53722. var ConvolutionPostProcess = (function (_super) {
  53723. __extends(ConvolutionPostProcess, _super);
  53724. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  53725. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  53726. _this.kernel = kernel;
  53727. _this.onApply = function (effect) {
  53728. effect.setFloat2("screenSize", _this.width, _this.height);
  53729. effect.setArray("kernel", _this.kernel);
  53730. };
  53731. return _this;
  53732. }
  53733. // Statics
  53734. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  53735. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  53736. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  53737. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  53738. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  53739. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  53740. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  53741. return ConvolutionPostProcess;
  53742. }(BABYLON.PostProcess));
  53743. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  53744. })(BABYLON || (BABYLON = {}));
  53745. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  53746. var BABYLON;
  53747. (function (BABYLON) {
  53748. var FilterPostProcess = (function (_super) {
  53749. __extends(FilterPostProcess, _super);
  53750. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  53751. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  53752. _this.kernelMatrix = kernelMatrix;
  53753. _this.onApply = function (effect) {
  53754. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  53755. };
  53756. return _this;
  53757. }
  53758. return FilterPostProcess;
  53759. }(BABYLON.PostProcess));
  53760. BABYLON.FilterPostProcess = FilterPostProcess;
  53761. })(BABYLON || (BABYLON = {}));
  53762. //# sourceMappingURL=babylon.filterPostProcess.js.map
  53763. var BABYLON;
  53764. (function (BABYLON) {
  53765. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53766. var VolumetricLightScatteringPostProcess = (function (_super) {
  53767. __extends(VolumetricLightScatteringPostProcess, _super);
  53768. /**
  53769. * @constructor
  53770. * @param {string} name - The post-process name
  53771. * @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)
  53772. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53773. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53774. * @param {number} samples - The post-process quality, default 100
  53775. * @param {number} samplingMode - The post-process filtering mode
  53776. * @param {BABYLON.Engine} engine - The babylon engine
  53777. * @param {boolean} reusable - If the post-process is reusable
  53778. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53779. */
  53780. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53781. if (samples === void 0) { samples = 100; }
  53782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53783. 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;
  53784. _this._screenCoordinates = BABYLON.Vector2.Zero();
  53785. /**
  53786. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53787. * @type {Vector3}
  53788. */
  53789. _this.customMeshPosition = BABYLON.Vector3.Zero();
  53790. /**
  53791. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53792. * @type {boolean}
  53793. */
  53794. _this.useCustomMeshPosition = false;
  53795. /**
  53796. * If the post-process should inverse the light scattering direction
  53797. * @type {boolean}
  53798. */
  53799. _this.invert = true;
  53800. /**
  53801. * Array containing the excluded meshes not rendered in the internal pass
  53802. */
  53803. _this.excludedMeshes = new Array();
  53804. /**
  53805. * Controls the overall intensity of the post-process
  53806. * @type {number}
  53807. */
  53808. _this.exposure = 0.3;
  53809. /**
  53810. * Dissipates each sample's contribution in range [0, 1]
  53811. * @type {number}
  53812. */
  53813. _this.decay = 0.96815;
  53814. /**
  53815. * Controls the overall intensity of each sample
  53816. * @type {number}
  53817. */
  53818. _this.weight = 0.58767;
  53819. /**
  53820. * Controls the density of each sample
  53821. * @type {number}
  53822. */
  53823. _this.density = 0.926;
  53824. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53825. var engine = scene.getEngine();
  53826. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53827. // Configure mesh
  53828. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53829. // Configure
  53830. _this._createPass(scene, ratio.passRatio || ratio);
  53831. _this.onActivate = function (camera) {
  53832. if (!_this.isSupported) {
  53833. _this.dispose(camera);
  53834. }
  53835. _this.onActivate = null;
  53836. };
  53837. _this.onApplyObservable.add(function (effect) {
  53838. _this._updateMeshScreenCoordinates(scene);
  53839. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53840. effect.setFloat("exposure", _this.exposure);
  53841. effect.setFloat("decay", _this.decay);
  53842. effect.setFloat("weight", _this.weight);
  53843. effect.setFloat("density", _this.density);
  53844. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53845. });
  53846. return _this;
  53847. }
  53848. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53849. get: function () {
  53850. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53851. return false;
  53852. },
  53853. set: function (useDiffuseColor) {
  53854. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53855. },
  53856. enumerable: true,
  53857. configurable: true
  53858. });
  53859. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  53860. return "VolumetricLightScatteringPostProcess";
  53861. };
  53862. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53863. var mesh = subMesh.getMesh();
  53864. // Render this.mesh as default
  53865. if (mesh === this.mesh) {
  53866. return mesh.material.isReady(mesh);
  53867. }
  53868. var defines = [];
  53869. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53870. var material = subMesh.getMaterial();
  53871. var needUV = false;
  53872. // Alpha test
  53873. if (material) {
  53874. if (material.needAlphaTesting()) {
  53875. defines.push("#define ALPHATEST");
  53876. }
  53877. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53878. attribs.push(BABYLON.VertexBuffer.UVKind);
  53879. defines.push("#define UV1");
  53880. }
  53881. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53882. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53883. defines.push("#define UV2");
  53884. }
  53885. }
  53886. // Bones
  53887. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53888. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53889. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53890. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53891. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53892. }
  53893. else {
  53894. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53895. }
  53896. // Instances
  53897. if (useInstances) {
  53898. defines.push("#define INSTANCES");
  53899. attribs.push("world0");
  53900. attribs.push("world1");
  53901. attribs.push("world2");
  53902. attribs.push("world3");
  53903. }
  53904. // Get correct effect
  53905. var join = defines.join("\n");
  53906. if (this._cachedDefines !== join) {
  53907. this._cachedDefines = join;
  53908. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53909. }
  53910. return this._volumetricLightScatteringPass.isReady();
  53911. };
  53912. /**
  53913. * Sets the new light position for light scattering effect
  53914. * @param {BABYLON.Vector3} The new custom light position
  53915. */
  53916. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53917. this.customMeshPosition = position;
  53918. };
  53919. /**
  53920. * Returns the light position for light scattering effect
  53921. * @return {BABYLON.Vector3} The custom light position
  53922. */
  53923. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53924. return this.customMeshPosition;
  53925. };
  53926. /**
  53927. * Disposes the internal assets and detaches the post-process from the camera
  53928. */
  53929. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53930. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53931. if (rttIndex !== -1) {
  53932. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53933. }
  53934. this._volumetricLightScatteringRTT.dispose();
  53935. _super.prototype.dispose.call(this, camera);
  53936. };
  53937. /**
  53938. * Returns the render target texture used by the post-process
  53939. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53940. */
  53941. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53942. return this._volumetricLightScatteringRTT;
  53943. };
  53944. // Private methods
  53945. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53946. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53947. return true;
  53948. }
  53949. return false;
  53950. };
  53951. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53952. var _this = this;
  53953. var engine = scene.getEngine();
  53954. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53955. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53956. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53957. this._volumetricLightScatteringRTT.renderList = null;
  53958. this._volumetricLightScatteringRTT.renderParticles = false;
  53959. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53960. // Custom render function for submeshes
  53961. var renderSubMesh = function (subMesh) {
  53962. var mesh = subMesh.getRenderingMesh();
  53963. if (_this._meshExcluded(mesh)) {
  53964. return;
  53965. }
  53966. var scene = mesh.getScene();
  53967. var engine = scene.getEngine();
  53968. // Culling
  53969. engine.setState(subMesh.getMaterial().backFaceCulling);
  53970. // Managing instances
  53971. var batch = mesh._getInstancesRenderList(subMesh._id);
  53972. if (batch.mustReturn) {
  53973. return;
  53974. }
  53975. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53976. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53977. var effect = _this._volumetricLightScatteringPass;
  53978. if (mesh === _this.mesh) {
  53979. if (subMesh.effect) {
  53980. effect = subMesh.effect;
  53981. }
  53982. else {
  53983. effect = subMesh.getMaterial().getEffect();
  53984. }
  53985. }
  53986. engine.enableEffect(effect);
  53987. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53988. if (mesh === _this.mesh) {
  53989. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53990. }
  53991. else {
  53992. var material = subMesh.getMaterial();
  53993. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53994. // Alpha test
  53995. if (material && material.needAlphaTesting()) {
  53996. var alphaTexture = material.getAlphaTestTexture();
  53997. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53998. if (alphaTexture) {
  53999. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54000. }
  54001. }
  54002. // Bones
  54003. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54004. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54005. }
  54006. }
  54007. // Draw
  54008. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  54009. }
  54010. };
  54011. // Render target texture callbacks
  54012. var savedSceneClearColor;
  54013. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  54014. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  54015. savedSceneClearColor = scene.clearColor;
  54016. scene.clearColor = sceneClearColor;
  54017. });
  54018. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  54019. scene.clearColor = savedSceneClearColor;
  54020. });
  54021. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  54022. var engine = scene.getEngine();
  54023. var index;
  54024. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54025. renderSubMesh(opaqueSubMeshes.data[index]);
  54026. }
  54027. engine.setAlphaTesting(true);
  54028. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54029. renderSubMesh(alphaTestSubMeshes.data[index]);
  54030. }
  54031. engine.setAlphaTesting(false);
  54032. if (transparentSubMeshes.length) {
  54033. // Sort sub meshes
  54034. for (index = 0; index < transparentSubMeshes.length; index++) {
  54035. var submesh = transparentSubMeshes.data[index];
  54036. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  54037. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  54038. }
  54039. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  54040. sortedArray.sort(function (a, b) {
  54041. // Alpha index first
  54042. if (a._alphaIndex > b._alphaIndex) {
  54043. return 1;
  54044. }
  54045. if (a._alphaIndex < b._alphaIndex) {
  54046. return -1;
  54047. }
  54048. // Then distance to camera
  54049. if (a._distanceToCamera < b._distanceToCamera) {
  54050. return 1;
  54051. }
  54052. if (a._distanceToCamera > b._distanceToCamera) {
  54053. return -1;
  54054. }
  54055. return 0;
  54056. });
  54057. // Render sub meshes
  54058. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54059. for (index = 0; index < sortedArray.length; index++) {
  54060. renderSubMesh(sortedArray[index]);
  54061. }
  54062. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54063. }
  54064. };
  54065. };
  54066. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  54067. var transform = scene.getTransformMatrix();
  54068. var meshPosition;
  54069. if (this.useCustomMeshPosition) {
  54070. meshPosition = this.customMeshPosition;
  54071. }
  54072. else if (this.attachedNode) {
  54073. meshPosition = this.attachedNode.position;
  54074. }
  54075. else {
  54076. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  54077. }
  54078. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  54079. this._screenCoordinates.x = pos.x / this._viewPort.width;
  54080. this._screenCoordinates.y = pos.y / this._viewPort.height;
  54081. if (this.invert)
  54082. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  54083. };
  54084. // Static methods
  54085. /**
  54086. * Creates a default mesh for the Volumeric Light Scattering post-process
  54087. * @param {string} The mesh name
  54088. * @param {BABYLON.Scene} The scene where to create the mesh
  54089. * @return {BABYLON.Mesh} the default mesh
  54090. */
  54091. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  54092. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  54093. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54094. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  54095. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  54096. mesh.material = material;
  54097. return mesh;
  54098. };
  54099. __decorate([
  54100. BABYLON.serializeAsVector3()
  54101. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  54102. __decorate([
  54103. BABYLON.serialize()
  54104. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  54105. __decorate([
  54106. BABYLON.serialize()
  54107. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  54108. __decorate([
  54109. BABYLON.serializeAsMeshReference()
  54110. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  54111. __decorate([
  54112. BABYLON.serialize()
  54113. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  54114. __decorate([
  54115. BABYLON.serialize()
  54116. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  54117. __decorate([
  54118. BABYLON.serialize()
  54119. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  54120. __decorate([
  54121. BABYLON.serialize()
  54122. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  54123. __decorate([
  54124. BABYLON.serialize()
  54125. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  54126. return VolumetricLightScatteringPostProcess;
  54127. }(BABYLON.PostProcess));
  54128. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  54129. })(BABYLON || (BABYLON = {}));
  54130. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  54131. //
  54132. // This post-process allows the modification of rendered colors by using
  54133. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54134. //
  54135. // The object needs to be provided an url to a texture containing the color
  54136. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54137. // Use an image editing software to tweak the LUT to match your needs.
  54138. //
  54139. // For an example of a color LUT, see here:
  54140. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54141. // For explanations on color grading, see here:
  54142. // http://udn.epicgames.com/Three/ColorGrading.html
  54143. //
  54144. var BABYLON;
  54145. (function (BABYLON) {
  54146. var ColorCorrectionPostProcess = (function (_super) {
  54147. __extends(ColorCorrectionPostProcess, _super);
  54148. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54149. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  54150. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54151. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  54152. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54153. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54154. _this.onApply = function (effect) {
  54155. effect.setTexture("colorTable", _this._colorTableTexture);
  54156. };
  54157. return _this;
  54158. }
  54159. return ColorCorrectionPostProcess;
  54160. }(BABYLON.PostProcess));
  54161. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54162. })(BABYLON || (BABYLON = {}));
  54163. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  54164. var BABYLON;
  54165. (function (BABYLON) {
  54166. var TonemappingOperator;
  54167. (function (TonemappingOperator) {
  54168. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  54169. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  54170. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  54171. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  54172. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  54173. ;
  54174. var TonemapPostProcess = (function (_super) {
  54175. __extends(TonemapPostProcess, _super);
  54176. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  54177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54178. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54179. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  54180. _this._operator = _operator;
  54181. _this.exposureAdjustment = exposureAdjustment;
  54182. var defines = "#define ";
  54183. if (_this._operator === TonemappingOperator.Hable)
  54184. defines += "HABLE_TONEMAPPING";
  54185. else if (_this._operator === TonemappingOperator.Reinhard)
  54186. defines += "REINHARD_TONEMAPPING";
  54187. else if (_this._operator === TonemappingOperator.HejiDawson)
  54188. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  54189. else if (_this._operator === TonemappingOperator.Photographic)
  54190. defines += "PHOTOGRAPHIC_TONEMAPPING";
  54191. //sadly a second call to create the effect.
  54192. _this.updateEffect(defines);
  54193. _this.onApply = function (effect) {
  54194. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  54195. };
  54196. return _this;
  54197. }
  54198. return TonemapPostProcess;
  54199. }(BABYLON.PostProcess));
  54200. BABYLON.TonemapPostProcess = TonemapPostProcess;
  54201. })(BABYLON || (BABYLON = {}));
  54202. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  54203. var BABYLON;
  54204. (function (BABYLON) {
  54205. var DisplayPassPostProcess = (function (_super) {
  54206. __extends(DisplayPassPostProcess, _super);
  54207. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  54208. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  54209. }
  54210. return DisplayPassPostProcess;
  54211. }(BABYLON.PostProcess));
  54212. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  54213. })(BABYLON || (BABYLON = {}));
  54214. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  54215. var BABYLON;
  54216. (function (BABYLON) {
  54217. var HighlightsPostProcess = (function (_super) {
  54218. __extends(HighlightsPostProcess, _super);
  54219. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54220. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54221. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  54222. }
  54223. return HighlightsPostProcess;
  54224. }(BABYLON.PostProcess));
  54225. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  54226. })(BABYLON || (BABYLON = {}));
  54227. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  54228. var BABYLON;
  54229. (function (BABYLON) {
  54230. var ImageProcessingPostProcess = (function (_super) {
  54231. __extends(ImageProcessingPostProcess, _super);
  54232. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54233. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54234. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  54235. _this._fromLinearSpace = true;
  54236. /**
  54237. * Defines cache preventing GC.
  54238. */
  54239. _this._defines = {
  54240. IMAGEPROCESSING: false,
  54241. VIGNETTE: false,
  54242. VIGNETTEBLENDMODEMULTIPLY: false,
  54243. VIGNETTEBLENDMODEOPAQUE: false,
  54244. TONEMAPPING: false,
  54245. CONTRAST: false,
  54246. COLORCURVES: false,
  54247. COLORGRADING: false,
  54248. FROMLINEARSPACE: false,
  54249. SAMPLER3DGREENDEPTH: false,
  54250. SAMPLER3DBGRMAP: false,
  54251. IMAGEPROCESSINGPOSTPROCESS: false,
  54252. EXPOSURE: false,
  54253. };
  54254. // Setup the default processing configuration to the scene.
  54255. _this._attachImageProcessingConfiguration(null, true);
  54256. _this.imageProcessingConfiguration.applyByPostProcess = true;
  54257. _this.onApply = function (effect) {
  54258. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  54259. };
  54260. return _this;
  54261. }
  54262. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  54263. /**
  54264. * Gets the image processing configuration used either in this material.
  54265. */
  54266. get: function () {
  54267. return this._imageProcessingConfiguration;
  54268. },
  54269. /**
  54270. * Sets the Default image processing configuration used either in the this material.
  54271. *
  54272. * If sets to null, the scene one is in use.
  54273. */
  54274. set: function (value) {
  54275. this._attachImageProcessingConfiguration(value);
  54276. },
  54277. enumerable: true,
  54278. configurable: true
  54279. });
  54280. /**
  54281. * Attaches a new image processing configuration to the PBR Material.
  54282. * @param configuration
  54283. */
  54284. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  54285. var _this = this;
  54286. if (doNotBuild === void 0) { doNotBuild = false; }
  54287. if (configuration === this._imageProcessingConfiguration) {
  54288. return;
  54289. }
  54290. // Detaches observer.
  54291. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  54292. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  54293. }
  54294. // Pick the scene configuration if needed.
  54295. if (!configuration) {
  54296. var camera = this.getCamera();
  54297. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  54298. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  54299. }
  54300. else {
  54301. this._imageProcessingConfiguration = configuration;
  54302. }
  54303. // Attaches observer.
  54304. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  54305. _this._updateParameters();
  54306. });
  54307. // Ensure the effect will be rebuilt.
  54308. if (!doNotBuild) {
  54309. this._updateParameters();
  54310. }
  54311. };
  54312. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  54313. /**
  54314. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54315. */
  54316. get: function () {
  54317. return this.imageProcessingConfiguration.colorCurves;
  54318. },
  54319. /**
  54320. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54321. */
  54322. set: function (value) {
  54323. this.imageProcessingConfiguration.colorCurves = value;
  54324. },
  54325. enumerable: true,
  54326. configurable: true
  54327. });
  54328. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  54329. /**
  54330. * Gets wether the color curves effect is enabled.
  54331. */
  54332. get: function () {
  54333. return this.imageProcessingConfiguration.colorCurvesEnabled;
  54334. },
  54335. /**
  54336. * Sets wether the color curves effect is enabled.
  54337. */
  54338. set: function (value) {
  54339. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  54340. },
  54341. enumerable: true,
  54342. configurable: true
  54343. });
  54344. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  54345. /**
  54346. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  54347. */
  54348. get: function () {
  54349. return this.imageProcessingConfiguration.colorGradingTexture;
  54350. },
  54351. /**
  54352. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  54353. */
  54354. set: function (value) {
  54355. this.imageProcessingConfiguration.colorGradingTexture = value;
  54356. },
  54357. enumerable: true,
  54358. configurable: true
  54359. });
  54360. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  54361. /**
  54362. * Gets wether the color grading effect is enabled.
  54363. */
  54364. get: function () {
  54365. return this.imageProcessingConfiguration.colorGradingEnabled;
  54366. },
  54367. /**
  54368. * Gets wether the color grading effect is enabled.
  54369. */
  54370. set: function (value) {
  54371. this.imageProcessingConfiguration.colorGradingEnabled = value;
  54372. },
  54373. enumerable: true,
  54374. configurable: true
  54375. });
  54376. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  54377. /**
  54378. * Gets exposure used in the effect.
  54379. */
  54380. get: function () {
  54381. return this.imageProcessingConfiguration.exposure;
  54382. },
  54383. /**
  54384. * Sets exposure used in the effect.
  54385. */
  54386. set: function (value) {
  54387. this.imageProcessingConfiguration.exposure = value;
  54388. },
  54389. enumerable: true,
  54390. configurable: true
  54391. });
  54392. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  54393. /**
  54394. * Gets wether tonemapping is enabled or not.
  54395. */
  54396. get: function () {
  54397. return this._imageProcessingConfiguration.toneMappingEnabled;
  54398. },
  54399. /**
  54400. * Sets wether tonemapping is enabled or not
  54401. */
  54402. set: function (value) {
  54403. this._imageProcessingConfiguration.toneMappingEnabled = value;
  54404. },
  54405. enumerable: true,
  54406. configurable: true
  54407. });
  54408. ;
  54409. ;
  54410. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  54411. /**
  54412. * Gets contrast used in the effect.
  54413. */
  54414. get: function () {
  54415. return this.imageProcessingConfiguration.contrast;
  54416. },
  54417. /**
  54418. * Sets contrast used in the effect.
  54419. */
  54420. set: function (value) {
  54421. this.imageProcessingConfiguration.contrast = value;
  54422. },
  54423. enumerable: true,
  54424. configurable: true
  54425. });
  54426. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  54427. /**
  54428. * Gets Vignette stretch size.
  54429. */
  54430. get: function () {
  54431. return this.imageProcessingConfiguration.vignetteStretch;
  54432. },
  54433. /**
  54434. * Sets Vignette stretch size.
  54435. */
  54436. set: function (value) {
  54437. this.imageProcessingConfiguration.vignetteStretch = value;
  54438. },
  54439. enumerable: true,
  54440. configurable: true
  54441. });
  54442. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  54443. /**
  54444. * Gets Vignette centre X Offset.
  54445. */
  54446. get: function () {
  54447. return this.imageProcessingConfiguration.vignetteCentreX;
  54448. },
  54449. /**
  54450. * Sets Vignette centre X Offset.
  54451. */
  54452. set: function (value) {
  54453. this.imageProcessingConfiguration.vignetteCentreX = value;
  54454. },
  54455. enumerable: true,
  54456. configurable: true
  54457. });
  54458. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  54459. /**
  54460. * Gets Vignette centre Y Offset.
  54461. */
  54462. get: function () {
  54463. return this.imageProcessingConfiguration.vignetteCentreY;
  54464. },
  54465. /**
  54466. * Sets Vignette centre Y Offset.
  54467. */
  54468. set: function (value) {
  54469. this.imageProcessingConfiguration.vignetteCentreY = value;
  54470. },
  54471. enumerable: true,
  54472. configurable: true
  54473. });
  54474. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  54475. /**
  54476. * Gets Vignette weight or intensity of the vignette effect.
  54477. */
  54478. get: function () {
  54479. return this.imageProcessingConfiguration.vignetteWeight;
  54480. },
  54481. /**
  54482. * Sets Vignette weight or intensity of the vignette effect.
  54483. */
  54484. set: function (value) {
  54485. this.imageProcessingConfiguration.vignetteWeight = value;
  54486. },
  54487. enumerable: true,
  54488. configurable: true
  54489. });
  54490. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  54491. /**
  54492. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54493. * if vignetteEnabled is set to true.
  54494. */
  54495. get: function () {
  54496. return this.imageProcessingConfiguration.vignetteColor;
  54497. },
  54498. /**
  54499. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54500. * if vignetteEnabled is set to true.
  54501. */
  54502. set: function (value) {
  54503. this.imageProcessingConfiguration.vignetteColor = value;
  54504. },
  54505. enumerable: true,
  54506. configurable: true
  54507. });
  54508. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  54509. /**
  54510. * Gets Camera field of view used by the Vignette effect.
  54511. */
  54512. get: function () {
  54513. return this.imageProcessingConfiguration.vignetteCameraFov;
  54514. },
  54515. /**
  54516. * Sets Camera field of view used by the Vignette effect.
  54517. */
  54518. set: function (value) {
  54519. this.imageProcessingConfiguration.vignetteCameraFov = value;
  54520. },
  54521. enumerable: true,
  54522. configurable: true
  54523. });
  54524. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  54525. /**
  54526. * Gets the vignette blend mode allowing different kind of effect.
  54527. */
  54528. get: function () {
  54529. return this.imageProcessingConfiguration.vignetteBlendMode;
  54530. },
  54531. /**
  54532. * Sets the vignette blend mode allowing different kind of effect.
  54533. */
  54534. set: function (value) {
  54535. this.imageProcessingConfiguration.vignetteBlendMode = value;
  54536. },
  54537. enumerable: true,
  54538. configurable: true
  54539. });
  54540. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  54541. /**
  54542. * Gets wether the vignette effect is enabled.
  54543. */
  54544. get: function () {
  54545. return this.imageProcessingConfiguration.vignetteEnabled;
  54546. },
  54547. /**
  54548. * Sets wether the vignette effect is enabled.
  54549. */
  54550. set: function (value) {
  54551. this.imageProcessingConfiguration.vignetteEnabled = value;
  54552. },
  54553. enumerable: true,
  54554. configurable: true
  54555. });
  54556. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  54557. /**
  54558. * Gets wether the input of the processing is in Gamma or Linear Space.
  54559. */
  54560. get: function () {
  54561. return this._fromLinearSpace;
  54562. },
  54563. /**
  54564. * Sets wether the input of the processing is in Gamma or Linear Space.
  54565. */
  54566. set: function (value) {
  54567. if (this._fromLinearSpace === value) {
  54568. return;
  54569. }
  54570. this._fromLinearSpace = value;
  54571. this._updateParameters();
  54572. },
  54573. enumerable: true,
  54574. configurable: true
  54575. });
  54576. ImageProcessingPostProcess.prototype.getClassName = function () {
  54577. return "ImageProcessingPostProcess";
  54578. };
  54579. ImageProcessingPostProcess.prototype._updateParameters = function () {
  54580. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  54581. this.imageProcessingConfiguration.prepareDefines(this._defines);
  54582. var defines = "";
  54583. for (var define in this._defines) {
  54584. if (this._defines[define]) {
  54585. defines += "#define " + define + ";\r\n";
  54586. }
  54587. }
  54588. var samplers = ["textureSampler"];
  54589. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  54590. var uniforms = ["scale"];
  54591. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  54592. this.updateEffect(defines, uniforms, samplers);
  54593. };
  54594. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  54595. _super.prototype.dispose.call(this, camera);
  54596. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  54597. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  54598. }
  54599. this.imageProcessingConfiguration.applyByPostProcess = false;
  54600. };
  54601. __decorate([
  54602. BABYLON.serialize()
  54603. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  54604. return ImageProcessingPostProcess;
  54605. }(BABYLON.PostProcess));
  54606. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  54607. })(BABYLON || (BABYLON = {}));
  54608. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  54609. var BABYLON;
  54610. (function (BABYLON) {
  54611. var BlurPostProcess = (function (_super) {
  54612. __extends(BlurPostProcess, _super);
  54613. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  54614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54615. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54616. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  54617. _this.direction = direction;
  54618. _this._packedFloat = false;
  54619. _this.onApplyObservable.add(function (effect) {
  54620. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  54621. });
  54622. _this.kernel = kernel;
  54623. return _this;
  54624. }
  54625. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  54626. /**
  54627. * Gets the length in pixels of the blur sample region
  54628. */
  54629. get: function () {
  54630. return this._idealKernel;
  54631. },
  54632. /**
  54633. * Sets the length in pixels of the blur sample region
  54634. */
  54635. set: function (v) {
  54636. if (this._idealKernel === v) {
  54637. return;
  54638. }
  54639. v = Math.max(v, 1);
  54640. this._idealKernel = v;
  54641. this._kernel = this._nearestBestKernel(v);
  54642. this._updateParameters();
  54643. },
  54644. enumerable: true,
  54645. configurable: true
  54646. });
  54647. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  54648. /**
  54649. * Gets wether or not the blur is unpacking/repacking floats
  54650. */
  54651. get: function () {
  54652. return this._packedFloat;
  54653. },
  54654. /**
  54655. * Sets wether or not the blur needs to unpack/repack floats
  54656. */
  54657. set: function (v) {
  54658. if (this._packedFloat === v) {
  54659. return;
  54660. }
  54661. this._packedFloat = v;
  54662. this._updateParameters();
  54663. },
  54664. enumerable: true,
  54665. configurable: true
  54666. });
  54667. BlurPostProcess.prototype._updateParameters = function () {
  54668. // Generate sampling offsets and weights
  54669. var N = this._kernel;
  54670. var centerIndex = (N - 1) / 2;
  54671. // Generate Gaussian sampling weights over kernel
  54672. var offsets = [];
  54673. var weights = [];
  54674. var totalWeight = 0;
  54675. for (var i = 0; i < N; i++) {
  54676. var u = i / (N - 1);
  54677. var w = this._gaussianWeight(u * 2.0 - 1);
  54678. offsets[i] = (i - centerIndex);
  54679. weights[i] = w;
  54680. totalWeight += w;
  54681. }
  54682. // Normalize weights
  54683. for (var i = 0; i < weights.length; i++) {
  54684. weights[i] /= totalWeight;
  54685. }
  54686. // Optimize: combine samples to take advantage of hardware linear sampling
  54687. // Walk from left to center, combining pairs (symmetrically)
  54688. var linearSamplingWeights = [];
  54689. var linearSamplingOffsets = [];
  54690. var linearSamplingMap = [];
  54691. for (var i = 0; i <= centerIndex; i += 2) {
  54692. var j = Math.min(i + 1, Math.floor(centerIndex));
  54693. var singleCenterSample = i === j;
  54694. if (singleCenterSample) {
  54695. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  54696. }
  54697. else {
  54698. var sharedCell = j === centerIndex;
  54699. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  54700. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  54701. if (offsetLinear === 0) {
  54702. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  54703. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  54704. }
  54705. else {
  54706. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  54707. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  54708. }
  54709. }
  54710. }
  54711. for (var i = 0; i < linearSamplingMap.length; i++) {
  54712. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  54713. linearSamplingWeights[i] = linearSamplingMap[i].w;
  54714. }
  54715. // Replace with optimized
  54716. offsets = linearSamplingOffsets;
  54717. weights = linearSamplingWeights;
  54718. // Generate shaders
  54719. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  54720. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  54721. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  54722. var defines = "";
  54723. for (var i = 0; i < varyingCount; i++) {
  54724. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  54725. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  54726. }
  54727. var depCount = 0;
  54728. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  54729. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  54730. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  54731. depCount++;
  54732. }
  54733. if (this.packedFloat) {
  54734. defines += "#define PACKEDFLOAT 1";
  54735. }
  54736. this.updateEffect(defines, null, null, {
  54737. varyingCount: varyingCount,
  54738. depCount: depCount
  54739. });
  54740. };
  54741. /**
  54742. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  54743. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  54744. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  54745. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  54746. * The gaps between physical kernels are compensated for in the weighting of the samples
  54747. * @param idealKernel Ideal blur kernel.
  54748. * @return Nearest best kernel.
  54749. */
  54750. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  54751. var v = Math.round(idealKernel);
  54752. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  54753. var k = _a[_i];
  54754. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  54755. return Math.max(k, 3);
  54756. }
  54757. }
  54758. return Math.max(v, 3);
  54759. };
  54760. /**
  54761. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  54762. * @param x The point on the Gaussian distribution to sample.
  54763. * @return the value of the Gaussian function at x.
  54764. */
  54765. BlurPostProcess.prototype._gaussianWeight = function (x) {
  54766. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  54767. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  54768. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  54769. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  54770. // truncated at around 1.3% of peak strength.
  54771. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  54772. var sigma = (1 / 3);
  54773. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  54774. var exponent = -((x * x) / (2.0 * sigma * sigma));
  54775. var weight = (1.0 / denominator) * Math.exp(exponent);
  54776. return weight;
  54777. };
  54778. /**
  54779. * Generates a string that can be used as a floating point number in GLSL.
  54780. * @param x Value to print.
  54781. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  54782. * @return GLSL float string.
  54783. */
  54784. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  54785. if (decimalFigures === void 0) { decimalFigures = 8; }
  54786. return x.toFixed(decimalFigures).replace(/0+$/, '');
  54787. };
  54788. return BlurPostProcess;
  54789. }(BABYLON.PostProcess));
  54790. BABYLON.BlurPostProcess = BlurPostProcess;
  54791. })(BABYLON || (BABYLON = {}));
  54792. //# sourceMappingURL=babylon.blurPostProcess.js.map
  54793. /// <reference path="..\babylon.node.ts" />
  54794. var BABYLON;
  54795. (function (BABYLON) {
  54796. var Bone = (function (_super) {
  54797. __extends(Bone, _super);
  54798. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  54799. if (parentBone === void 0) { parentBone = null; }
  54800. var _this = _super.call(this, name, skeleton.getScene()) || this;
  54801. _this.name = name;
  54802. _this.children = new Array();
  54803. _this.animations = new Array();
  54804. _this._worldTransform = new BABYLON.Matrix();
  54805. _this._absoluteTransform = new BABYLON.Matrix();
  54806. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  54807. _this._scaleMatrix = BABYLON.Matrix.Identity();
  54808. _this._scaleVector = BABYLON.Vector3.One();
  54809. _this._negateScaleChildren = BABYLON.Vector3.One();
  54810. _this._scalingDeterminant = 1;
  54811. _this._skeleton = skeleton;
  54812. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  54813. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  54814. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  54815. _this._index = index;
  54816. skeleton.bones.push(_this);
  54817. _this.setParent(parentBone, false);
  54818. _this._updateDifferenceMatrix();
  54819. return _this;
  54820. }
  54821. Object.defineProperty(Bone.prototype, "_matrix", {
  54822. get: function () {
  54823. return this._localMatrix;
  54824. },
  54825. set: function (val) {
  54826. if (this._localMatrix) {
  54827. this._localMatrix.copyFrom(val);
  54828. }
  54829. else {
  54830. this._localMatrix = val;
  54831. }
  54832. },
  54833. enumerable: true,
  54834. configurable: true
  54835. });
  54836. // Members
  54837. Bone.prototype.getSkeleton = function () {
  54838. return this._skeleton;
  54839. };
  54840. Bone.prototype.getParent = function () {
  54841. return this._parent;
  54842. };
  54843. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  54844. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  54845. if (this._parent === parent) {
  54846. return;
  54847. }
  54848. if (this._parent) {
  54849. var index = this._parent.children.indexOf(this);
  54850. if (index !== -1) {
  54851. this._parent.children.splice(index);
  54852. }
  54853. }
  54854. this._parent = parent;
  54855. if (this._parent) {
  54856. this._parent.children.push(this);
  54857. }
  54858. if (updateDifferenceMatrix) {
  54859. this._updateDifferenceMatrix();
  54860. }
  54861. };
  54862. Bone.prototype.getLocalMatrix = function () {
  54863. return this._localMatrix;
  54864. };
  54865. Bone.prototype.getBaseMatrix = function () {
  54866. return this._baseMatrix;
  54867. };
  54868. Bone.prototype.getRestPose = function () {
  54869. return this._restPose;
  54870. };
  54871. Bone.prototype.returnToRest = function () {
  54872. this.updateMatrix(this._restPose.clone());
  54873. };
  54874. Bone.prototype.getWorldMatrix = function () {
  54875. return this._worldTransform;
  54876. };
  54877. Bone.prototype.getInvertedAbsoluteTransform = function () {
  54878. return this._invertedAbsoluteTransform;
  54879. };
  54880. Bone.prototype.getAbsoluteTransform = function () {
  54881. return this._absoluteTransform;
  54882. };
  54883. Object.defineProperty(Bone.prototype, "position", {
  54884. // Properties (matches AbstractMesh properties)
  54885. get: function () {
  54886. return this.getPosition();
  54887. },
  54888. set: function (newPosition) {
  54889. this.setPosition(newPosition);
  54890. },
  54891. enumerable: true,
  54892. configurable: true
  54893. });
  54894. Object.defineProperty(Bone.prototype, "rotation", {
  54895. get: function () {
  54896. return this.getRotation();
  54897. },
  54898. set: function (newRotation) {
  54899. this.setRotation(newRotation);
  54900. },
  54901. enumerable: true,
  54902. configurable: true
  54903. });
  54904. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  54905. get: function () {
  54906. return this.getRotationQuaternion();
  54907. },
  54908. set: function (newRotation) {
  54909. this.setRotationQuaternion(newRotation);
  54910. },
  54911. enumerable: true,
  54912. configurable: true
  54913. });
  54914. Object.defineProperty(Bone.prototype, "scaling", {
  54915. get: function () {
  54916. return this.getScale();
  54917. },
  54918. set: function (newScaling) {
  54919. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  54920. },
  54921. enumerable: true,
  54922. configurable: true
  54923. });
  54924. // Methods
  54925. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  54926. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  54927. this._baseMatrix = matrix.clone();
  54928. this._localMatrix = matrix.clone();
  54929. this._skeleton._markAsDirty();
  54930. if (updateDifferenceMatrix) {
  54931. this._updateDifferenceMatrix();
  54932. }
  54933. };
  54934. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  54935. if (!rootMatrix) {
  54936. rootMatrix = this._baseMatrix;
  54937. }
  54938. if (this._parent) {
  54939. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  54940. }
  54941. else {
  54942. this._absoluteTransform.copyFrom(rootMatrix);
  54943. }
  54944. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  54945. for (var index = 0; index < this.children.length; index++) {
  54946. this.children[index]._updateDifferenceMatrix();
  54947. }
  54948. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  54949. };
  54950. Bone.prototype.markAsDirty = function () {
  54951. this._currentRenderId++;
  54952. this._skeleton._markAsDirty();
  54953. };
  54954. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  54955. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  54956. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  54957. // all animation may be coming from a library skeleton, so may need to create animation
  54958. if (this.animations.length === 0) {
  54959. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  54960. this.animations[0].setKeys([]);
  54961. }
  54962. // get animation info / verify there is such a range from the source bone
  54963. var sourceRange = source.animations[0].getRange(rangeName);
  54964. if (!sourceRange) {
  54965. return false;
  54966. }
  54967. var from = sourceRange.from;
  54968. var to = sourceRange.to;
  54969. var sourceKeys = source.animations[0].getKeys();
  54970. // rescaling prep
  54971. var sourceBoneLength = source.length;
  54972. var sourceParent = source.getParent();
  54973. var parent = this.getParent();
  54974. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  54975. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  54976. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  54977. var destKeys = this.animations[0].getKeys();
  54978. // loop vars declaration
  54979. var orig;
  54980. var origTranslation;
  54981. var mat;
  54982. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  54983. orig = sourceKeys[key];
  54984. if (orig.frame >= from && orig.frame <= to) {
  54985. if (rescaleAsRequired) {
  54986. mat = orig.value.clone();
  54987. // scale based on parent ratio, when bone has parent
  54988. if (parentScalingReqd) {
  54989. origTranslation = mat.getTranslation();
  54990. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  54991. // scale based on skeleton dimension ratio when root bone, and value is passed
  54992. }
  54993. else if (dimensionsScalingReqd) {
  54994. origTranslation = mat.getTranslation();
  54995. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  54996. // use original when root bone, and no data for skelDimensionsRatio
  54997. }
  54998. else {
  54999. mat = orig.value;
  55000. }
  55001. }
  55002. else {
  55003. mat = orig.value;
  55004. }
  55005. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  55006. }
  55007. }
  55008. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  55009. return true;
  55010. };
  55011. /**
  55012. * Translate the bone in local or world space.
  55013. * @param vec The amount to translate the bone.
  55014. * @param space The space that the translation is in.
  55015. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55016. */
  55017. Bone.prototype.translate = function (vec, space, mesh) {
  55018. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55019. var lm = this.getLocalMatrix();
  55020. if (space == BABYLON.Space.LOCAL) {
  55021. lm.m[12] += vec.x;
  55022. lm.m[13] += vec.y;
  55023. lm.m[14] += vec.z;
  55024. }
  55025. else {
  55026. var wm;
  55027. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55028. if (mesh) {
  55029. wm = mesh.getWorldMatrix();
  55030. }
  55031. this._skeleton.computeAbsoluteTransforms();
  55032. var tmat = Bone._tmpMats[0];
  55033. var tvec = Bone._tmpVecs[0];
  55034. if (mesh) {
  55035. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55036. tmat.multiplyToRef(wm, tmat);
  55037. }
  55038. else {
  55039. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55040. }
  55041. tmat.m[12] = 0;
  55042. tmat.m[13] = 0;
  55043. tmat.m[14] = 0;
  55044. tmat.invert();
  55045. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  55046. lm.m[12] += tvec.x;
  55047. lm.m[13] += tvec.y;
  55048. lm.m[14] += tvec.z;
  55049. }
  55050. this.markAsDirty();
  55051. };
  55052. /**
  55053. * Set the postion of the bone in local or world space.
  55054. * @param position The position to set the bone.
  55055. * @param space The space that the position is in.
  55056. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55057. */
  55058. Bone.prototype.setPosition = function (position, space, mesh) {
  55059. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55060. var lm = this.getLocalMatrix();
  55061. if (space == BABYLON.Space.LOCAL) {
  55062. lm.m[12] = position.x;
  55063. lm.m[13] = position.y;
  55064. lm.m[14] = position.z;
  55065. }
  55066. else {
  55067. var wm;
  55068. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55069. if (mesh) {
  55070. wm = mesh.getWorldMatrix();
  55071. }
  55072. this._skeleton.computeAbsoluteTransforms();
  55073. var tmat = Bone._tmpMats[0];
  55074. var vec = Bone._tmpVecs[0];
  55075. if (mesh) {
  55076. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55077. tmat.multiplyToRef(wm, tmat);
  55078. }
  55079. else {
  55080. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55081. }
  55082. tmat.invert();
  55083. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  55084. lm.m[12] = vec.x;
  55085. lm.m[13] = vec.y;
  55086. lm.m[14] = vec.z;
  55087. }
  55088. this.markAsDirty();
  55089. };
  55090. /**
  55091. * Set the absolute postion of the bone (world space).
  55092. * @param position The position to set the bone.
  55093. * @param mesh The mesh that this bone is attached to.
  55094. */
  55095. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  55096. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  55097. };
  55098. /**
  55099. * Set the scale of the bone on the x, y and z axes.
  55100. * @param x The scale of the bone on the x axis.
  55101. * @param x The scale of the bone on the y axis.
  55102. * @param z The scale of the bone on the z axis.
  55103. * @param scaleChildren Set this to true if children of the bone should be scaled.
  55104. */
  55105. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  55106. if (scaleChildren === void 0) { scaleChildren = false; }
  55107. if (this.animations[0] && !this.animations[0].isStopped()) {
  55108. if (!scaleChildren) {
  55109. this._negateScaleChildren.x = 1 / x;
  55110. this._negateScaleChildren.y = 1 / y;
  55111. this._negateScaleChildren.z = 1 / z;
  55112. }
  55113. this._syncScaleVector();
  55114. }
  55115. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  55116. };
  55117. /**
  55118. * Scale the bone on the x, y and z axes.
  55119. * @param x The amount to scale the bone on the x axis.
  55120. * @param x The amount to scale the bone on the y axis.
  55121. * @param z The amount to scale the bone on the z axis.
  55122. * @param scaleChildren Set this to true if children of the bone should be scaled.
  55123. */
  55124. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  55125. if (scaleChildren === void 0) { scaleChildren = false; }
  55126. var locMat = this.getLocalMatrix();
  55127. var origLocMat = Bone._tmpMats[0];
  55128. origLocMat.copyFrom(locMat);
  55129. var origLocMatInv = Bone._tmpMats[1];
  55130. origLocMatInv.copyFrom(origLocMat);
  55131. origLocMatInv.invert();
  55132. var scaleMat = Bone._tmpMats[2];
  55133. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  55134. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  55135. this._scaleVector.x *= x;
  55136. this._scaleVector.y *= y;
  55137. this._scaleVector.z *= z;
  55138. locMat.multiplyToRef(origLocMatInv, locMat);
  55139. locMat.multiplyToRef(scaleMat, locMat);
  55140. locMat.multiplyToRef(origLocMat, locMat);
  55141. var parent = this.getParent();
  55142. if (parent) {
  55143. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  55144. }
  55145. else {
  55146. this.getAbsoluteTransform().copyFrom(locMat);
  55147. }
  55148. var len = this.children.length;
  55149. scaleMat.invert();
  55150. for (var i = 0; i < len; i++) {
  55151. var child = this.children[i];
  55152. var cm = child.getLocalMatrix();
  55153. cm.multiplyToRef(scaleMat, cm);
  55154. var lm = child.getLocalMatrix();
  55155. lm.m[12] *= x;
  55156. lm.m[13] *= y;
  55157. lm.m[14] *= z;
  55158. }
  55159. this.computeAbsoluteTransforms();
  55160. if (scaleChildren) {
  55161. for (var i = 0; i < len; i++) {
  55162. this.children[i].scale(x, y, z, scaleChildren);
  55163. }
  55164. }
  55165. this.markAsDirty();
  55166. };
  55167. /**
  55168. * Set the yaw, pitch, and roll of the bone in local or world space.
  55169. * @param yaw The rotation of the bone on the y axis.
  55170. * @param pitch The rotation of the bone on the x axis.
  55171. * @param roll The rotation of the bone on the z axis.
  55172. * @param space The space that the axes of rotation are in.
  55173. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55174. */
  55175. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  55176. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55177. var rotMat = Bone._tmpMats[0];
  55178. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  55179. var rotMatInv = Bone._tmpMats[1];
  55180. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55181. rotMatInv.multiplyToRef(rotMat, rotMat);
  55182. this._rotateWithMatrix(rotMat, space, mesh);
  55183. };
  55184. /**
  55185. * Rotate the bone on an axis in local or world space.
  55186. * @param axis The axis to rotate the bone on.
  55187. * @param amount The amount to rotate the bone.
  55188. * @param space The space that the axis is in.
  55189. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55190. */
  55191. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  55192. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55193. var rmat = Bone._tmpMats[0];
  55194. rmat.m[12] = 0;
  55195. rmat.m[13] = 0;
  55196. rmat.m[14] = 0;
  55197. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  55198. this._rotateWithMatrix(rmat, space, mesh);
  55199. };
  55200. /**
  55201. * Set the rotation of the bone to a particular axis angle in local or world space.
  55202. * @param axis The axis to rotate the bone on.
  55203. * @param angle The angle that the bone should be rotated to.
  55204. * @param space The space that the axis is in.
  55205. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55206. */
  55207. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  55208. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55209. var rotMat = Bone._tmpMats[0];
  55210. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  55211. var rotMatInv = Bone._tmpMats[1];
  55212. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55213. rotMatInv.multiplyToRef(rotMat, rotMat);
  55214. this._rotateWithMatrix(rotMat, space, mesh);
  55215. };
  55216. /**
  55217. * Set the euler rotation of the bone in local of world space.
  55218. * @param rotation The euler rotation that the bone should be set to.
  55219. * @param space The space that the rotation is in.
  55220. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55221. */
  55222. Bone.prototype.setRotation = function (rotation, space, mesh) {
  55223. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55224. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  55225. };
  55226. /**
  55227. * Set the quaternion rotation of the bone in local of world space.
  55228. * @param quat The quaternion rotation that the bone should be set to.
  55229. * @param space The space that the rotation is in.
  55230. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55231. */
  55232. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  55233. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55234. var rotMatInv = Bone._tmpMats[0];
  55235. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55236. var rotMat = Bone._tmpMats[1];
  55237. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  55238. rotMatInv.multiplyToRef(rotMat, rotMat);
  55239. this._rotateWithMatrix(rotMat, space, mesh);
  55240. };
  55241. /**
  55242. * Set the rotation matrix of the bone in local of world space.
  55243. * @param rotMat The rotation matrix that the bone should be set to.
  55244. * @param space The space that the rotation is in.
  55245. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55246. */
  55247. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  55248. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55249. var rotMatInv = Bone._tmpMats[0];
  55250. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55251. var rotMat2 = Bone._tmpMats[1];
  55252. rotMat2.copyFrom(rotMat);
  55253. rotMatInv.multiplyToRef(rotMat, rotMat2);
  55254. this._rotateWithMatrix(rotMat2, space, mesh);
  55255. };
  55256. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  55257. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55258. var lmat = this.getLocalMatrix();
  55259. var lx = lmat.m[12];
  55260. var ly = lmat.m[13];
  55261. var lz = lmat.m[14];
  55262. var parent = this.getParent();
  55263. var parentScale = Bone._tmpMats[3];
  55264. var parentScaleInv = Bone._tmpMats[4];
  55265. if (parent) {
  55266. if (space == BABYLON.Space.WORLD) {
  55267. if (mesh) {
  55268. parentScale.copyFrom(mesh.getWorldMatrix());
  55269. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  55270. }
  55271. else {
  55272. parentScale.copyFrom(parent.getAbsoluteTransform());
  55273. }
  55274. }
  55275. else {
  55276. parentScale = parent._scaleMatrix;
  55277. }
  55278. parentScaleInv.copyFrom(parentScale);
  55279. parentScaleInv.invert();
  55280. lmat.multiplyToRef(parentScale, lmat);
  55281. lmat.multiplyToRef(rmat, lmat);
  55282. lmat.multiplyToRef(parentScaleInv, lmat);
  55283. }
  55284. else {
  55285. if (space == BABYLON.Space.WORLD && mesh) {
  55286. parentScale.copyFrom(mesh.getWorldMatrix());
  55287. parentScaleInv.copyFrom(parentScale);
  55288. parentScaleInv.invert();
  55289. lmat.multiplyToRef(parentScale, lmat);
  55290. lmat.multiplyToRef(rmat, lmat);
  55291. lmat.multiplyToRef(parentScaleInv, lmat);
  55292. }
  55293. else {
  55294. lmat.multiplyToRef(rmat, lmat);
  55295. }
  55296. }
  55297. lmat.m[12] = lx;
  55298. lmat.m[13] = ly;
  55299. lmat.m[14] = lz;
  55300. this.computeAbsoluteTransforms();
  55301. this.markAsDirty();
  55302. };
  55303. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  55304. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55305. if (space == BABYLON.Space.WORLD) {
  55306. var scaleMatrix = Bone._tmpMats[2];
  55307. scaleMatrix.copyFrom(this._scaleMatrix);
  55308. rotMatInv.copyFrom(this.getAbsoluteTransform());
  55309. if (mesh) {
  55310. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  55311. var meshScale = Bone._tmpMats[3];
  55312. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  55313. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  55314. }
  55315. rotMatInv.invert();
  55316. scaleMatrix.m[0] *= this._scalingDeterminant;
  55317. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55318. }
  55319. else {
  55320. rotMatInv.copyFrom(this.getLocalMatrix());
  55321. rotMatInv.invert();
  55322. var scaleMatrix = Bone._tmpMats[2];
  55323. scaleMatrix.copyFrom(this._scaleMatrix);
  55324. if (this._parent) {
  55325. var pscaleMatrix = Bone._tmpMats[3];
  55326. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  55327. pscaleMatrix.invert();
  55328. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  55329. }
  55330. else {
  55331. scaleMatrix.m[0] *= this._scalingDeterminant;
  55332. }
  55333. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55334. }
  55335. };
  55336. /**
  55337. * Get the scale of the bone
  55338. * @returns the scale of the bone
  55339. */
  55340. Bone.prototype.getScale = function () {
  55341. return this._scaleVector.clone();
  55342. };
  55343. /**
  55344. * Copy the scale of the bone to a vector3.
  55345. * @param result The vector3 to copy the scale to
  55346. */
  55347. Bone.prototype.getScaleToRef = function (result) {
  55348. result.copyFrom(this._scaleVector);
  55349. };
  55350. /**
  55351. * Get the position of the bone in local or world space.
  55352. * @param space The space that the returned position is in.
  55353. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55354. * @returns The position of the bone
  55355. */
  55356. Bone.prototype.getPosition = function (space, mesh) {
  55357. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55358. var pos = BABYLON.Vector3.Zero();
  55359. this.getPositionToRef(space, mesh, pos);
  55360. return pos;
  55361. };
  55362. /**
  55363. * Copy the position of the bone to a vector3 in local or world space.
  55364. * @param space The space that the returned position is in.
  55365. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55366. * @param result The vector3 to copy the position to.
  55367. */
  55368. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  55369. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55370. if (space == BABYLON.Space.LOCAL) {
  55371. var lm = this.getLocalMatrix();
  55372. result.x = lm.m[12];
  55373. result.y = lm.m[13];
  55374. result.z = lm.m[14];
  55375. }
  55376. else {
  55377. var wm;
  55378. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55379. if (mesh) {
  55380. wm = mesh.getWorldMatrix();
  55381. }
  55382. this._skeleton.computeAbsoluteTransforms();
  55383. var tmat = Bone._tmpMats[0];
  55384. if (mesh) {
  55385. tmat.copyFrom(this.getAbsoluteTransform());
  55386. tmat.multiplyToRef(wm, tmat);
  55387. }
  55388. else {
  55389. tmat = this.getAbsoluteTransform();
  55390. }
  55391. result.x = tmat.m[12];
  55392. result.y = tmat.m[13];
  55393. result.z = tmat.m[14];
  55394. }
  55395. };
  55396. /**
  55397. * Get the absolute position of the bone (world space).
  55398. * @param mesh The mesh that this bone is attached to.
  55399. * @returns The absolute position of the bone
  55400. */
  55401. Bone.prototype.getAbsolutePosition = function (mesh) {
  55402. var pos = BABYLON.Vector3.Zero();
  55403. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  55404. return pos;
  55405. };
  55406. /**
  55407. * Copy the absolute position of the bone (world space) to the result param.
  55408. * @param mesh The mesh that this bone is attached to.
  55409. * @param result The vector3 to copy the absolute position to.
  55410. */
  55411. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  55412. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  55413. };
  55414. /**
  55415. * Compute the absolute transforms of this bone and its children.
  55416. */
  55417. Bone.prototype.computeAbsoluteTransforms = function () {
  55418. if (this._parent) {
  55419. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  55420. }
  55421. else {
  55422. this._absoluteTransform.copyFrom(this._localMatrix);
  55423. var poseMatrix = this._skeleton.getPoseMatrix();
  55424. if (poseMatrix) {
  55425. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  55426. }
  55427. }
  55428. var children = this.children;
  55429. var len = children.length;
  55430. for (var i = 0; i < len; i++) {
  55431. children[i].computeAbsoluteTransforms();
  55432. }
  55433. };
  55434. Bone.prototype._syncScaleVector = function () {
  55435. var lm = this.getLocalMatrix();
  55436. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  55437. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  55438. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  55439. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  55440. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  55441. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  55442. this._scaleVector.x = xs * Math.sqrt(xsq);
  55443. this._scaleVector.y = ys * Math.sqrt(ysq);
  55444. this._scaleVector.z = zs * Math.sqrt(zsq);
  55445. if (this._parent) {
  55446. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  55447. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  55448. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  55449. }
  55450. 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);
  55451. };
  55452. /**
  55453. * Get the world direction from an axis that is in the local space of the bone.
  55454. * @param localAxis The local direction that is used to compute the world direction.
  55455. * @param mesh The mesh that this bone is attached to.
  55456. * @returns The world direction
  55457. */
  55458. Bone.prototype.getDirection = function (localAxis, mesh) {
  55459. var result = BABYLON.Vector3.Zero();
  55460. this.getDirectionToRef(localAxis, mesh, result);
  55461. return result;
  55462. };
  55463. /**
  55464. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  55465. * @param localAxis The local direction that is used to compute the world direction.
  55466. * @param mesh The mesh that this bone is attached to.
  55467. * @param result The vector3 that the world direction will be copied to.
  55468. */
  55469. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  55470. var wm;
  55471. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55472. if (mesh) {
  55473. wm = mesh.getWorldMatrix();
  55474. }
  55475. this._skeleton.computeAbsoluteTransforms();
  55476. var mat = Bone._tmpMats[0];
  55477. mat.copyFrom(this.getAbsoluteTransform());
  55478. if (mesh) {
  55479. mat.multiplyToRef(wm, mat);
  55480. }
  55481. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  55482. result.normalize();
  55483. };
  55484. /**
  55485. * Get the euler rotation of the bone in local or world space.
  55486. * @param space The space that the rotation should be in.
  55487. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55488. * @returns The euler rotation
  55489. */
  55490. Bone.prototype.getRotation = function (space, mesh) {
  55491. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55492. var result = BABYLON.Vector3.Zero();
  55493. this.getRotationToRef(space, mesh, result);
  55494. return result;
  55495. };
  55496. /**
  55497. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  55498. * @param space The space that the rotation should be in.
  55499. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55500. * @param result The vector3 that the rotation should be copied to.
  55501. */
  55502. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  55503. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55504. var quat = Bone._tmpQuat;
  55505. this.getRotationQuaternionToRef(space, mesh, quat);
  55506. quat.toEulerAnglesToRef(result);
  55507. };
  55508. /**
  55509. * Get the quaternion rotation of the bone in either local or world space.
  55510. * @param space The space that the rotation should be in.
  55511. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55512. * @returns The quaternion rotation
  55513. */
  55514. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  55515. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55516. var result = BABYLON.Quaternion.Identity();
  55517. this.getRotationQuaternionToRef(space, mesh, result);
  55518. return result;
  55519. };
  55520. /**
  55521. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  55522. * @param space The space that the rotation should be in.
  55523. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55524. * @param result The quaternion that the rotation should be copied to.
  55525. */
  55526. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  55527. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55528. if (space == BABYLON.Space.LOCAL) {
  55529. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  55530. }
  55531. else {
  55532. var mat = Bone._tmpMats[0];
  55533. var amat = this.getAbsoluteTransform();
  55534. if (mesh) {
  55535. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  55536. }
  55537. else {
  55538. mat.copyFrom(amat);
  55539. }
  55540. mat.m[0] *= this._scalingDeterminant;
  55541. mat.m[1] *= this._scalingDeterminant;
  55542. mat.m[2] *= this._scalingDeterminant;
  55543. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  55544. }
  55545. };
  55546. /**
  55547. * Get the rotation matrix of the bone in local or world space.
  55548. * @param space The space that the rotation should be in.
  55549. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55550. * @returns The rotation matrix
  55551. */
  55552. Bone.prototype.getRotationMatrix = function (space, mesh) {
  55553. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55554. var result = BABYLON.Matrix.Identity();
  55555. this.getRotationMatrixToRef(space, mesh, result);
  55556. return result;
  55557. };
  55558. /**
  55559. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  55560. * @param space The space that the rotation should be in.
  55561. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55562. * @param result The quaternion that the rotation should be copied to.
  55563. */
  55564. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  55565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55566. if (space == BABYLON.Space.LOCAL) {
  55567. this.getLocalMatrix().getRotationMatrixToRef(result);
  55568. }
  55569. else {
  55570. var mat = Bone._tmpMats[0];
  55571. var amat = this.getAbsoluteTransform();
  55572. if (mesh) {
  55573. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  55574. }
  55575. else {
  55576. mat.copyFrom(amat);
  55577. }
  55578. mat.m[0] *= this._scalingDeterminant;
  55579. mat.m[1] *= this._scalingDeterminant;
  55580. mat.m[2] *= this._scalingDeterminant;
  55581. mat.getRotationMatrixToRef(result);
  55582. }
  55583. };
  55584. /**
  55585. * Get the world position of a point that is in the local space of the bone.
  55586. * @param position The local position
  55587. * @param mesh The mesh that this bone is attached to.
  55588. * @returns The world position
  55589. */
  55590. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  55591. var result = BABYLON.Vector3.Zero();
  55592. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  55593. return result;
  55594. };
  55595. /**
  55596. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  55597. * @param position The local position
  55598. * @param mesh The mesh that this bone is attached to.
  55599. * @param result The vector3 that the world position should be copied to.
  55600. */
  55601. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  55602. var wm;
  55603. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55604. if (mesh) {
  55605. wm = mesh.getWorldMatrix();
  55606. }
  55607. this._skeleton.computeAbsoluteTransforms();
  55608. var tmat = Bone._tmpMats[0];
  55609. if (mesh) {
  55610. tmat.copyFrom(this.getAbsoluteTransform());
  55611. tmat.multiplyToRef(wm, tmat);
  55612. }
  55613. else {
  55614. tmat = this.getAbsoluteTransform();
  55615. }
  55616. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  55617. };
  55618. /**
  55619. * Get the local position of a point that is in world space.
  55620. * @param position The world position
  55621. * @param mesh The mesh that this bone is attached to.
  55622. * @returns The local position
  55623. */
  55624. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  55625. var result = BABYLON.Vector3.Zero();
  55626. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  55627. return result;
  55628. };
  55629. /**
  55630. * Get the local position of a point that is in world space and copy it to the result param.
  55631. * @param position The world position
  55632. * @param mesh The mesh that this bone is attached to.
  55633. * @param result The vector3 that the local position should be copied to.
  55634. */
  55635. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  55636. var wm;
  55637. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55638. if (mesh) {
  55639. wm = mesh.getWorldMatrix();
  55640. }
  55641. this._skeleton.computeAbsoluteTransforms();
  55642. var tmat = Bone._tmpMats[0];
  55643. tmat.copyFrom(this.getAbsoluteTransform());
  55644. if (mesh) {
  55645. tmat.multiplyToRef(wm, tmat);
  55646. }
  55647. tmat.invert();
  55648. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  55649. };
  55650. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55651. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  55652. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  55653. return Bone;
  55654. }(BABYLON.Node));
  55655. BABYLON.Bone = Bone;
  55656. })(BABYLON || (BABYLON = {}));
  55657. //# sourceMappingURL=babylon.bone.js.map
  55658. var BABYLON;
  55659. (function (BABYLON) {
  55660. var BoneIKController = (function () {
  55661. function BoneIKController(mesh, bone, options) {
  55662. this.targetPosition = BABYLON.Vector3.Zero();
  55663. this.poleTargetPosition = BABYLON.Vector3.Zero();
  55664. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  55665. this.poleAngle = 0;
  55666. this.slerpAmount = 1;
  55667. this._bone1Quat = BABYLON.Quaternion.Identity();
  55668. this._bone1Mat = BABYLON.Matrix.Identity();
  55669. this._bone2Ang = Math.PI;
  55670. this._maxAngle = Math.PI;
  55671. this._rightHandedSystem = false;
  55672. this._bendAxis = BABYLON.Vector3.Right();
  55673. this._slerping = false;
  55674. this._adjustRoll = 0;
  55675. this._bone2 = bone;
  55676. this._bone1 = bone.getParent();
  55677. this.mesh = mesh;
  55678. var bonePos = bone.getPosition();
  55679. if (bone.getAbsoluteTransform().determinant() > 0) {
  55680. this._rightHandedSystem = true;
  55681. this._bendAxis.x = 0;
  55682. this._bendAxis.y = 0;
  55683. this._bendAxis.z = -1;
  55684. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  55685. this._adjustRoll = Math.PI * .5;
  55686. this._bendAxis.z = 1;
  55687. }
  55688. }
  55689. if (this._bone1.length) {
  55690. var boneScale1 = this._bone1.getScale();
  55691. var boneScale2 = this._bone2.getScale();
  55692. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  55693. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  55694. }
  55695. else if (this._bone1.children[0]) {
  55696. mesh.computeWorldMatrix(true);
  55697. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  55698. var pos2 = this._bone2.getAbsolutePosition(mesh);
  55699. var pos3 = this._bone1.getAbsolutePosition(mesh);
  55700. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  55701. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  55702. }
  55703. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  55704. this.maxAngle = Math.PI;
  55705. if (options) {
  55706. if (options.targetMesh) {
  55707. this.targetMesh = options.targetMesh;
  55708. this.targetMesh.computeWorldMatrix(true);
  55709. }
  55710. if (options.poleTargetMesh) {
  55711. this.poleTargetMesh = options.poleTargetMesh;
  55712. this.poleTargetMesh.computeWorldMatrix(true);
  55713. }
  55714. else if (options.poleTargetBone) {
  55715. this.poleTargetBone = options.poleTargetBone;
  55716. }
  55717. else if (this._bone1.getParent()) {
  55718. this.poleTargetBone = this._bone1.getParent();
  55719. }
  55720. if (options.poleTargetLocalOffset) {
  55721. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  55722. }
  55723. if (options.poleAngle) {
  55724. this.poleAngle = options.poleAngle;
  55725. }
  55726. if (options.bendAxis) {
  55727. this._bendAxis.copyFrom(options.bendAxis);
  55728. }
  55729. if (options.maxAngle) {
  55730. this.maxAngle = options.maxAngle;
  55731. }
  55732. if (options.slerpAmount) {
  55733. this.slerpAmount = options.slerpAmount;
  55734. }
  55735. }
  55736. }
  55737. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  55738. get: function () {
  55739. return this._maxAngle;
  55740. },
  55741. set: function (value) {
  55742. this._setMaxAngle(value);
  55743. },
  55744. enumerable: true,
  55745. configurable: true
  55746. });
  55747. BoneIKController.prototype._setMaxAngle = function (ang) {
  55748. if (ang < 0) {
  55749. ang = 0;
  55750. }
  55751. if (ang > Math.PI || ang == undefined) {
  55752. ang = Math.PI;
  55753. }
  55754. this._maxAngle = ang;
  55755. var a = this._bone1Length;
  55756. var b = this._bone2Length;
  55757. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  55758. };
  55759. BoneIKController.prototype.update = function () {
  55760. var bone1 = this._bone1;
  55761. var target = this.targetPosition;
  55762. var poleTarget = this.poleTargetPosition;
  55763. var mat1 = BoneIKController._tmpMats[0];
  55764. var mat2 = BoneIKController._tmpMats[1];
  55765. if (this.targetMesh) {
  55766. target.copyFrom(this.targetMesh.getAbsolutePosition());
  55767. }
  55768. if (this.poleTargetBone) {
  55769. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  55770. }
  55771. else if (this.poleTargetMesh) {
  55772. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  55773. }
  55774. var bonePos = BoneIKController._tmpVecs[0];
  55775. var zaxis = BoneIKController._tmpVecs[1];
  55776. var xaxis = BoneIKController._tmpVecs[2];
  55777. var yaxis = BoneIKController._tmpVecs[3];
  55778. var upAxis = BoneIKController._tmpVecs[4];
  55779. var _tmpQuat = BoneIKController._tmpQuat;
  55780. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  55781. poleTarget.subtractToRef(bonePos, upAxis);
  55782. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  55783. upAxis.y = 1;
  55784. }
  55785. else {
  55786. upAxis.normalize();
  55787. }
  55788. target.subtractToRef(bonePos, yaxis);
  55789. yaxis.normalize();
  55790. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  55791. zaxis.normalize();
  55792. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  55793. xaxis.normalize();
  55794. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  55795. var a = this._bone1Length;
  55796. var b = this._bone2Length;
  55797. var c = BABYLON.Vector3.Distance(bonePos, target);
  55798. if (this._maxReach > 0) {
  55799. c = Math.min(this._maxReach, c);
  55800. }
  55801. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  55802. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  55803. if (acosa > 1) {
  55804. acosa = 1;
  55805. }
  55806. if (acosb > 1) {
  55807. acosb = 1;
  55808. }
  55809. if (acosa < -1) {
  55810. acosa = -1;
  55811. }
  55812. if (acosb < -1) {
  55813. acosb = -1;
  55814. }
  55815. var angA = Math.acos(acosa);
  55816. var angB = Math.acos(acosb);
  55817. var angC = -angA - angB;
  55818. if (this._rightHandedSystem) {
  55819. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  55820. mat2.multiplyToRef(mat1, mat1);
  55821. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  55822. mat2.multiplyToRef(mat1, mat1);
  55823. }
  55824. else {
  55825. var _tmpVec = BoneIKController._tmpVecs[5];
  55826. _tmpVec.copyFrom(this._bendAxis);
  55827. _tmpVec.x *= -1;
  55828. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  55829. mat2.multiplyToRef(mat1, mat1);
  55830. }
  55831. if (this.poleAngle) {
  55832. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  55833. mat1.multiplyToRef(mat2, mat1);
  55834. }
  55835. if (this.slerpAmount < 1) {
  55836. if (!this._slerping) {
  55837. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  55838. }
  55839. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  55840. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  55841. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  55842. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  55843. this._slerping = true;
  55844. }
  55845. else {
  55846. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  55847. this._bone1Mat.copyFrom(mat1);
  55848. this._slerping = false;
  55849. }
  55850. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  55851. this._bone2Ang = angC;
  55852. };
  55853. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55854. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  55855. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  55856. return BoneIKController;
  55857. }());
  55858. BABYLON.BoneIKController = BoneIKController;
  55859. })(BABYLON || (BABYLON = {}));
  55860. //# sourceMappingURL=babylon.boneIKController.js.map
  55861. var BABYLON;
  55862. (function (BABYLON) {
  55863. var BoneLookController = (function () {
  55864. /**
  55865. * Create a BoneLookController
  55866. * @param mesh the mesh that the bone belongs to
  55867. * @param bone the bone that will be looking to the target
  55868. * @param target the target Vector3 to look at
  55869. * @param settings optional settings:
  55870. * - maxYaw: the maximum angle the bone will yaw to
  55871. * - minYaw: the minimum angle the bone will yaw to
  55872. * - maxPitch: the maximum angle the bone will pitch to
  55873. * - minPitch: the minimum angle the bone will yaw to
  55874. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  55875. * - upAxis: the up axis of the coordinate system
  55876. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  55877. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  55878. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  55879. * - adjustYaw: used to make an adjustment to the yaw of the bone
  55880. * - adjustPitch: used to make an adjustment to the pitch of the bone
  55881. * - adjustRoll: used to make an adjustment to the roll of the bone
  55882. **/
  55883. function BoneLookController(mesh, bone, target, options) {
  55884. /**
  55885. * The up axis of the coordinate system that is used when the bone is rotated.
  55886. */
  55887. this.upAxis = BABYLON.Vector3.Up();
  55888. /**
  55889. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  55890. */
  55891. this.upAxisSpace = BABYLON.Space.LOCAL;
  55892. /**
  55893. * Used to make an adjustment to the yaw of the bone.
  55894. */
  55895. this.adjustYaw = 0;
  55896. /**
  55897. * Used to make an adjustment to the pitch of the bone.
  55898. */
  55899. this.adjustPitch = 0;
  55900. /**
  55901. * Used to make an adjustment to the roll of the bone.
  55902. */
  55903. this.adjustRoll = 0;
  55904. /**
  55905. * 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).
  55906. */
  55907. this.slerpAmount = 1;
  55908. this._boneQuat = BABYLON.Quaternion.Identity();
  55909. this._slerping = false;
  55910. this._firstFrameSkipped = false;
  55911. this._fowardAxis = BABYLON.Vector3.Forward();
  55912. this.mesh = mesh;
  55913. this.bone = bone;
  55914. this.target = target;
  55915. if (options) {
  55916. if (options.adjustYaw) {
  55917. this.adjustYaw = options.adjustYaw;
  55918. }
  55919. if (options.adjustPitch) {
  55920. this.adjustPitch = options.adjustPitch;
  55921. }
  55922. if (options.adjustRoll) {
  55923. this.adjustRoll = options.adjustRoll;
  55924. }
  55925. if (options.maxYaw != null) {
  55926. this.maxYaw = options.maxYaw;
  55927. }
  55928. else {
  55929. this.maxYaw = Math.PI;
  55930. }
  55931. if (options.minYaw != null) {
  55932. this.minYaw = options.minYaw;
  55933. }
  55934. else {
  55935. this.minYaw = -Math.PI;
  55936. }
  55937. if (options.maxPitch != null) {
  55938. this.maxPitch = options.maxPitch;
  55939. }
  55940. else {
  55941. this.maxPitch = Math.PI;
  55942. }
  55943. if (options.minPitch != null) {
  55944. this.minPitch = options.minPitch;
  55945. }
  55946. else {
  55947. this.minPitch = -Math.PI;
  55948. }
  55949. if (options.slerpAmount != null) {
  55950. this.slerpAmount = options.slerpAmount;
  55951. }
  55952. if (options.upAxis != null) {
  55953. this.upAxis = options.upAxis;
  55954. }
  55955. if (options.upAxisSpace != null) {
  55956. this.upAxisSpace = options.upAxisSpace;
  55957. }
  55958. if (options.yawAxis != null || options.pitchAxis != null) {
  55959. var newYawAxis = BABYLON.Axis.Y;
  55960. var newPitchAxis = BABYLON.Axis.X;
  55961. if (options.yawAxis != null) {
  55962. newYawAxis = options.yawAxis.clone();
  55963. newYawAxis.normalize();
  55964. }
  55965. if (options.pitchAxis != null) {
  55966. newPitchAxis = options.pitchAxis.clone();
  55967. newPitchAxis.normalize();
  55968. }
  55969. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  55970. this._transformYawPitch = BABYLON.Matrix.Identity();
  55971. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  55972. this._transformYawPitchInv = this._transformYawPitch.clone();
  55973. this._transformYawPitch.invert();
  55974. }
  55975. }
  55976. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  55977. this.upAxisSpace = BABYLON.Space.LOCAL;
  55978. }
  55979. }
  55980. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  55981. /**
  55982. * Get/set the minimum yaw angle that the bone can look to.
  55983. */
  55984. get: function () {
  55985. return this._minYaw;
  55986. },
  55987. set: function (value) {
  55988. this._minYaw = value;
  55989. this._minYawSin = Math.sin(value);
  55990. this._minYawCos = Math.cos(value);
  55991. if (this._maxYaw != null) {
  55992. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  55993. this._yawRange = this._maxYaw - this._minYaw;
  55994. }
  55995. },
  55996. enumerable: true,
  55997. configurable: true
  55998. });
  55999. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  56000. /**
  56001. * Get/set the maximum yaw angle that the bone can look to.
  56002. */
  56003. get: function () {
  56004. return this._maxYaw;
  56005. },
  56006. set: function (value) {
  56007. this._maxYaw = value;
  56008. this._maxYawSin = Math.sin(value);
  56009. this._maxYawCos = Math.cos(value);
  56010. if (this._minYaw != null) {
  56011. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  56012. this._yawRange = this._maxYaw - this._minYaw;
  56013. }
  56014. },
  56015. enumerable: true,
  56016. configurable: true
  56017. });
  56018. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  56019. /**
  56020. * Get/set the minimum pitch angle that the bone can look to.
  56021. */
  56022. get: function () {
  56023. return this._minPitch;
  56024. },
  56025. set: function (value) {
  56026. this._minPitch = value;
  56027. this._minPitchTan = Math.tan(value);
  56028. },
  56029. enumerable: true,
  56030. configurable: true
  56031. });
  56032. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  56033. /**
  56034. * Get/set the maximum pitch angle that the bone can look to.
  56035. */
  56036. get: function () {
  56037. return this._maxPitch;
  56038. },
  56039. set: function (value) {
  56040. this._maxPitch = value;
  56041. this._maxPitchTan = Math.tan(value);
  56042. },
  56043. enumerable: true,
  56044. configurable: true
  56045. });
  56046. /**
  56047. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  56048. */
  56049. BoneLookController.prototype.update = function () {
  56050. //skip the first frame when slerping so that the mesh rotation is correct
  56051. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  56052. this._firstFrameSkipped = true;
  56053. return;
  56054. }
  56055. var bone = this.bone;
  56056. var bonePos = BoneLookController._tmpVecs[0];
  56057. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  56058. var target = this.target;
  56059. var _tmpMat1 = BoneLookController._tmpMats[0];
  56060. var _tmpMat2 = BoneLookController._tmpMats[1];
  56061. var mesh = this.mesh;
  56062. var parentBone = bone.getParent();
  56063. var upAxis = BoneLookController._tmpVecs[1];
  56064. upAxis.copyFrom(this.upAxis);
  56065. if (this.upAxisSpace == BABYLON.Space.BONE) {
  56066. if (this._transformYawPitch) {
  56067. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  56068. }
  56069. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  56070. }
  56071. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  56072. mesh.getDirectionToRef(upAxis, upAxis);
  56073. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  56074. upAxis.normalize();
  56075. }
  56076. }
  56077. var checkYaw = false;
  56078. var checkPitch = false;
  56079. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  56080. checkYaw = true;
  56081. }
  56082. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  56083. checkPitch = true;
  56084. }
  56085. if (checkYaw || checkPitch) {
  56086. var spaceMat = BoneLookController._tmpMats[2];
  56087. var spaceMatInv = BoneLookController._tmpMats[3];
  56088. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  56089. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  56090. }
  56091. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  56092. spaceMat.copyFrom(mesh.getWorldMatrix());
  56093. }
  56094. else {
  56095. var forwardAxis = BoneLookController._tmpVecs[2];
  56096. forwardAxis.copyFrom(this._fowardAxis);
  56097. if (this._transformYawPitch) {
  56098. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  56099. }
  56100. if (parentBone) {
  56101. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  56102. }
  56103. else {
  56104. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  56105. }
  56106. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  56107. rightAxis.normalize();
  56108. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  56109. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  56110. }
  56111. spaceMat.invertToRef(spaceMatInv);
  56112. var xzlen;
  56113. if (checkPitch) {
  56114. var localTarget = BoneLookController._tmpVecs[3];
  56115. target.subtractToRef(bonePos, localTarget);
  56116. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  56117. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56118. var pitch = Math.atan2(localTarget.y, xzlen);
  56119. var newPitch = pitch;
  56120. if (pitch > this._maxPitch) {
  56121. localTarget.y = this._maxPitchTan * xzlen;
  56122. newPitch = this._maxPitch;
  56123. }
  56124. else if (pitch < this._minPitch) {
  56125. localTarget.y = this._minPitchTan * xzlen;
  56126. newPitch = this._minPitch;
  56127. }
  56128. if (pitch != newPitch) {
  56129. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  56130. localTarget.addInPlace(bonePos);
  56131. target = localTarget;
  56132. }
  56133. }
  56134. if (checkYaw) {
  56135. var localTarget = BoneLookController._tmpVecs[4];
  56136. target.subtractToRef(bonePos, localTarget);
  56137. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  56138. var yaw = Math.atan2(localTarget.x, localTarget.z);
  56139. var newYaw = yaw;
  56140. if (yaw > this._maxYaw || yaw < this._minYaw) {
  56141. if (xzlen == null) {
  56142. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56143. }
  56144. if (this._yawRange > Math.PI) {
  56145. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  56146. localTarget.z = this._maxYawCos * xzlen;
  56147. localTarget.x = this._maxYawSin * xzlen;
  56148. newYaw = this._maxYaw;
  56149. }
  56150. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  56151. localTarget.z = this._minYawCos * xzlen;
  56152. localTarget.x = this._minYawSin * xzlen;
  56153. newYaw = this._minYaw;
  56154. }
  56155. }
  56156. else {
  56157. if (yaw > this._maxYaw) {
  56158. localTarget.z = this._maxYawCos * xzlen;
  56159. localTarget.x = this._maxYawSin * xzlen;
  56160. newYaw = this._maxYaw;
  56161. }
  56162. else if (yaw < this._minYaw) {
  56163. localTarget.z = this._minYawCos * xzlen;
  56164. localTarget.x = this._minYawSin * xzlen;
  56165. newYaw = this._minYaw;
  56166. }
  56167. }
  56168. }
  56169. if (this._slerping && this._yawRange > Math.PI) {
  56170. //are we going to be crossing into the min/max region?
  56171. var boneFwd = BoneLookController._tmpVecs[8];
  56172. boneFwd.copyFrom(BABYLON.Axis.Z);
  56173. if (this._transformYawPitch) {
  56174. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  56175. }
  56176. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  56177. this._boneQuat.toRotationMatrix(boneRotMat);
  56178. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  56179. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  56180. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  56181. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  56182. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  56183. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  56184. if (angBtwTar > angBtwMidYaw) {
  56185. if (xzlen == null) {
  56186. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56187. }
  56188. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  56189. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  56190. if (angBtwMin < angBtwMax) {
  56191. newYaw = boneYaw + Math.PI * .75;
  56192. localTarget.z = Math.cos(newYaw) * xzlen;
  56193. localTarget.x = Math.sin(newYaw) * xzlen;
  56194. }
  56195. else {
  56196. newYaw = boneYaw - Math.PI * .75;
  56197. localTarget.z = Math.cos(newYaw) * xzlen;
  56198. localTarget.x = Math.sin(newYaw) * xzlen;
  56199. }
  56200. }
  56201. }
  56202. if (yaw != newYaw) {
  56203. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  56204. localTarget.addInPlace(bonePos);
  56205. target = localTarget;
  56206. }
  56207. }
  56208. }
  56209. var zaxis = BoneLookController._tmpVecs[5];
  56210. var xaxis = BoneLookController._tmpVecs[6];
  56211. var yaxis = BoneLookController._tmpVecs[7];
  56212. var _tmpQuat = BoneLookController._tmpQuat;
  56213. target.subtractToRef(bonePos, zaxis);
  56214. zaxis.normalize();
  56215. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  56216. xaxis.normalize();
  56217. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  56218. yaxis.normalize();
  56219. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  56220. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  56221. return;
  56222. }
  56223. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  56224. return;
  56225. }
  56226. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  56227. return;
  56228. }
  56229. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  56230. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  56231. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  56232. }
  56233. if (this.slerpAmount < 1) {
  56234. if (!this._slerping) {
  56235. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  56236. }
  56237. if (this._transformYawPitch) {
  56238. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  56239. }
  56240. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  56241. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  56242. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  56243. this._slerping = true;
  56244. }
  56245. else {
  56246. if (this._transformYawPitch) {
  56247. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  56248. }
  56249. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  56250. this._slerping = false;
  56251. }
  56252. };
  56253. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  56254. var angDiff = ang2 - ang1;
  56255. angDiff %= Math.PI * 2;
  56256. if (angDiff > Math.PI) {
  56257. angDiff -= Math.PI * 2;
  56258. }
  56259. else if (angDiff < -Math.PI) {
  56260. angDiff += Math.PI * 2;
  56261. }
  56262. return angDiff;
  56263. };
  56264. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  56265. ang1 %= (2 * Math.PI);
  56266. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56267. ang2 %= (2 * Math.PI);
  56268. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56269. var ab = 0;
  56270. if (ang1 < ang2) {
  56271. ab = ang2 - ang1;
  56272. }
  56273. else {
  56274. ab = ang1 - ang2;
  56275. }
  56276. if (ab > Math.PI) {
  56277. ab = Math.PI * 2 - ab;
  56278. }
  56279. return ab;
  56280. };
  56281. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  56282. ang %= (2 * Math.PI);
  56283. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  56284. ang1 %= (2 * Math.PI);
  56285. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56286. ang2 %= (2 * Math.PI);
  56287. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56288. if (ang1 < ang2) {
  56289. if (ang > ang1 && ang < ang2) {
  56290. return true;
  56291. }
  56292. }
  56293. else {
  56294. if (ang > ang2 && ang < ang1) {
  56295. return true;
  56296. }
  56297. }
  56298. return false;
  56299. };
  56300. 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()];
  56301. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  56302. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56303. return BoneLookController;
  56304. }());
  56305. BABYLON.BoneLookController = BoneLookController;
  56306. })(BABYLON || (BABYLON = {}));
  56307. //# sourceMappingURL=babylon.boneLookController.js.map
  56308. var BABYLON;
  56309. (function (BABYLON) {
  56310. var Skeleton = (function () {
  56311. function Skeleton(name, id, scene) {
  56312. this.name = name;
  56313. this.id = id;
  56314. this.bones = new Array();
  56315. this.needInitialSkinMatrix = false;
  56316. this._isDirty = true;
  56317. this._meshesWithPoseMatrix = new Array();
  56318. this._identity = BABYLON.Matrix.Identity();
  56319. this._ranges = {};
  56320. this._lastAbsoluteTransformsUpdateId = -1;
  56321. // Events
  56322. /**
  56323. * An event triggered before computing the skeleton's matrices
  56324. * @type {BABYLON.Observable}
  56325. */
  56326. this.onBeforeComputeObservable = new BABYLON.Observable();
  56327. this.bones = [];
  56328. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56329. scene.skeletons.push(this);
  56330. //make sure it will recalculate the matrix next time prepare is called.
  56331. this._isDirty = true;
  56332. }
  56333. // Members
  56334. Skeleton.prototype.getTransformMatrices = function (mesh) {
  56335. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  56336. return mesh._bonesTransformMatrices;
  56337. }
  56338. if (!this._transformMatrices) {
  56339. this.prepare();
  56340. }
  56341. return this._transformMatrices;
  56342. };
  56343. Skeleton.prototype.getScene = function () {
  56344. return this._scene;
  56345. };
  56346. // Methods
  56347. /**
  56348. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  56349. */
  56350. Skeleton.prototype.toString = function (fullDetails) {
  56351. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  56352. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  56353. if (fullDetails) {
  56354. ret += ", Ranges: {";
  56355. var first = true;
  56356. for (var name_1 in this._ranges) {
  56357. if (first) {
  56358. ret += ", ";
  56359. first = false;
  56360. }
  56361. ret += name_1;
  56362. }
  56363. ret += "}";
  56364. }
  56365. return ret;
  56366. };
  56367. /**
  56368. * Get bone's index searching by name
  56369. * @param {string} name is bone's name to search for
  56370. * @return {number} Indice of the bone. Returns -1 if not found
  56371. */
  56372. Skeleton.prototype.getBoneIndexByName = function (name) {
  56373. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  56374. if (this.bones[boneIndex].name === name) {
  56375. return boneIndex;
  56376. }
  56377. }
  56378. return -1;
  56379. };
  56380. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  56381. // check name not already in use
  56382. if (!this._ranges[name]) {
  56383. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  56384. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56385. if (this.bones[i].animations[0]) {
  56386. this.bones[i].animations[0].createRange(name, from, to);
  56387. }
  56388. }
  56389. }
  56390. };
  56391. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  56392. if (deleteFrames === void 0) { deleteFrames = true; }
  56393. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56394. if (this.bones[i].animations[0]) {
  56395. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  56396. }
  56397. }
  56398. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  56399. };
  56400. Skeleton.prototype.getAnimationRange = function (name) {
  56401. return this._ranges[name];
  56402. };
  56403. /**
  56404. * Returns as an Array, all AnimationRanges defined on this skeleton
  56405. */
  56406. Skeleton.prototype.getAnimationRanges = function () {
  56407. var animationRanges = [];
  56408. var name;
  56409. var i = 0;
  56410. for (name in this._ranges) {
  56411. animationRanges[i] = this._ranges[name];
  56412. i++;
  56413. }
  56414. return animationRanges;
  56415. };
  56416. /**
  56417. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  56418. */
  56419. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  56420. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56421. if (this._ranges[name] || !source.getAnimationRange(name)) {
  56422. return false;
  56423. }
  56424. var ret = true;
  56425. var frameOffset = this._getHighestAnimationFrame() + 1;
  56426. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  56427. var boneDict = {};
  56428. var sourceBones = source.bones;
  56429. var nBones;
  56430. var i;
  56431. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  56432. boneDict[sourceBones[i].name] = sourceBones[i];
  56433. }
  56434. if (this.bones.length !== sourceBones.length) {
  56435. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  56436. ret = false;
  56437. }
  56438. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  56439. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  56440. var boneName = this.bones[i].name;
  56441. var sourceBone = boneDict[boneName];
  56442. if (sourceBone) {
  56443. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  56444. }
  56445. else {
  56446. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  56447. ret = false;
  56448. }
  56449. }
  56450. // do not call createAnimationRange(), since it also is done to bones, which was already done
  56451. var range = source.getAnimationRange(name);
  56452. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  56453. return ret;
  56454. };
  56455. Skeleton.prototype.returnToRest = function () {
  56456. for (var index = 0; index < this.bones.length; index++) {
  56457. this.bones[index].returnToRest();
  56458. }
  56459. };
  56460. Skeleton.prototype._getHighestAnimationFrame = function () {
  56461. var ret = 0;
  56462. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56463. if (this.bones[i].animations[0]) {
  56464. var highest = this.bones[i].animations[0].getHighestFrame();
  56465. if (ret < highest) {
  56466. ret = highest;
  56467. }
  56468. }
  56469. }
  56470. return ret;
  56471. };
  56472. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  56473. var range = this.getAnimationRange(name);
  56474. if (!range) {
  56475. return null;
  56476. }
  56477. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  56478. };
  56479. Skeleton.prototype._markAsDirty = function () {
  56480. this._isDirty = true;
  56481. };
  56482. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  56483. this._meshesWithPoseMatrix.push(mesh);
  56484. };
  56485. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  56486. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  56487. if (index > -1) {
  56488. this._meshesWithPoseMatrix.splice(index, 1);
  56489. }
  56490. };
  56491. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  56492. this.onBeforeComputeObservable.notifyObservers(this);
  56493. for (var index = 0; index < this.bones.length; index++) {
  56494. var bone = this.bones[index];
  56495. var parentBone = bone.getParent();
  56496. if (parentBone) {
  56497. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  56498. }
  56499. else {
  56500. if (initialSkinMatrix) {
  56501. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  56502. }
  56503. else {
  56504. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  56505. }
  56506. }
  56507. if (bone._index !== -1) {
  56508. var mappedIndex = bone._index === undefined ? index : bone._index;
  56509. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  56510. }
  56511. }
  56512. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  56513. };
  56514. Skeleton.prototype.prepare = function () {
  56515. if (!this._isDirty) {
  56516. return;
  56517. }
  56518. if (this.needInitialSkinMatrix) {
  56519. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  56520. var mesh = this._meshesWithPoseMatrix[index];
  56521. var poseMatrix = mesh.getPoseMatrix();
  56522. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  56523. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  56524. }
  56525. if (this._synchronizedWithMesh !== mesh) {
  56526. this._synchronizedWithMesh = mesh;
  56527. // Prepare bones
  56528. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  56529. var bone = this.bones[boneIndex];
  56530. if (!bone.getParent()) {
  56531. var matrix = bone.getBaseMatrix();
  56532. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  56533. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  56534. }
  56535. }
  56536. }
  56537. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  56538. }
  56539. }
  56540. else {
  56541. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  56542. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  56543. }
  56544. this._computeTransformMatrices(this._transformMatrices, null);
  56545. }
  56546. this._isDirty = false;
  56547. this._scene._activeBones.addCount(this.bones.length, false);
  56548. };
  56549. Skeleton.prototype.getAnimatables = function () {
  56550. if (!this._animatables || this._animatables.length !== this.bones.length) {
  56551. this._animatables = [];
  56552. for (var index = 0; index < this.bones.length; index++) {
  56553. this._animatables.push(this.bones[index]);
  56554. }
  56555. }
  56556. return this._animatables;
  56557. };
  56558. Skeleton.prototype.clone = function (name, id) {
  56559. var result = new Skeleton(name, id || name, this._scene);
  56560. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  56561. for (var index = 0; index < this.bones.length; index++) {
  56562. var source = this.bones[index];
  56563. var parentBone = null;
  56564. if (source.getParent()) {
  56565. var parentIndex = this.bones.indexOf(source.getParent());
  56566. parentBone = result.bones[parentIndex];
  56567. }
  56568. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  56569. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  56570. }
  56571. if (this._ranges) {
  56572. result._ranges = {};
  56573. for (var rangeName in this._ranges) {
  56574. result._ranges[rangeName] = this._ranges[rangeName].clone();
  56575. }
  56576. }
  56577. this._isDirty = true;
  56578. return result;
  56579. };
  56580. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  56581. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  56582. this.bones.forEach(function (bone) {
  56583. bone.animations.forEach(function (animation) {
  56584. animation.enableBlending = true;
  56585. animation.blendingSpeed = blendingSpeed;
  56586. });
  56587. });
  56588. };
  56589. Skeleton.prototype.dispose = function () {
  56590. this._meshesWithPoseMatrix = [];
  56591. // Animations
  56592. this.getScene().stopAnimation(this);
  56593. // Remove from scene
  56594. this.getScene().removeSkeleton(this);
  56595. };
  56596. Skeleton.prototype.serialize = function () {
  56597. var serializationObject = {};
  56598. serializationObject.name = this.name;
  56599. serializationObject.id = this.id;
  56600. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  56601. serializationObject.bones = [];
  56602. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  56603. for (var index = 0; index < this.bones.length; index++) {
  56604. var bone = this.bones[index];
  56605. var serializedBone = {
  56606. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  56607. name: bone.name,
  56608. matrix: bone.getBaseMatrix().toArray(),
  56609. rest: bone.getRestPose().toArray()
  56610. };
  56611. serializationObject.bones.push(serializedBone);
  56612. if (bone.length) {
  56613. serializedBone.length = bone.length;
  56614. }
  56615. if (bone.animations && bone.animations.length > 0) {
  56616. serializedBone.animation = bone.animations[0].serialize();
  56617. }
  56618. serializationObject.ranges = [];
  56619. for (var name in this._ranges) {
  56620. var range = {};
  56621. range.name = name;
  56622. range.from = this._ranges[name].from;
  56623. range.to = this._ranges[name].to;
  56624. serializationObject.ranges.push(range);
  56625. }
  56626. }
  56627. return serializationObject;
  56628. };
  56629. Skeleton.Parse = function (parsedSkeleton, scene) {
  56630. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  56631. if (parsedSkeleton.dimensionsAtRest) {
  56632. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  56633. }
  56634. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  56635. var index;
  56636. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  56637. var parsedBone = parsedSkeleton.bones[index];
  56638. var parentBone = null;
  56639. if (parsedBone.parentBoneIndex > -1) {
  56640. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  56641. }
  56642. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  56643. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  56644. if (parsedBone.length) {
  56645. bone.length = parsedBone.length;
  56646. }
  56647. if (parsedBone.animation) {
  56648. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  56649. }
  56650. }
  56651. // placed after bones, so createAnimationRange can cascade down
  56652. if (parsedSkeleton.ranges) {
  56653. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  56654. var data = parsedSkeleton.ranges[index];
  56655. skeleton.createAnimationRange(data.name, data.from, data.to);
  56656. }
  56657. }
  56658. return skeleton;
  56659. };
  56660. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  56661. if (forceUpdate === void 0) { forceUpdate = false; }
  56662. var renderId = this._scene.getRenderId();
  56663. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  56664. this.bones[0].computeAbsoluteTransforms();
  56665. this._lastAbsoluteTransformsUpdateId = renderId;
  56666. }
  56667. };
  56668. Skeleton.prototype.getPoseMatrix = function () {
  56669. var poseMatrix;
  56670. if (this._meshesWithPoseMatrix.length > 0) {
  56671. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  56672. }
  56673. return poseMatrix;
  56674. };
  56675. Skeleton.prototype.sortBones = function () {
  56676. var bones = new Array();
  56677. var visited = new Array(this.bones.length);
  56678. for (var index = 0; index < this.bones.length; index++) {
  56679. this._sortBones(index, bones, visited);
  56680. }
  56681. this.bones = bones;
  56682. };
  56683. Skeleton.prototype._sortBones = function (index, bones, visited) {
  56684. if (visited[index]) {
  56685. return;
  56686. }
  56687. visited[index] = true;
  56688. var bone = this.bones[index];
  56689. if (bone._index === undefined) {
  56690. bone._index = index;
  56691. }
  56692. var parentBone = bone.getParent();
  56693. if (parentBone) {
  56694. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  56695. }
  56696. bones.push(bone);
  56697. };
  56698. return Skeleton;
  56699. }());
  56700. BABYLON.Skeleton = Skeleton;
  56701. })(BABYLON || (BABYLON = {}));
  56702. //# sourceMappingURL=babylon.skeleton.js.map
  56703. var BABYLON;
  56704. (function (BABYLON) {
  56705. var SphericalPolynomial = (function () {
  56706. function SphericalPolynomial() {
  56707. this.x = BABYLON.Vector3.Zero();
  56708. this.y = BABYLON.Vector3.Zero();
  56709. this.z = BABYLON.Vector3.Zero();
  56710. this.xx = BABYLON.Vector3.Zero();
  56711. this.yy = BABYLON.Vector3.Zero();
  56712. this.zz = BABYLON.Vector3.Zero();
  56713. this.xy = BABYLON.Vector3.Zero();
  56714. this.yz = BABYLON.Vector3.Zero();
  56715. this.zx = BABYLON.Vector3.Zero();
  56716. }
  56717. SphericalPolynomial.prototype.addAmbient = function (color) {
  56718. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  56719. this.xx = this.xx.add(colorVector);
  56720. this.yy = this.yy.add(colorVector);
  56721. this.zz = this.zz.add(colorVector);
  56722. };
  56723. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  56724. var result = new SphericalPolynomial();
  56725. result.x = harmonics.L11.scale(1.02333);
  56726. result.y = harmonics.L1_1.scale(1.02333);
  56727. result.z = harmonics.L10.scale(1.02333);
  56728. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  56729. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  56730. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  56731. result.yz = harmonics.L2_1.scale(0.858086);
  56732. result.zx = harmonics.L21.scale(0.858086);
  56733. result.xy = harmonics.L2_2.scale(0.858086);
  56734. result.scale(1.0 / Math.PI);
  56735. return result;
  56736. };
  56737. SphericalPolynomial.prototype.scale = function (scale) {
  56738. this.x = this.x.scale(scale);
  56739. this.y = this.y.scale(scale);
  56740. this.z = this.z.scale(scale);
  56741. this.xx = this.xx.scale(scale);
  56742. this.yy = this.yy.scale(scale);
  56743. this.zz = this.zz.scale(scale);
  56744. this.yz = this.yz.scale(scale);
  56745. this.zx = this.zx.scale(scale);
  56746. this.xy = this.xy.scale(scale);
  56747. };
  56748. return SphericalPolynomial;
  56749. }());
  56750. BABYLON.SphericalPolynomial = SphericalPolynomial;
  56751. var SphericalHarmonics = (function () {
  56752. function SphericalHarmonics() {
  56753. this.L00 = BABYLON.Vector3.Zero();
  56754. this.L1_1 = BABYLON.Vector3.Zero();
  56755. this.L10 = BABYLON.Vector3.Zero();
  56756. this.L11 = BABYLON.Vector3.Zero();
  56757. this.L2_2 = BABYLON.Vector3.Zero();
  56758. this.L2_1 = BABYLON.Vector3.Zero();
  56759. this.L20 = BABYLON.Vector3.Zero();
  56760. this.L21 = BABYLON.Vector3.Zero();
  56761. this.L22 = BABYLON.Vector3.Zero();
  56762. }
  56763. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  56764. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  56765. var c = colorVector.scale(deltaSolidAngle);
  56766. this.L00 = this.L00.add(c.scale(0.282095));
  56767. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  56768. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  56769. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  56770. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  56771. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  56772. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  56773. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  56774. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  56775. };
  56776. SphericalHarmonics.prototype.scale = function (scale) {
  56777. this.L00 = this.L00.scale(scale);
  56778. this.L1_1 = this.L1_1.scale(scale);
  56779. this.L10 = this.L10.scale(scale);
  56780. this.L11 = this.L11.scale(scale);
  56781. this.L2_2 = this.L2_2.scale(scale);
  56782. this.L2_1 = this.L2_1.scale(scale);
  56783. this.L20 = this.L20.scale(scale);
  56784. this.L21 = this.L21.scale(scale);
  56785. this.L22 = this.L22.scale(scale);
  56786. };
  56787. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  56788. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  56789. //
  56790. // E_lm = A_l * L_lm
  56791. //
  56792. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  56793. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  56794. // the scaling factors are given in equation 9.
  56795. // Constant (Band 0)
  56796. this.L00 = this.L00.scale(3.141593);
  56797. // Linear (Band 1)
  56798. this.L1_1 = this.L1_1.scale(2.094395);
  56799. this.L10 = this.L10.scale(2.094395);
  56800. this.L11 = this.L11.scale(2.094395);
  56801. // Quadratic (Band 2)
  56802. this.L2_2 = this.L2_2.scale(0.785398);
  56803. this.L2_1 = this.L2_1.scale(0.785398);
  56804. this.L20 = this.L20.scale(0.785398);
  56805. this.L21 = this.L21.scale(0.785398);
  56806. this.L22 = this.L22.scale(0.785398);
  56807. };
  56808. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  56809. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  56810. // L = (1/pi) * E * rho
  56811. //
  56812. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  56813. this.scale(1.0 / Math.PI);
  56814. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  56815. // (The pixel shader must apply albedo after texture fetches, etc).
  56816. };
  56817. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  56818. var result = new SphericalHarmonics();
  56819. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  56820. result.L1_1 = polynomial.y.scale(0.977204);
  56821. result.L10 = polynomial.z.scale(0.977204);
  56822. result.L11 = polynomial.x.scale(0.977204);
  56823. result.L2_2 = polynomial.xy.scale(1.16538);
  56824. result.L2_1 = polynomial.yz.scale(1.16538);
  56825. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  56826. result.L21 = polynomial.zx.scale(1.16538);
  56827. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  56828. result.scale(Math.PI);
  56829. return result;
  56830. };
  56831. return SphericalHarmonics;
  56832. }());
  56833. BABYLON.SphericalHarmonics = SphericalHarmonics;
  56834. })(BABYLON || (BABYLON = {}));
  56835. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  56836. var BABYLON;
  56837. (function (BABYLON) {
  56838. var Internals;
  56839. (function (Internals) {
  56840. var FileFaceOrientation = (function () {
  56841. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56842. this.name = name;
  56843. this.worldAxisForNormal = worldAxisForNormal;
  56844. this.worldAxisForFileX = worldAxisForFileX;
  56845. this.worldAxisForFileY = worldAxisForFileY;
  56846. }
  56847. return FileFaceOrientation;
  56848. }());
  56849. ;
  56850. /**
  56851. * Helper class dealing with the extraction of spherical polynomial dataArray
  56852. * from a cube map.
  56853. */
  56854. var CubeMapToSphericalPolynomialTools = (function () {
  56855. function CubeMapToSphericalPolynomialTools() {
  56856. }
  56857. /**
  56858. * Converts a texture to the according Spherical Polynomial data.
  56859. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56860. *
  56861. * @param texture The texture to extract the information from.
  56862. * @return The Spherical Polynomial data.
  56863. */
  56864. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  56865. if (!texture.isCube) {
  56866. // Only supports cube Textures currently.
  56867. return null;
  56868. }
  56869. var size = texture.getSize().width;
  56870. var right = texture.readPixels(0);
  56871. var left = texture.readPixels(1);
  56872. var up;
  56873. var down;
  56874. if (texture.isRenderTarget) {
  56875. up = texture.readPixels(3);
  56876. down = texture.readPixels(2);
  56877. }
  56878. else {
  56879. up = texture.readPixels(2);
  56880. down = texture.readPixels(3);
  56881. }
  56882. var front = texture.readPixels(4);
  56883. var back = texture.readPixels(5);
  56884. var gammaSpace = texture.gammaSpace;
  56885. // Always read as RGBA.
  56886. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  56887. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56888. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56889. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56890. }
  56891. var cubeInfo = {
  56892. size: size,
  56893. right: right,
  56894. left: left,
  56895. up: up,
  56896. down: down,
  56897. front: front,
  56898. back: back,
  56899. format: format,
  56900. type: type,
  56901. gammaSpace: gammaSpace,
  56902. };
  56903. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  56904. };
  56905. /**
  56906. * Converts a cubemap to the according Spherical Polynomial data.
  56907. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56908. *
  56909. * @param cubeInfo The Cube map to extract the information from.
  56910. * @return The Spherical Polynomial data.
  56911. */
  56912. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56913. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56914. var totalSolidAngle = 0.0;
  56915. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56916. var du = 2.0 / cubeInfo.size;
  56917. var dv = du;
  56918. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56919. var minUV = du * 0.5 - 1.0;
  56920. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56921. var fileFace = this.FileFaces[faceIndex];
  56922. var dataArray = cubeInfo[fileFace.name];
  56923. var v = minUV;
  56924. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56925. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56926. // Because SP is still linear, so summation is fine in that basis.
  56927. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  56928. for (var y = 0; y < cubeInfo.size; y++) {
  56929. var u = minUV;
  56930. for (var x = 0; x < cubeInfo.size; x++) {
  56931. // World direction (not normalised)
  56932. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56933. worldDirection.normalize();
  56934. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56935. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  56936. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  56937. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  56938. // Handle Integer types.
  56939. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56940. r /= 255;
  56941. g /= 255;
  56942. b /= 255;
  56943. }
  56944. // Handle Gamma space textures.
  56945. if (cubeInfo.gammaSpace) {
  56946. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  56947. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  56948. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  56949. }
  56950. var color = new BABYLON.Color3(r, g, b);
  56951. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56952. totalSolidAngle += deltaSolidAngle;
  56953. u += du;
  56954. }
  56955. v += dv;
  56956. }
  56957. }
  56958. // Solid angle for entire sphere is 4*pi
  56959. var sphereSolidAngle = 4.0 * Math.PI;
  56960. // Adjust the solid angle to allow for how many faces we processed.
  56961. var facesProcessed = 6.0;
  56962. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  56963. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  56964. // This is needed because the numerical integration over the cube uses a
  56965. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  56966. // and also to compensate for accumulative error due to float precision in the summation.
  56967. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  56968. sphericalHarmonics.scale(correctionFactor);
  56969. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  56970. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  56971. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56972. };
  56973. CubeMapToSphericalPolynomialTools.FileFaces = [
  56974. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56975. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56976. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56977. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56978. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56979. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56980. ];
  56981. return CubeMapToSphericalPolynomialTools;
  56982. }());
  56983. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56984. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56985. })(BABYLON || (BABYLON = {}));
  56986. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  56987. var BABYLON;
  56988. (function (BABYLON) {
  56989. var Internals;
  56990. (function (Internals) {
  56991. /**
  56992. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56993. */
  56994. var PanoramaToCubeMapTools = (function () {
  56995. function PanoramaToCubeMapTools() {
  56996. }
  56997. /**
  56998. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56999. *
  57000. * @param float32Array The source data.
  57001. * @param inputWidth The width of the input panorama.
  57002. * @param inputhHeight The height of the input panorama.
  57003. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57004. * @return The cubemap data
  57005. */
  57006. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57007. if (!float32Array) {
  57008. throw "ConvertPanoramaToCubemap: input cannot be null";
  57009. }
  57010. if (float32Array.length != inputWidth * inputHeight * 3) {
  57011. throw "ConvertPanoramaToCubemap: input size is wrong";
  57012. }
  57013. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57014. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57015. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57016. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57017. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57018. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57019. return {
  57020. front: textureFront,
  57021. back: textureBack,
  57022. left: textureLeft,
  57023. right: textureRight,
  57024. up: textureUp,
  57025. down: textureDown,
  57026. size: size,
  57027. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  57028. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  57029. gammaSpace: false,
  57030. };
  57031. };
  57032. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57033. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57034. var textureArray = new Float32Array(buffer);
  57035. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57036. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57037. var dy = 1 / texSize;
  57038. var fy = 0;
  57039. for (var y = 0; y < texSize; y++) {
  57040. var xv1 = faceData[0];
  57041. var xv2 = faceData[2];
  57042. for (var x = 0; x < texSize; x++) {
  57043. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57044. v.normalize();
  57045. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57046. // 3 channels per pixels
  57047. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57048. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57049. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57050. xv1 = xv1.add(rotDX1);
  57051. xv2 = xv2.add(rotDX2);
  57052. }
  57053. fy += dy;
  57054. }
  57055. return textureArray;
  57056. };
  57057. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57058. var theta = Math.atan2(vDir.z, vDir.x);
  57059. var phi = Math.acos(vDir.y);
  57060. while (theta < -Math.PI)
  57061. theta += 2 * Math.PI;
  57062. while (theta > Math.PI)
  57063. theta -= 2 * Math.PI;
  57064. var dx = theta / Math.PI;
  57065. var dy = phi / Math.PI;
  57066. // recenter.
  57067. dx = dx * 0.5 + 0.5;
  57068. var px = Math.round(dx * inputWidth);
  57069. if (px < 0)
  57070. px = 0;
  57071. else if (px >= inputWidth)
  57072. px = inputWidth - 1;
  57073. var py = Math.round(dy * inputHeight);
  57074. if (py < 0)
  57075. py = 0;
  57076. else if (py >= inputHeight)
  57077. py = inputHeight - 1;
  57078. var inputY = (inputHeight - py - 1);
  57079. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57080. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57081. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57082. return {
  57083. r: r,
  57084. g: g,
  57085. b: b
  57086. };
  57087. };
  57088. PanoramaToCubeMapTools.FACE_FRONT = [
  57089. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57090. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57091. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57092. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57093. ];
  57094. PanoramaToCubeMapTools.FACE_BACK = [
  57095. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57096. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57097. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57098. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57099. ];
  57100. PanoramaToCubeMapTools.FACE_RIGHT = [
  57101. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57102. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57103. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57104. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57105. ];
  57106. PanoramaToCubeMapTools.FACE_LEFT = [
  57107. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57108. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57109. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57110. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57111. ];
  57112. PanoramaToCubeMapTools.FACE_DOWN = [
  57113. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57114. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57115. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57116. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57117. ];
  57118. PanoramaToCubeMapTools.FACE_UP = [
  57119. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57120. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57121. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57122. new BABYLON.Vector3(1.0, -1.0, -1.0)
  57123. ];
  57124. return PanoramaToCubeMapTools;
  57125. }());
  57126. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  57127. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57128. })(BABYLON || (BABYLON = {}));
  57129. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  57130. var BABYLON;
  57131. (function (BABYLON) {
  57132. var Internals;
  57133. (function (Internals) {
  57134. ;
  57135. /**
  57136. * This groups tools to convert HDR texture to native colors array.
  57137. */
  57138. var HDRTools = (function () {
  57139. function HDRTools() {
  57140. }
  57141. HDRTools.Ldexp = function (mantissa, exponent) {
  57142. if (exponent > 1023) {
  57143. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57144. }
  57145. if (exponent < -1074) {
  57146. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57147. }
  57148. return mantissa * Math.pow(2, exponent);
  57149. };
  57150. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57151. if (exponent > 0) {
  57152. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57153. float32array[index + 0] = red * exponent;
  57154. float32array[index + 1] = green * exponent;
  57155. float32array[index + 2] = blue * exponent;
  57156. }
  57157. else {
  57158. float32array[index + 0] = 0;
  57159. float32array[index + 1] = 0;
  57160. float32array[index + 2] = 0;
  57161. }
  57162. };
  57163. HDRTools.readStringLine = function (uint8array, startIndex) {
  57164. var line = "";
  57165. var character = "";
  57166. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57167. character = String.fromCharCode(uint8array[i]);
  57168. if (character == "\n") {
  57169. break;
  57170. }
  57171. line += character;
  57172. }
  57173. return line;
  57174. };
  57175. /**
  57176. * Reads header information from an RGBE texture stored in a native array.
  57177. * More information on this format are available here:
  57178. * https://en.wikipedia.org/wiki/RGBE_image_format
  57179. *
  57180. * @param uint8array The binary file stored in native array.
  57181. * @return The header information.
  57182. */
  57183. HDRTools.RGBE_ReadHeader = function (uint8array) {
  57184. var height = 0;
  57185. var width = 0;
  57186. var line = this.readStringLine(uint8array, 0);
  57187. if (line[0] != '#' || line[1] != '?') {
  57188. throw "Bad HDR Format.";
  57189. }
  57190. var endOfHeader = false;
  57191. var findFormat = false;
  57192. var lineIndex = 0;
  57193. do {
  57194. lineIndex += (line.length + 1);
  57195. line = this.readStringLine(uint8array, lineIndex);
  57196. if (line == "FORMAT=32-bit_rle_rgbe") {
  57197. findFormat = true;
  57198. }
  57199. else if (line.length == 0) {
  57200. endOfHeader = true;
  57201. }
  57202. } while (!endOfHeader);
  57203. if (!findFormat) {
  57204. throw "HDR Bad header format, unsupported FORMAT";
  57205. }
  57206. lineIndex += (line.length + 1);
  57207. line = this.readStringLine(uint8array, lineIndex);
  57208. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  57209. var match = sizeRegexp.exec(line);
  57210. // TODO. Support +Y and -X if needed.
  57211. if (match.length < 3) {
  57212. throw "HDR Bad header format, no size";
  57213. }
  57214. width = parseInt(match[2]);
  57215. height = parseInt(match[1]);
  57216. if (width < 8 || width > 0x7fff) {
  57217. throw "HDR Bad header format, unsupported size";
  57218. }
  57219. lineIndex += (line.length + 1);
  57220. return {
  57221. height: height,
  57222. width: width,
  57223. dataPosition: lineIndex
  57224. };
  57225. };
  57226. /**
  57227. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  57228. * This RGBE texture needs to store the information as a panorama.
  57229. *
  57230. * More information on this format are available here:
  57231. * https://en.wikipedia.org/wiki/RGBE_image_format
  57232. *
  57233. * @param buffer The binary file stored in an array buffer.
  57234. * @param size The expected size of the extracted cubemap.
  57235. * @return The Cube Map information.
  57236. */
  57237. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  57238. var uint8array = new Uint8Array(buffer);
  57239. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  57240. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57241. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  57242. return cubeMapData;
  57243. };
  57244. /**
  57245. * Returns the pixels data extracted from an RGBE texture.
  57246. * This pixels will be stored left to right up to down in the R G B order in one array.
  57247. *
  57248. * More information on this format are available here:
  57249. * https://en.wikipedia.org/wiki/RGBE_image_format
  57250. *
  57251. * @param uint8array The binary file stored in an array buffer.
  57252. * @param hdrInfo The header information of the file.
  57253. * @return The pixels data in RGB right to left up to down order.
  57254. */
  57255. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  57256. // Keep for multi format supports.
  57257. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57258. };
  57259. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  57260. var num_scanlines = hdrInfo.height;
  57261. var scanline_width = hdrInfo.width;
  57262. var a, b, c, d, count;
  57263. var dataIndex = hdrInfo.dataPosition;
  57264. var index = 0, endIndex = 0, i = 0;
  57265. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  57266. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  57267. // 3 channels of 4 bytes per pixel in float.
  57268. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  57269. var resultArray = new Float32Array(resultBuffer);
  57270. // read in each successive scanline
  57271. while (num_scanlines > 0) {
  57272. a = uint8array[dataIndex++];
  57273. b = uint8array[dataIndex++];
  57274. c = uint8array[dataIndex++];
  57275. d = uint8array[dataIndex++];
  57276. if (a != 2 || b != 2 || (c & 0x80)) {
  57277. // this file is not run length encoded
  57278. throw "HDR Bad header format, not RLE";
  57279. }
  57280. if (((c << 8) | d) != scanline_width) {
  57281. throw "HDR Bad header format, wrong scan line width";
  57282. }
  57283. index = 0;
  57284. // read each of the four channels for the scanline into the buffer
  57285. for (i = 0; i < 4; i++) {
  57286. endIndex = (i + 1) * scanline_width;
  57287. while (index < endIndex) {
  57288. a = uint8array[dataIndex++];
  57289. b = uint8array[dataIndex++];
  57290. if (a > 128) {
  57291. // a run of the same value
  57292. count = a - 128;
  57293. if ((count == 0) || (count > endIndex - index)) {
  57294. throw "HDR Bad Format, bad scanline data (run)";
  57295. }
  57296. while (count-- > 0) {
  57297. scanLineArray[index++] = b;
  57298. }
  57299. }
  57300. else {
  57301. // a non-run
  57302. count = a;
  57303. if ((count == 0) || (count > endIndex - index)) {
  57304. throw "HDR Bad Format, bad scanline data (non-run)";
  57305. }
  57306. scanLineArray[index++] = b;
  57307. if (--count > 0) {
  57308. for (var j = 0; j < count; j++) {
  57309. scanLineArray[index++] = uint8array[dataIndex++];
  57310. }
  57311. }
  57312. }
  57313. }
  57314. }
  57315. // now convert data from buffer into floats
  57316. for (i = 0; i < scanline_width; i++) {
  57317. a = scanLineArray[i];
  57318. b = scanLineArray[i + scanline_width];
  57319. c = scanLineArray[i + 2 * scanline_width];
  57320. d = scanLineArray[i + 3 * scanline_width];
  57321. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57322. }
  57323. num_scanlines--;
  57324. }
  57325. return resultArray;
  57326. };
  57327. return HDRTools;
  57328. }());
  57329. Internals.HDRTools = HDRTools;
  57330. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57331. })(BABYLON || (BABYLON = {}));
  57332. //# sourceMappingURL=babylon.hdr.js.map
  57333. var BABYLON;
  57334. (function (BABYLON) {
  57335. /**
  57336. * This represents a texture coming from an HDR input.
  57337. *
  57338. * The only supported format is currently panorama picture stored in RGBE format.
  57339. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57340. */
  57341. var HDRCubeTexture = (function (_super) {
  57342. __extends(HDRCubeTexture, _super);
  57343. /**
  57344. * Instantiates an HDRTexture from the following parameters.
  57345. *
  57346. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57347. * @param scene The scene the texture will be used in
  57348. * @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.
  57349. * @param noMipmap Forces to not generate the mipmap if true
  57350. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57351. * @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)
  57352. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57353. */
  57354. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  57355. if (noMipmap === void 0) { noMipmap = false; }
  57356. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57357. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57358. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57359. if (onLoad === void 0) { onLoad = null; }
  57360. if (onError === void 0) { onError = null; }
  57361. var _this = _super.call(this, scene) || this;
  57362. _this._useInGammaSpace = false;
  57363. _this._generateHarmonics = true;
  57364. _this._isBABYLONPreprocessed = false;
  57365. _this._onLoad = null;
  57366. _this._onError = null;
  57367. /**
  57368. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57369. */
  57370. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57371. /**
  57372. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57373. * This is usefull at run time to apply the good shader.
  57374. */
  57375. _this.isPMREM = false;
  57376. _this._isBlocking = true;
  57377. if (!url) {
  57378. return _this;
  57379. }
  57380. _this.name = url;
  57381. _this.url = url;
  57382. _this.hasAlpha = false;
  57383. _this.isCube = true;
  57384. _this._textureMatrix = BABYLON.Matrix.Identity();
  57385. _this._onLoad = onLoad;
  57386. _this._onError = onError;
  57387. _this.gammaSpace = false;
  57388. if (size) {
  57389. _this._isBABYLONPreprocessed = false;
  57390. _this._noMipmap = noMipmap;
  57391. _this._size = size;
  57392. _this._useInGammaSpace = useInGammaSpace;
  57393. _this._usePMREMGenerator = usePMREMGenerator &&
  57394. scene.getEngine().getCaps().textureLOD &&
  57395. _this.getScene().getEngine().getCaps().textureFloat &&
  57396. !_this._useInGammaSpace;
  57397. }
  57398. else {
  57399. _this._isBABYLONPreprocessed = true;
  57400. _this._noMipmap = false;
  57401. _this._useInGammaSpace = false;
  57402. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57403. _this.getScene().getEngine().getCaps().textureFloat &&
  57404. !_this._useInGammaSpace;
  57405. }
  57406. _this.isPMREM = _this._usePMREMGenerator;
  57407. _this._texture = _this._getFromCache(url, _this._noMipmap);
  57408. if (!_this._texture) {
  57409. if (!scene.useDelayedTextureLoading) {
  57410. _this.loadTexture();
  57411. }
  57412. else {
  57413. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57414. }
  57415. }
  57416. return _this;
  57417. }
  57418. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  57419. /**
  57420. * Gets wether or not the texture is blocking during loading.
  57421. */
  57422. get: function () {
  57423. return this._isBlocking;
  57424. },
  57425. /**
  57426. * Sets wether or not the texture is blocking during loading.
  57427. */
  57428. set: function (value) {
  57429. this._isBlocking = value;
  57430. },
  57431. enumerable: true,
  57432. configurable: true
  57433. });
  57434. /**
  57435. * Occurs when the file is a preprocessed .babylon.hdr file.
  57436. */
  57437. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57438. var _this = this;
  57439. var mipLevels = 0;
  57440. var floatArrayView = null;
  57441. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57442. var mips = [];
  57443. var startIndex = 30;
  57444. for (var level = 0; level < mipLevels; level++) {
  57445. mips.push([]);
  57446. // Fill each pixel of the mip level.
  57447. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57448. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57449. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57450. mips[level].push(faceData);
  57451. startIndex += faceSize;
  57452. }
  57453. }
  57454. return mips;
  57455. } : null;
  57456. var callback = function (buffer) {
  57457. // Create Native Array Views
  57458. var intArrayView = new Int32Array(buffer);
  57459. floatArrayView = new Float32Array(buffer);
  57460. // Fill header.
  57461. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57462. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57463. // Update Texture Information.
  57464. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  57465. // Fill polynomial information.
  57466. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57467. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57468. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57469. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57470. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57471. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57472. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57473. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57474. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57475. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57476. _this.sphericalPolynomial = sphericalPolynomial;
  57477. // Fill pixel data.
  57478. mipLevels = intArrayView[29]; // Number of mip levels.
  57479. var startIndex = 30;
  57480. var data = [];
  57481. var faceSize = Math.pow(_this._size, 2) * 3;
  57482. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57483. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57484. startIndex += faceSize;
  57485. }
  57486. var results = [];
  57487. var byteArray = null;
  57488. // Push each faces.
  57489. for (var k = 0; k < 6; k++) {
  57490. var dataFace = null;
  57491. // To be deprecated.
  57492. if (version === 1) {
  57493. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  57494. dataFace = data[j];
  57495. }
  57496. // If special cases.
  57497. if (!mipmapGenerator) {
  57498. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57499. // 3 channels of 1 bytes per pixel in bytes.
  57500. var byteBuffer = new ArrayBuffer(faceSize);
  57501. byteArray = new Uint8Array(byteBuffer);
  57502. }
  57503. for (var i = 0; i < _this._size * _this._size; i++) {
  57504. // Put in gamma space if requested.
  57505. if (_this._useInGammaSpace) {
  57506. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57507. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57508. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57509. }
  57510. // Convert to int texture for fallback.
  57511. if (byteArray) {
  57512. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57513. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57514. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57515. // May use luminance instead if the result is not accurate.
  57516. var max = Math.max(Math.max(r, g), b);
  57517. if (max > 255) {
  57518. var scale = 255 / max;
  57519. r *= scale;
  57520. g *= scale;
  57521. b *= scale;
  57522. }
  57523. byteArray[(i * 3) + 0] = r;
  57524. byteArray[(i * 3) + 1] = g;
  57525. byteArray[(i * 3) + 2] = b;
  57526. }
  57527. }
  57528. }
  57529. // Fill the array accordingly.
  57530. if (byteArray) {
  57531. results.push(byteArray);
  57532. }
  57533. else {
  57534. results.push(dataFace);
  57535. }
  57536. }
  57537. return results;
  57538. };
  57539. 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);
  57540. };
  57541. /**
  57542. * Occurs when the file is raw .hdr file.
  57543. */
  57544. HDRCubeTexture.prototype.loadHDRTexture = function () {
  57545. var _this = this;
  57546. var callback = function (buffer) {
  57547. // Extract the raw linear data.
  57548. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  57549. // Generate harmonics if needed.
  57550. if (_this._generateHarmonics) {
  57551. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  57552. _this.sphericalPolynomial = sphericalPolynomial;
  57553. }
  57554. var results = [];
  57555. var byteArray = null;
  57556. // Push each faces.
  57557. for (var j = 0; j < 6; j++) {
  57558. // Create uintarray fallback.
  57559. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57560. // 3 channels of 1 bytes per pixel in bytes.
  57561. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  57562. byteArray = new Uint8Array(byteBuffer);
  57563. }
  57564. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  57565. // If special cases.
  57566. if (_this._useInGammaSpace || byteArray) {
  57567. for (var i = 0; i < _this._size * _this._size; i++) {
  57568. // Put in gamma space if requested.
  57569. if (_this._useInGammaSpace) {
  57570. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57571. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57572. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57573. }
  57574. // Convert to int texture for fallback.
  57575. if (byteArray) {
  57576. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57577. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57578. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57579. // May use luminance instead if the result is not accurate.
  57580. var max = Math.max(Math.max(r, g), b);
  57581. if (max > 255) {
  57582. var scale = 255 / max;
  57583. r *= scale;
  57584. g *= scale;
  57585. b *= scale;
  57586. }
  57587. byteArray[(i * 3) + 0] = r;
  57588. byteArray[(i * 3) + 1] = g;
  57589. byteArray[(i * 3) + 2] = b;
  57590. }
  57591. }
  57592. }
  57593. if (byteArray) {
  57594. results.push(byteArray);
  57595. }
  57596. else {
  57597. results.push(dataFace);
  57598. }
  57599. }
  57600. return results;
  57601. };
  57602. var mipmapGenerator = null;
  57603. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  57604. // if (!this._noMipmap &&
  57605. // this._usePMREMGenerator) {
  57606. // mipmapGenerator = (data: ArrayBufferView[]) => {
  57607. // // Custom setup of the generator matching with the PBR shader values.
  57608. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  57609. // this._size,
  57610. // this._size,
  57611. // 0,
  57612. // 3,
  57613. // this.getScene().getEngine().getCaps().textureFloat,
  57614. // 2048,
  57615. // 0.25,
  57616. // false,
  57617. // true);
  57618. // return generator.filterCubeMap();
  57619. // };
  57620. // }
  57621. 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);
  57622. };
  57623. /**
  57624. * Starts the loading process of the texture.
  57625. */
  57626. HDRCubeTexture.prototype.loadTexture = function () {
  57627. if (this._isBABYLONPreprocessed) {
  57628. this.loadBabylonTexture();
  57629. }
  57630. else {
  57631. this.loadHDRTexture();
  57632. }
  57633. };
  57634. HDRCubeTexture.prototype.clone = function () {
  57635. var size = this._isBABYLONPreprocessed ? null : this._size;
  57636. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  57637. // Base texture
  57638. newTexture.level = this.level;
  57639. newTexture.wrapU = this.wrapU;
  57640. newTexture.wrapV = this.wrapV;
  57641. newTexture.coordinatesIndex = this.coordinatesIndex;
  57642. newTexture.coordinatesMode = this.coordinatesMode;
  57643. return newTexture;
  57644. };
  57645. // Methods
  57646. HDRCubeTexture.prototype.delayLoad = function () {
  57647. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57648. return;
  57649. }
  57650. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57651. this._texture = this._getFromCache(this.url, this._noMipmap);
  57652. if (!this._texture) {
  57653. this.loadTexture();
  57654. }
  57655. };
  57656. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  57657. return this._textureMatrix;
  57658. };
  57659. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57660. this._textureMatrix = value;
  57661. };
  57662. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57663. var texture = null;
  57664. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57665. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  57666. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  57667. texture.name = parsedTexture.name;
  57668. texture.hasAlpha = parsedTexture.hasAlpha;
  57669. texture.level = parsedTexture.level;
  57670. texture.coordinatesMode = parsedTexture.coordinatesMode;
  57671. texture.isBlocking = parsedTexture.isBlocking;
  57672. }
  57673. return texture;
  57674. };
  57675. HDRCubeTexture.prototype.serialize = function () {
  57676. if (!this.name) {
  57677. return null;
  57678. }
  57679. var serializationObject = {};
  57680. serializationObject.name = this.name;
  57681. serializationObject.hasAlpha = this.hasAlpha;
  57682. serializationObject.isCube = true;
  57683. serializationObject.level = this.level;
  57684. serializationObject.size = this._size;
  57685. serializationObject.coordinatesMode = this.coordinatesMode;
  57686. serializationObject.useInGammaSpace = this._useInGammaSpace;
  57687. serializationObject.generateHarmonics = this._generateHarmonics;
  57688. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  57689. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  57690. serializationObject.customType = "BABYLON.HDRCubeTexture";
  57691. serializationObject.noMipmap = this._noMipmap;
  57692. serializationObject.isBlocking = this._isBlocking;
  57693. return serializationObject;
  57694. };
  57695. /**
  57696. * Saves as a file the data contained in the texture in a binary format.
  57697. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57698. * as the spherical used in the lighting.
  57699. * @param url The HDR file url.
  57700. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57701. * @param onError Method called if any error happens during download.
  57702. * @return The packed binary data.
  57703. */
  57704. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  57705. if (onError === void 0) { onError = null; }
  57706. var callback = function (buffer) {
  57707. var data = new Blob([buffer], { type: 'application/octet-stream' });
  57708. // Returns a URL you can use as a href.
  57709. var objUrl = window.URL.createObjectURL(data);
  57710. // Simulates a link to it and click to dowload.
  57711. var a = document.createElement("a");
  57712. document.body.appendChild(a);
  57713. a.style.display = "none";
  57714. a.href = objUrl;
  57715. a.download = "envmap.babylon.hdr";
  57716. a.click();
  57717. };
  57718. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  57719. };
  57720. /**
  57721. * Serializes the data contained in the texture in a binary format.
  57722. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57723. * as the spherical used in the lighting.
  57724. * @param url The HDR file url.
  57725. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57726. * @param onError Method called if any error happens during download.
  57727. * @return The packed binary data.
  57728. */
  57729. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  57730. if (onError === void 0) { onError = null; }
  57731. // Needs the url tho create the texture.
  57732. if (!url) {
  57733. return null;
  57734. }
  57735. // Check Power of two size.
  57736. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  57737. return null;
  57738. }
  57739. // Coming Back in 3.1.
  57740. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  57741. return null;
  57742. };
  57743. HDRCubeTexture._facesMapping = [
  57744. "right",
  57745. "left",
  57746. "up",
  57747. "down",
  57748. "front",
  57749. "back"
  57750. ];
  57751. return HDRCubeTexture;
  57752. }(BABYLON.BaseTexture));
  57753. BABYLON.HDRCubeTexture = HDRCubeTexture;
  57754. })(BABYLON || (BABYLON = {}));
  57755. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  57756. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  57757. // Huge respect for a such great lib.
  57758. // Earcut license:
  57759. // Copyright (c) 2016, Mapbox
  57760. //
  57761. // Permission to use, copy, modify, and/or distribute this software for any purpose
  57762. // with or without fee is hereby granted, provided that the above copyright notice
  57763. // and this permission notice appear in all copies.
  57764. //
  57765. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  57766. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  57767. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  57768. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  57769. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  57770. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  57771. // THIS SOFTWARE.
  57772. var Earcut;
  57773. (function (Earcut) {
  57774. /**
  57775. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  57776. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  57777. * @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).
  57778. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  57779. */
  57780. function earcut(data, holeIndices, dim) {
  57781. dim = dim || 2;
  57782. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  57783. if (!outerNode)
  57784. return triangles;
  57785. var minX, minY, maxX, maxY, x, y, size;
  57786. if (hasHoles)
  57787. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  57788. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  57789. if (data.length > 80 * dim) {
  57790. minX = maxX = data[0];
  57791. minY = maxY = data[1];
  57792. for (var i = dim; i < outerLen; i += dim) {
  57793. x = data[i];
  57794. y = data[i + 1];
  57795. if (x < minX)
  57796. minX = x;
  57797. if (y < minY)
  57798. minY = y;
  57799. if (x > maxX)
  57800. maxX = x;
  57801. if (y > maxY)
  57802. maxY = y;
  57803. }
  57804. // minX, minY and size are later used to transform coords into integers for z-order calculation
  57805. size = Math.max(maxX - minX, maxY - minY);
  57806. }
  57807. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  57808. return triangles;
  57809. }
  57810. Earcut.earcut = earcut;
  57811. // create a circular doubly linked list from polygon points in the specified winding order
  57812. function linkedList(data, start, end, dim, clockwise) {
  57813. var i, last;
  57814. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  57815. for (i = start; i < end; i += dim)
  57816. last = insertNode(i, data[i], data[i + 1], last);
  57817. }
  57818. else {
  57819. for (i = end - dim; i >= start; i -= dim)
  57820. last = insertNode(i, data[i], data[i + 1], last);
  57821. }
  57822. if (last && equals(last, last.next)) {
  57823. removeNode(last);
  57824. last = last.next;
  57825. }
  57826. return last;
  57827. }
  57828. // eliminate colinear or duplicate points
  57829. function filterPoints(start, end) {
  57830. if (!start)
  57831. return start;
  57832. if (!end)
  57833. end = start;
  57834. var p = start, again;
  57835. do {
  57836. again = false;
  57837. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  57838. removeNode(p);
  57839. p = end = p.prev;
  57840. if (p === p.next)
  57841. return null;
  57842. again = true;
  57843. }
  57844. else {
  57845. p = p.next;
  57846. }
  57847. } while (again || p !== end);
  57848. return end;
  57849. }
  57850. // main ear slicing loop which triangulates a polygon (given as a linked list)
  57851. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  57852. if (!ear)
  57853. return;
  57854. // interlink polygon nodes in z-order
  57855. if (!pass && size)
  57856. indexCurve(ear, minX, minY, size);
  57857. var stop = ear, prev, next;
  57858. // iterate through ears, slicing them one by one
  57859. while (ear.prev !== ear.next) {
  57860. prev = ear.prev;
  57861. next = ear.next;
  57862. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  57863. // cut off the triangle
  57864. triangles.push(prev.i / dim);
  57865. triangles.push(ear.i / dim);
  57866. triangles.push(next.i / dim);
  57867. removeNode(ear);
  57868. // skipping the next vertice leads to less sliver triangles
  57869. ear = next.next;
  57870. stop = next.next;
  57871. continue;
  57872. }
  57873. ear = next;
  57874. // if we looped through the whole remaining polygon and can't find any more ears
  57875. if (ear === stop) {
  57876. // try filtering points and slicing again
  57877. if (!pass) {
  57878. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  57879. // if this didn't work, try curing all small self-intersections locally
  57880. }
  57881. else if (pass === 1) {
  57882. ear = cureLocalIntersections(ear, triangles, dim);
  57883. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  57884. // as a last resort, try splitting the remaining polygon into two
  57885. }
  57886. else if (pass === 2) {
  57887. splitEarcut(ear, triangles, dim, minX, minY, size);
  57888. }
  57889. break;
  57890. }
  57891. }
  57892. }
  57893. // check whether a polygon node forms a valid ear with adjacent nodes
  57894. function isEar(ear) {
  57895. var a = ear.prev, b = ear, c = ear.next;
  57896. if (area(a, b, c) >= 0)
  57897. return false; // reflex, can't be an ear
  57898. // now make sure we don't have other points inside the potential ear
  57899. var p = ear.next.next;
  57900. while (p !== ear.prev) {
  57901. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57902. area(p.prev, p, p.next) >= 0)
  57903. return false;
  57904. p = p.next;
  57905. }
  57906. return true;
  57907. }
  57908. function isEarHashed(ear, minX, minY, size) {
  57909. var a = ear.prev, b = ear, c = ear.next;
  57910. if (area(a, b, c) >= 0)
  57911. return false; // reflex, can't be an ear
  57912. // triangle bbox; min & max are calculated like this for speed
  57913. 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);
  57914. // z-order range for the current triangle bbox;
  57915. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  57916. // first look for points inside the triangle in increasing z-order
  57917. var p = ear.nextZ;
  57918. while (p && p.z <= maxZ) {
  57919. if (p !== ear.prev &&
  57920. p !== ear.next &&
  57921. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57922. area(p.prev, p, p.next) >= 0)
  57923. return false;
  57924. p = p.nextZ;
  57925. }
  57926. // then look for points in decreasing z-order
  57927. p = ear.prevZ;
  57928. while (p && p.z >= minZ) {
  57929. if (p !== ear.prev &&
  57930. p !== ear.next &&
  57931. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  57932. area(p.prev, p, p.next) >= 0)
  57933. return false;
  57934. p = p.prevZ;
  57935. }
  57936. return true;
  57937. }
  57938. // go through all polygon nodes and cure small local self-intersections
  57939. function cureLocalIntersections(start, triangles, dim) {
  57940. var p = start;
  57941. do {
  57942. var a = p.prev, b = p.next.next;
  57943. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  57944. triangles.push(a.i / dim);
  57945. triangles.push(p.i / dim);
  57946. triangles.push(b.i / dim);
  57947. // remove two nodes involved
  57948. removeNode(p);
  57949. removeNode(p.next);
  57950. p = start = b;
  57951. }
  57952. p = p.next;
  57953. } while (p !== start);
  57954. return p;
  57955. }
  57956. // try splitting polygon into two and triangulate them independently
  57957. function splitEarcut(start, triangles, dim, minX, minY, size) {
  57958. // look for a valid diagonal that divides the polygon into two
  57959. var a = start;
  57960. do {
  57961. var b = a.next.next;
  57962. while (b !== a.prev) {
  57963. if (a.i !== b.i && isValidDiagonal(a, b)) {
  57964. // split the polygon in two by the diagonal
  57965. var c = splitPolygon(a, b);
  57966. // filter colinear points around the cuts
  57967. a = filterPoints(a, a.next);
  57968. c = filterPoints(c, c.next);
  57969. // run earcut on each half
  57970. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  57971. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  57972. return;
  57973. }
  57974. b = b.next;
  57975. }
  57976. a = a.next;
  57977. } while (a !== start);
  57978. }
  57979. // link every hole into the outer loop, producing a single-ring polygon without holes
  57980. function eliminateHoles(data, holeIndices, outerNode, dim) {
  57981. var queue = [], i, len, start, end, list;
  57982. for (i = 0, len = holeIndices.length; i < len; i++) {
  57983. start = holeIndices[i] * dim;
  57984. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  57985. list = linkedList(data, start, end, dim, false);
  57986. if (list === list.next)
  57987. list.steiner = true;
  57988. queue.push(getLeftmost(list));
  57989. }
  57990. queue.sort(compareX);
  57991. // process holes from left to right
  57992. for (i = 0; i < queue.length; i++) {
  57993. eliminateHole(queue[i], outerNode);
  57994. outerNode = filterPoints(outerNode, outerNode.next);
  57995. }
  57996. return outerNode;
  57997. }
  57998. function compareX(a, b) {
  57999. return a.x - b.x;
  58000. }
  58001. // find a bridge between vertices that connects hole with an outer ring and and link it
  58002. function eliminateHole(hole, outerNode) {
  58003. outerNode = findHoleBridge(hole, outerNode);
  58004. if (outerNode) {
  58005. var b = splitPolygon(outerNode, hole);
  58006. filterPoints(b, b.next);
  58007. }
  58008. }
  58009. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  58010. function findHoleBridge(hole, outerNode) {
  58011. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  58012. // find a segment intersected by a ray from the hole's leftmost point to the left;
  58013. // segment's endpoint with lesser x will be potential connection point
  58014. do {
  58015. if (hy <= p.y && hy >= p.next.y) {
  58016. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  58017. if (x <= hx && x > qx) {
  58018. qx = x;
  58019. if (x === hx) {
  58020. if (hy === p.y)
  58021. return p;
  58022. if (hy === p.next.y)
  58023. return p.next;
  58024. }
  58025. m = p.x < p.next.x ? p : p.next;
  58026. }
  58027. }
  58028. p = p.next;
  58029. } while (p !== outerNode);
  58030. if (!m)
  58031. return null;
  58032. if (hx === qx)
  58033. return m.prev; // hole touches outer segment; pick lower endpoint
  58034. // look for points inside the triangle of hole point, segment intersection and endpoint;
  58035. // if there are no points found, we have a valid connection;
  58036. // otherwise choose the point of the minimum angle with the ray as connection point
  58037. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  58038. p = m.next;
  58039. while (p !== stop) {
  58040. if (hx >= p.x &&
  58041. p.x >= mx &&
  58042. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  58043. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  58044. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  58045. m = p;
  58046. tanMin = tan;
  58047. }
  58048. }
  58049. p = p.next;
  58050. }
  58051. return m;
  58052. }
  58053. // interlink polygon nodes in z-order
  58054. function indexCurve(start, minX, minY, size) {
  58055. var p = start;
  58056. do {
  58057. if (p.z === null)
  58058. p.z = zOrder(p.x, p.y, minX, minY, size);
  58059. p.prevZ = p.prev;
  58060. p.nextZ = p.next;
  58061. p = p.next;
  58062. } while (p !== start);
  58063. p.prevZ.nextZ = null;
  58064. p.prevZ = null;
  58065. sortLinked(p);
  58066. }
  58067. // Simon Tatham's linked list merge sort algorithm
  58068. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  58069. function sortLinked(list) {
  58070. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  58071. do {
  58072. p = list;
  58073. list = null;
  58074. tail = null;
  58075. numMerges = 0;
  58076. while (p) {
  58077. numMerges++;
  58078. q = p;
  58079. pSize = 0;
  58080. for (i = 0; i < inSize; i++) {
  58081. pSize++;
  58082. q = q.nextZ;
  58083. if (!q)
  58084. break;
  58085. }
  58086. qSize = inSize;
  58087. while (pSize > 0 || (qSize > 0 && q)) {
  58088. if (pSize === 0) {
  58089. e = q;
  58090. q = q.nextZ;
  58091. qSize--;
  58092. }
  58093. else if (qSize === 0 || !q) {
  58094. e = p;
  58095. p = p.nextZ;
  58096. pSize--;
  58097. }
  58098. else if (p.z <= q.z) {
  58099. e = p;
  58100. p = p.nextZ;
  58101. pSize--;
  58102. }
  58103. else {
  58104. e = q;
  58105. q = q.nextZ;
  58106. qSize--;
  58107. }
  58108. if (tail)
  58109. tail.nextZ = e;
  58110. else
  58111. list = e;
  58112. e.prevZ = tail;
  58113. tail = e;
  58114. }
  58115. p = q;
  58116. }
  58117. tail.nextZ = null;
  58118. inSize *= 2;
  58119. } while (numMerges > 1);
  58120. return list;
  58121. }
  58122. // z-order of a point given coords and size of the data bounding box
  58123. function zOrder(x, y, minX, minY, size) {
  58124. // coords are transformed into non-negative 15-bit integer range
  58125. x = 32767 * (x - minX) / size;
  58126. y = 32767 * (y - minY) / size;
  58127. x = (x | (x << 8)) & 0x00FF00FF;
  58128. x = (x | (x << 4)) & 0x0F0F0F0F;
  58129. x = (x | (x << 2)) & 0x33333333;
  58130. x = (x | (x << 1)) & 0x55555555;
  58131. y = (y | (y << 8)) & 0x00FF00FF;
  58132. y = (y | (y << 4)) & 0x0F0F0F0F;
  58133. y = (y | (y << 2)) & 0x33333333;
  58134. y = (y | (y << 1)) & 0x55555555;
  58135. return x | (y << 1);
  58136. }
  58137. // find the leftmost node of a polygon ring
  58138. function getLeftmost(start) {
  58139. var p = start, leftmost = start;
  58140. do {
  58141. if (p.x < leftmost.x)
  58142. leftmost = p;
  58143. p = p.next;
  58144. } while (p !== start);
  58145. return leftmost;
  58146. }
  58147. // check if a point lies within a convex triangle
  58148. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  58149. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  58150. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  58151. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  58152. }
  58153. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  58154. function isValidDiagonal(a, b) {
  58155. return a.next.i !== b.i &&
  58156. a.prev.i !== b.i &&
  58157. !intersectsPolygon(a, b) &&
  58158. locallyInside(a, b) &&
  58159. locallyInside(b, a) &&
  58160. middleInside(a, b);
  58161. }
  58162. // signed area of a triangle
  58163. function area(p, q, r) {
  58164. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  58165. }
  58166. // check if two points are equal
  58167. function equals(p1, p2) {
  58168. return p1.x === p2.x && p1.y === p2.y;
  58169. }
  58170. // check if two segments intersect
  58171. function intersects(p1, q1, p2, q2) {
  58172. if ((equals(p1, q1) && equals(p2, q2)) ||
  58173. (equals(p1, q2) && equals(p2, q1)))
  58174. return true;
  58175. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  58176. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  58177. }
  58178. // check if a polygon diagonal intersects any polygon segments
  58179. function intersectsPolygon(a, b) {
  58180. var p = a;
  58181. do {
  58182. if (p.i !== a.i &&
  58183. p.next.i !== a.i &&
  58184. p.i !== b.i &&
  58185. p.next.i !== b.i &&
  58186. intersects(p, p.next, a, b))
  58187. return true;
  58188. p = p.next;
  58189. } while (p !== a);
  58190. return false;
  58191. }
  58192. // check if a polygon diagonal is locally inside the polygon
  58193. function locallyInside(a, b) {
  58194. return area(a.prev, a, a.next) < 0
  58195. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  58196. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  58197. }
  58198. // check if the middle point of a polygon diagonal is inside the polygon
  58199. function middleInside(a, b) {
  58200. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  58201. do {
  58202. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  58203. inside = !inside;
  58204. p = p.next;
  58205. } while (p !== a);
  58206. return inside;
  58207. }
  58208. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  58209. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  58210. function splitPolygon(a, b) {
  58211. 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;
  58212. a.next = b;
  58213. b.prev = a;
  58214. a2.next = an;
  58215. an.prev = a2;
  58216. b2.next = a2;
  58217. a2.prev = b2;
  58218. bp.next = b2;
  58219. b2.prev = bp;
  58220. return b2;
  58221. }
  58222. // create a node and optionally link it with previous one (in a circular doubly linked list)
  58223. function insertNode(i, x, y, last) {
  58224. var p = new Node(i, x, y);
  58225. if (!last) {
  58226. p.prev = p;
  58227. p.next = p;
  58228. }
  58229. else {
  58230. p.next = last.next;
  58231. p.prev = last;
  58232. last.next.prev = p;
  58233. last.next = p;
  58234. }
  58235. return p;
  58236. }
  58237. function removeNode(p) {
  58238. p.next.prev = p.prev;
  58239. p.prev.next = p.next;
  58240. if (p.prevZ)
  58241. p.prevZ.nextZ = p.nextZ;
  58242. if (p.nextZ)
  58243. p.nextZ.prevZ = p.prevZ;
  58244. }
  58245. function Node(i, x, y) {
  58246. // vertice index in coordinates array
  58247. this.i = i;
  58248. // vertex coordinates
  58249. this.x = x;
  58250. this.y = y;
  58251. // previous and next vertice nodes in a polygon ring
  58252. this.prev = null;
  58253. this.next = null;
  58254. // z-order curve value
  58255. this.z = null;
  58256. // previous and next nodes in z-order
  58257. this.prevZ = null;
  58258. this.nextZ = null;
  58259. // indicates whether this is a steiner point
  58260. this.steiner = false;
  58261. }
  58262. /**
  58263. * return a percentage difference between the polygon area and its triangulation area;
  58264. * used to verify correctness of triangulation
  58265. */
  58266. function deviation(data, holeIndices, dim, triangles) {
  58267. var hasHoles = holeIndices && holeIndices.length;
  58268. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  58269. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  58270. if (hasHoles) {
  58271. for (var i = 0, len = holeIndices.length; i < len; i++) {
  58272. var start = holeIndices[i] * dim;
  58273. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  58274. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  58275. }
  58276. }
  58277. var trianglesArea = 0;
  58278. for (i = 0; i < triangles.length; i += 3) {
  58279. var a = triangles[i] * dim;
  58280. var b = triangles[i + 1] * dim;
  58281. var c = triangles[i + 2] * dim;
  58282. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  58283. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  58284. }
  58285. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  58286. }
  58287. Earcut.deviation = deviation;
  58288. ;
  58289. function signedArea(data, start, end, dim) {
  58290. var sum = 0;
  58291. for (var i = start, j = end - dim; i < end; i += dim) {
  58292. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  58293. j = i;
  58294. }
  58295. return sum;
  58296. }
  58297. /**
  58298. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  58299. */
  58300. function flatten(data) {
  58301. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  58302. for (var i = 0; i < data.length; i++) {
  58303. for (var j = 0; j < data[i].length; j++) {
  58304. for (var d = 0; d < dim; d++)
  58305. result.vertices.push(data[i][j][d]);
  58306. }
  58307. if (i > 0) {
  58308. holeIndex += data[i - 1].length;
  58309. result.holes.push(holeIndex);
  58310. }
  58311. }
  58312. return result;
  58313. }
  58314. Earcut.flatten = flatten;
  58315. ;
  58316. })(Earcut || (Earcut = {}));
  58317. //# sourceMappingURL=babylon.earcut.js.map
  58318. /// <reference path="..\Math\babylon.math.ts" />
  58319. var BABYLON;
  58320. (function (BABYLON) {
  58321. var IndexedVector2 = (function (_super) {
  58322. __extends(IndexedVector2, _super);
  58323. function IndexedVector2(original, index) {
  58324. var _this = _super.call(this, original.x, original.y) || this;
  58325. _this.index = index;
  58326. return _this;
  58327. }
  58328. return IndexedVector2;
  58329. }(BABYLON.Vector2));
  58330. var PolygonPoints = (function () {
  58331. function PolygonPoints() {
  58332. this.elements = new Array();
  58333. }
  58334. PolygonPoints.prototype.add = function (originalPoints) {
  58335. var _this = this;
  58336. var result = new Array();
  58337. originalPoints.forEach(function (point) {
  58338. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  58339. var newPoint = new IndexedVector2(point, _this.elements.length);
  58340. result.push(newPoint);
  58341. _this.elements.push(newPoint);
  58342. }
  58343. });
  58344. return result;
  58345. };
  58346. PolygonPoints.prototype.computeBounds = function () {
  58347. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  58348. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  58349. this.elements.forEach(function (point) {
  58350. // x
  58351. if (point.x < lmin.x) {
  58352. lmin.x = point.x;
  58353. }
  58354. else if (point.x > lmax.x) {
  58355. lmax.x = point.x;
  58356. }
  58357. // y
  58358. if (point.y < lmin.y) {
  58359. lmin.y = point.y;
  58360. }
  58361. else if (point.y > lmax.y) {
  58362. lmax.y = point.y;
  58363. }
  58364. });
  58365. return {
  58366. min: lmin,
  58367. max: lmax,
  58368. width: lmax.x - lmin.x,
  58369. height: lmax.y - lmin.y
  58370. };
  58371. };
  58372. return PolygonPoints;
  58373. }());
  58374. var Polygon = (function () {
  58375. function Polygon() {
  58376. }
  58377. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  58378. return [
  58379. new BABYLON.Vector2(xmin, ymin),
  58380. new BABYLON.Vector2(xmax, ymin),
  58381. new BABYLON.Vector2(xmax, ymax),
  58382. new BABYLON.Vector2(xmin, ymax)
  58383. ];
  58384. };
  58385. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  58386. if (cx === void 0) { cx = 0; }
  58387. if (cy === void 0) { cy = 0; }
  58388. if (numberOfSides === void 0) { numberOfSides = 32; }
  58389. var result = new Array();
  58390. var angle = 0;
  58391. var increment = (Math.PI * 2) / numberOfSides;
  58392. for (var i = 0; i < numberOfSides; i++) {
  58393. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  58394. angle -= increment;
  58395. }
  58396. return result;
  58397. };
  58398. Polygon.Parse = function (input) {
  58399. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  58400. var i, result = [];
  58401. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  58402. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  58403. }
  58404. return result;
  58405. };
  58406. Polygon.StartingAt = function (x, y) {
  58407. return BABYLON.Path2.StartingAt(x, y);
  58408. };
  58409. return Polygon;
  58410. }());
  58411. BABYLON.Polygon = Polygon;
  58412. var PolygonMeshBuilder = (function () {
  58413. function PolygonMeshBuilder(name, contours, scene) {
  58414. this._points = new PolygonPoints();
  58415. this._outlinepoints = new PolygonPoints();
  58416. this._holes = [];
  58417. this._epoints = new Array();
  58418. this._eholes = new Array();
  58419. this._name = name;
  58420. this._scene = scene;
  58421. var points;
  58422. if (contours instanceof BABYLON.Path2) {
  58423. points = contours.getPoints();
  58424. }
  58425. else {
  58426. points = contours;
  58427. }
  58428. this._addToepoint(points);
  58429. this._points.add(points);
  58430. this._outlinepoints.add(points);
  58431. }
  58432. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  58433. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  58434. var p = points_1[_i];
  58435. this._epoints.push(p.x, p.y);
  58436. }
  58437. };
  58438. PolygonMeshBuilder.prototype.addHole = function (hole) {
  58439. this._points.add(hole);
  58440. var holepoints = new PolygonPoints();
  58441. holepoints.add(hole);
  58442. this._holes.push(holepoints);
  58443. this._eholes.push(this._epoints.length / 2);
  58444. this._addToepoint(hole);
  58445. return this;
  58446. };
  58447. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  58448. var _this = this;
  58449. if (updatable === void 0) { updatable = false; }
  58450. var result = new BABYLON.Mesh(this._name, this._scene);
  58451. var normals = [];
  58452. var positions = [];
  58453. var uvs = [];
  58454. var bounds = this._points.computeBounds();
  58455. this._points.elements.forEach(function (p) {
  58456. normals.push(0, 1.0, 0);
  58457. positions.push(p.x, 0, p.y);
  58458. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  58459. });
  58460. var indices = [];
  58461. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  58462. for (var i = 0; i < res.length; i++) {
  58463. indices.push(res[i]);
  58464. }
  58465. if (depth > 0) {
  58466. var positionscount = (positions.length / 3); //get the current pointcount
  58467. this._points.elements.forEach(function (p) {
  58468. normals.push(0, -1.0, 0);
  58469. positions.push(p.x, -depth, p.y);
  58470. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  58471. });
  58472. var totalCount = indices.length;
  58473. for (var i = 0; i < totalCount; i += 3) {
  58474. var i0 = indices[i + 0];
  58475. var i1 = indices[i + 1];
  58476. var i2 = indices[i + 2];
  58477. indices.push(i2 + positionscount);
  58478. indices.push(i1 + positionscount);
  58479. indices.push(i0 + positionscount);
  58480. }
  58481. //Add the sides
  58482. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  58483. this._holes.forEach(function (hole) {
  58484. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  58485. });
  58486. }
  58487. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  58488. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  58489. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  58490. result.setIndices(indices);
  58491. return result;
  58492. };
  58493. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  58494. var StartIndex = positions.length / 3;
  58495. var ulength = 0;
  58496. for (var i = 0; i < points.elements.length; i++) {
  58497. var p = points.elements[i];
  58498. var p1;
  58499. if ((i + 1) > points.elements.length - 1) {
  58500. p1 = points.elements[0];
  58501. }
  58502. else {
  58503. p1 = points.elements[i + 1];
  58504. }
  58505. positions.push(p.x, 0, p.y);
  58506. positions.push(p.x, -depth, p.y);
  58507. positions.push(p1.x, 0, p1.y);
  58508. positions.push(p1.x, -depth, p1.y);
  58509. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  58510. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  58511. var v3 = v2.subtract(v1);
  58512. var v4 = new BABYLON.Vector3(0, 1, 0);
  58513. var vn = BABYLON.Vector3.Cross(v3, v4);
  58514. vn = vn.normalize();
  58515. uvs.push(ulength / bounds.width, 0);
  58516. uvs.push(ulength / bounds.width, 1);
  58517. ulength += v3.length();
  58518. uvs.push((ulength / bounds.width), 0);
  58519. uvs.push((ulength / bounds.width), 1);
  58520. if (!flip) {
  58521. normals.push(-vn.x, -vn.y, -vn.z);
  58522. normals.push(-vn.x, -vn.y, -vn.z);
  58523. normals.push(-vn.x, -vn.y, -vn.z);
  58524. normals.push(-vn.x, -vn.y, -vn.z);
  58525. indices.push(StartIndex);
  58526. indices.push(StartIndex + 1);
  58527. indices.push(StartIndex + 2);
  58528. indices.push(StartIndex + 1);
  58529. indices.push(StartIndex + 3);
  58530. indices.push(StartIndex + 2);
  58531. }
  58532. else {
  58533. normals.push(vn.x, vn.y, vn.z);
  58534. normals.push(vn.x, vn.y, vn.z);
  58535. normals.push(vn.x, vn.y, vn.z);
  58536. normals.push(vn.x, vn.y, vn.z);
  58537. indices.push(StartIndex);
  58538. indices.push(StartIndex + 2);
  58539. indices.push(StartIndex + 1);
  58540. indices.push(StartIndex + 1);
  58541. indices.push(StartIndex + 2);
  58542. indices.push(StartIndex + 3);
  58543. }
  58544. StartIndex += 4;
  58545. }
  58546. ;
  58547. };
  58548. return PolygonMeshBuilder;
  58549. }());
  58550. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  58551. })(BABYLON || (BABYLON = {}));
  58552. //# sourceMappingURL=babylon.polygonMesh.js.map
  58553. var BABYLON;
  58554. (function (BABYLON) {
  58555. // Unique ID when we import meshes from Babylon to CSG
  58556. var currentCSGMeshId = 0;
  58557. // # class Vertex
  58558. // Represents a vertex of a polygon. Use your own vertex class instead of this
  58559. // one to provide additional features like texture coordinates and vertex
  58560. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  58561. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  58562. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  58563. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  58564. // is not used anywhere else.
  58565. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  58566. var Vertex = (function () {
  58567. function Vertex(pos, normal, uv) {
  58568. this.pos = pos;
  58569. this.normal = normal;
  58570. this.uv = uv;
  58571. }
  58572. Vertex.prototype.clone = function () {
  58573. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  58574. };
  58575. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  58576. // orientation of a polygon is flipped.
  58577. Vertex.prototype.flip = function () {
  58578. this.normal = this.normal.scale(-1);
  58579. };
  58580. // Create a new vertex between this vertex and `other` by linearly
  58581. // interpolating all properties using a parameter of `t`. Subclasses should
  58582. // override this to interpolate additional properties.
  58583. Vertex.prototype.interpolate = function (other, t) {
  58584. 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));
  58585. };
  58586. return Vertex;
  58587. }());
  58588. // # class Plane
  58589. // Represents a plane in 3D space.
  58590. var Plane = (function () {
  58591. function Plane(normal, w) {
  58592. this.normal = normal;
  58593. this.w = w;
  58594. }
  58595. Plane.FromPoints = function (a, b, c) {
  58596. var v0 = c.subtract(a);
  58597. var v1 = b.subtract(a);
  58598. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  58599. return null;
  58600. }
  58601. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  58602. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  58603. };
  58604. Plane.prototype.clone = function () {
  58605. return new Plane(this.normal.clone(), this.w);
  58606. };
  58607. Plane.prototype.flip = function () {
  58608. this.normal.scaleInPlace(-1);
  58609. this.w = -this.w;
  58610. };
  58611. // Split `polygon` by this plane if needed, then put the polygon or polygon
  58612. // fragments in the appropriate lists. Coplanar polygons go into either
  58613. // `coplanarFront` or `coplanarBack` depending on their orientation with
  58614. // respect to this plane. Polygons in front or in back of this plane go into
  58615. // either `front` or `back`.
  58616. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  58617. var COPLANAR = 0;
  58618. var FRONT = 1;
  58619. var BACK = 2;
  58620. var SPANNING = 3;
  58621. // Classify each point as well as the entire polygon into one of the above
  58622. // four classes.
  58623. var polygonType = 0;
  58624. var types = [];
  58625. var i;
  58626. var t;
  58627. for (i = 0; i < polygon.vertices.length; i++) {
  58628. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  58629. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  58630. polygonType |= type;
  58631. types.push(type);
  58632. }
  58633. // Put the polygon in the correct list, splitting it when necessary.
  58634. switch (polygonType) {
  58635. case COPLANAR:
  58636. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  58637. break;
  58638. case FRONT:
  58639. front.push(polygon);
  58640. break;
  58641. case BACK:
  58642. back.push(polygon);
  58643. break;
  58644. case SPANNING:
  58645. var f = [], b = [];
  58646. for (i = 0; i < polygon.vertices.length; i++) {
  58647. var j = (i + 1) % polygon.vertices.length;
  58648. var ti = types[i], tj = types[j];
  58649. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  58650. if (ti !== BACK)
  58651. f.push(vi);
  58652. if (ti !== FRONT)
  58653. b.push(ti !== BACK ? vi.clone() : vi);
  58654. if ((ti | tj) === SPANNING) {
  58655. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  58656. var v = vi.interpolate(vj, t);
  58657. f.push(v);
  58658. b.push(v.clone());
  58659. }
  58660. }
  58661. var poly;
  58662. if (f.length >= 3) {
  58663. poly = new Polygon(f, polygon.shared);
  58664. if (poly.plane)
  58665. front.push(poly);
  58666. }
  58667. if (b.length >= 3) {
  58668. poly = new Polygon(b, polygon.shared);
  58669. if (poly.plane)
  58670. back.push(poly);
  58671. }
  58672. break;
  58673. }
  58674. };
  58675. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  58676. // point is on the plane.
  58677. Plane.EPSILON = 1e-5;
  58678. return Plane;
  58679. }());
  58680. // # class Polygon
  58681. // Represents a convex polygon. The vertices used to initialize a polygon must
  58682. // be coplanar and form a convex loop.
  58683. //
  58684. // Each convex polygon has a `shared` property, which is shared between all
  58685. // polygons that are clones of each other or were split from the same polygon.
  58686. // This can be used to define per-polygon properties (such as surface color).
  58687. var Polygon = (function () {
  58688. function Polygon(vertices, shared) {
  58689. this.vertices = vertices;
  58690. this.shared = shared;
  58691. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  58692. }
  58693. Polygon.prototype.clone = function () {
  58694. var vertices = this.vertices.map(function (v) { return v.clone(); });
  58695. return new Polygon(vertices, this.shared);
  58696. };
  58697. Polygon.prototype.flip = function () {
  58698. this.vertices.reverse().map(function (v) { v.flip(); });
  58699. this.plane.flip();
  58700. };
  58701. return Polygon;
  58702. }());
  58703. // # class Node
  58704. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  58705. // by picking a polygon to split along. That polygon (and all other coplanar
  58706. // polygons) are added directly to that node and the other polygons are added to
  58707. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  58708. // no distinction between internal and leaf nodes.
  58709. var Node = (function () {
  58710. function Node(polygons) {
  58711. this.plane = null;
  58712. this.front = null;
  58713. this.back = null;
  58714. this.polygons = [];
  58715. if (polygons) {
  58716. this.build(polygons);
  58717. }
  58718. }
  58719. Node.prototype.clone = function () {
  58720. var node = new Node();
  58721. node.plane = this.plane && this.plane.clone();
  58722. node.front = this.front && this.front.clone();
  58723. node.back = this.back && this.back.clone();
  58724. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  58725. return node;
  58726. };
  58727. // Convert solid space to empty space and empty space to solid space.
  58728. Node.prototype.invert = function () {
  58729. for (var i = 0; i < this.polygons.length; i++) {
  58730. this.polygons[i].flip();
  58731. }
  58732. if (this.plane) {
  58733. this.plane.flip();
  58734. }
  58735. if (this.front) {
  58736. this.front.invert();
  58737. }
  58738. if (this.back) {
  58739. this.back.invert();
  58740. }
  58741. var temp = this.front;
  58742. this.front = this.back;
  58743. this.back = temp;
  58744. };
  58745. // Recursively remove all polygons in `polygons` that are inside this BSP
  58746. // tree.
  58747. Node.prototype.clipPolygons = function (polygons) {
  58748. if (!this.plane)
  58749. return polygons.slice();
  58750. var front = [], back = [];
  58751. for (var i = 0; i < polygons.length; i++) {
  58752. this.plane.splitPolygon(polygons[i], front, back, front, back);
  58753. }
  58754. if (this.front) {
  58755. front = this.front.clipPolygons(front);
  58756. }
  58757. if (this.back) {
  58758. back = this.back.clipPolygons(back);
  58759. }
  58760. else {
  58761. back = [];
  58762. }
  58763. return front.concat(back);
  58764. };
  58765. // Remove all polygons in this BSP tree that are inside the other BSP tree
  58766. // `bsp`.
  58767. Node.prototype.clipTo = function (bsp) {
  58768. this.polygons = bsp.clipPolygons(this.polygons);
  58769. if (this.front)
  58770. this.front.clipTo(bsp);
  58771. if (this.back)
  58772. this.back.clipTo(bsp);
  58773. };
  58774. // Return a list of all polygons in this BSP tree.
  58775. Node.prototype.allPolygons = function () {
  58776. var polygons = this.polygons.slice();
  58777. if (this.front)
  58778. polygons = polygons.concat(this.front.allPolygons());
  58779. if (this.back)
  58780. polygons = polygons.concat(this.back.allPolygons());
  58781. return polygons;
  58782. };
  58783. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  58784. // new polygons are filtered down to the bottom of the tree and become new
  58785. // nodes there. Each set of polygons is partitioned using the first polygon
  58786. // (no heuristic is used to pick a good split).
  58787. Node.prototype.build = function (polygons) {
  58788. if (!polygons.length)
  58789. return;
  58790. if (!this.plane)
  58791. this.plane = polygons[0].plane.clone();
  58792. var front = [], back = [];
  58793. for (var i = 0; i < polygons.length; i++) {
  58794. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  58795. }
  58796. if (front.length) {
  58797. if (!this.front)
  58798. this.front = new Node();
  58799. this.front.build(front);
  58800. }
  58801. if (back.length) {
  58802. if (!this.back)
  58803. this.back = new Node();
  58804. this.back.build(back);
  58805. }
  58806. };
  58807. return Node;
  58808. }());
  58809. var CSG = (function () {
  58810. function CSG() {
  58811. this.polygons = new Array();
  58812. }
  58813. // Convert BABYLON.Mesh to BABYLON.CSG
  58814. CSG.FromMesh = function (mesh) {
  58815. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  58816. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  58817. if (mesh instanceof BABYLON.Mesh) {
  58818. mesh.computeWorldMatrix(true);
  58819. matrix = mesh.getWorldMatrix();
  58820. meshPosition = mesh.position.clone();
  58821. meshRotation = mesh.rotation.clone();
  58822. if (mesh.rotationQuaternion) {
  58823. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  58824. }
  58825. meshScaling = mesh.scaling.clone();
  58826. }
  58827. else {
  58828. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  58829. }
  58830. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58831. var subMeshes = mesh.subMeshes;
  58832. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  58833. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  58834. vertices = [];
  58835. for (var j = 0; j < 3; j++) {
  58836. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  58837. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  58838. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  58839. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  58840. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  58841. vertex = new Vertex(position, normal, uv);
  58842. vertices.push(vertex);
  58843. }
  58844. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  58845. // To handle the case of degenerated triangle
  58846. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  58847. if (polygon.plane)
  58848. polygons.push(polygon);
  58849. }
  58850. }
  58851. var csg = CSG.FromPolygons(polygons);
  58852. csg.matrix = matrix;
  58853. csg.position = meshPosition;
  58854. csg.rotation = meshRotation;
  58855. csg.scaling = meshScaling;
  58856. csg.rotationQuaternion = meshRotationQuaternion;
  58857. currentCSGMeshId++;
  58858. return csg;
  58859. };
  58860. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  58861. CSG.FromPolygons = function (polygons) {
  58862. var csg = new CSG();
  58863. csg.polygons = polygons;
  58864. return csg;
  58865. };
  58866. CSG.prototype.clone = function () {
  58867. var csg = new CSG();
  58868. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  58869. csg.copyTransformAttributes(this);
  58870. return csg;
  58871. };
  58872. CSG.prototype.toPolygons = function () {
  58873. return this.polygons;
  58874. };
  58875. CSG.prototype.union = function (csg) {
  58876. var a = new Node(this.clone().polygons);
  58877. var b = new Node(csg.clone().polygons);
  58878. a.clipTo(b);
  58879. b.clipTo(a);
  58880. b.invert();
  58881. b.clipTo(a);
  58882. b.invert();
  58883. a.build(b.allPolygons());
  58884. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58885. };
  58886. CSG.prototype.unionInPlace = function (csg) {
  58887. var a = new Node(this.polygons);
  58888. var b = new Node(csg.polygons);
  58889. a.clipTo(b);
  58890. b.clipTo(a);
  58891. b.invert();
  58892. b.clipTo(a);
  58893. b.invert();
  58894. a.build(b.allPolygons());
  58895. this.polygons = a.allPolygons();
  58896. };
  58897. CSG.prototype.subtract = function (csg) {
  58898. var a = new Node(this.clone().polygons);
  58899. var b = new Node(csg.clone().polygons);
  58900. a.invert();
  58901. a.clipTo(b);
  58902. b.clipTo(a);
  58903. b.invert();
  58904. b.clipTo(a);
  58905. b.invert();
  58906. a.build(b.allPolygons());
  58907. a.invert();
  58908. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58909. };
  58910. CSG.prototype.subtractInPlace = function (csg) {
  58911. var a = new Node(this.polygons);
  58912. var b = new Node(csg.polygons);
  58913. a.invert();
  58914. a.clipTo(b);
  58915. b.clipTo(a);
  58916. b.invert();
  58917. b.clipTo(a);
  58918. b.invert();
  58919. a.build(b.allPolygons());
  58920. a.invert();
  58921. this.polygons = a.allPolygons();
  58922. };
  58923. CSG.prototype.intersect = function (csg) {
  58924. var a = new Node(this.clone().polygons);
  58925. var b = new Node(csg.clone().polygons);
  58926. a.invert();
  58927. b.clipTo(a);
  58928. b.invert();
  58929. a.clipTo(b);
  58930. b.clipTo(a);
  58931. a.build(b.allPolygons());
  58932. a.invert();
  58933. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  58934. };
  58935. CSG.prototype.intersectInPlace = function (csg) {
  58936. var a = new Node(this.polygons);
  58937. var b = new Node(csg.polygons);
  58938. a.invert();
  58939. b.clipTo(a);
  58940. b.invert();
  58941. a.clipTo(b);
  58942. b.clipTo(a);
  58943. a.build(b.allPolygons());
  58944. a.invert();
  58945. this.polygons = a.allPolygons();
  58946. };
  58947. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  58948. // not modified.
  58949. CSG.prototype.inverse = function () {
  58950. var csg = this.clone();
  58951. csg.inverseInPlace();
  58952. return csg;
  58953. };
  58954. CSG.prototype.inverseInPlace = function () {
  58955. this.polygons.map(function (p) { p.flip(); });
  58956. };
  58957. // This is used to keep meshes transformations so they can be restored
  58958. // when we build back a Babylon Mesh
  58959. // NB : All CSG operations are performed in world coordinates
  58960. CSG.prototype.copyTransformAttributes = function (csg) {
  58961. this.matrix = csg.matrix;
  58962. this.position = csg.position;
  58963. this.rotation = csg.rotation;
  58964. this.scaling = csg.scaling;
  58965. this.rotationQuaternion = csg.rotationQuaternion;
  58966. return this;
  58967. };
  58968. // Build Raw mesh from CSG
  58969. // Coordinates here are in world space
  58970. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  58971. var matrix = this.matrix.clone();
  58972. matrix.invert();
  58973. 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;
  58974. if (keepSubMeshes) {
  58975. // Sort Polygons, since subMeshes are indices range
  58976. polygons.sort(function (a, b) {
  58977. if (a.shared.meshId === b.shared.meshId) {
  58978. return a.shared.subMeshId - b.shared.subMeshId;
  58979. }
  58980. else {
  58981. return a.shared.meshId - b.shared.meshId;
  58982. }
  58983. });
  58984. }
  58985. for (var i = 0, il = polygons.length; i < il; i++) {
  58986. polygon = polygons[i];
  58987. // Building SubMeshes
  58988. if (!subMesh_dict[polygon.shared.meshId]) {
  58989. subMesh_dict[polygon.shared.meshId] = {};
  58990. }
  58991. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  58992. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  58993. indexStart: +Infinity,
  58994. indexEnd: -Infinity,
  58995. materialIndex: polygon.shared.materialIndex
  58996. };
  58997. }
  58998. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  58999. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  59000. polygonIndices[0] = 0;
  59001. polygonIndices[1] = j - 1;
  59002. polygonIndices[2] = j;
  59003. for (var k = 0; k < 3; k++) {
  59004. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  59005. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  59006. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  59007. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  59008. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  59009. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  59010. // Check if 2 points can be merged
  59011. if (!(typeof vertex_idx !== 'undefined' &&
  59012. normals[vertex_idx * 3] === localNormal.x &&
  59013. normals[vertex_idx * 3 + 1] === localNormal.y &&
  59014. normals[vertex_idx * 3 + 2] === localNormal.z &&
  59015. uvs[vertex_idx * 2] === uv.x &&
  59016. uvs[vertex_idx * 2 + 1] === uv.y)) {
  59017. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  59018. uvs.push(uv.x, uv.y);
  59019. normals.push(normal.x, normal.y, normal.z);
  59020. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  59021. }
  59022. indices.push(vertex_idx);
  59023. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  59024. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  59025. currentIndex++;
  59026. }
  59027. }
  59028. }
  59029. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  59030. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  59031. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  59032. mesh.setIndices(indices);
  59033. if (keepSubMeshes) {
  59034. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  59035. var materialIndexOffset = 0, materialMaxIndex;
  59036. mesh.subMeshes = new Array();
  59037. for (var m in subMesh_dict) {
  59038. materialMaxIndex = -1;
  59039. for (var sm in subMesh_dict[m]) {
  59040. subMesh_obj = subMesh_dict[m][sm];
  59041. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  59042. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  59043. }
  59044. materialIndexOffset += ++materialMaxIndex;
  59045. }
  59046. }
  59047. return mesh;
  59048. };
  59049. // Build Mesh from CSG taking material and transforms into account
  59050. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  59051. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  59052. mesh.material = material;
  59053. mesh.position.copyFrom(this.position);
  59054. mesh.rotation.copyFrom(this.rotation);
  59055. if (this.rotationQuaternion) {
  59056. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  59057. }
  59058. mesh.scaling.copyFrom(this.scaling);
  59059. mesh.computeWorldMatrix(true);
  59060. return mesh;
  59061. };
  59062. return CSG;
  59063. }());
  59064. BABYLON.CSG = CSG;
  59065. })(BABYLON || (BABYLON = {}));
  59066. //# sourceMappingURL=babylon.csg.js.map
  59067. var BABYLON;
  59068. (function (BABYLON) {
  59069. var LensFlare = (function () {
  59070. function LensFlare(size, position, color, imgUrl, system) {
  59071. this.size = size;
  59072. this.position = position;
  59073. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  59074. this.dispose = function () {
  59075. if (this.texture) {
  59076. this.texture.dispose();
  59077. }
  59078. // Remove from scene
  59079. var index = this._system.lensFlares.indexOf(this);
  59080. this._system.lensFlares.splice(index, 1);
  59081. };
  59082. this.color = color || new BABYLON.Color3(1, 1, 1);
  59083. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  59084. this._system = system;
  59085. system.lensFlares.push(this);
  59086. }
  59087. return LensFlare;
  59088. }());
  59089. BABYLON.LensFlare = LensFlare;
  59090. })(BABYLON || (BABYLON = {}));
  59091. //# sourceMappingURL=babylon.lensFlare.js.map
  59092. var BABYLON;
  59093. (function (BABYLON) {
  59094. var LensFlareSystem = (function () {
  59095. function LensFlareSystem(name, emitter, scene) {
  59096. this.name = name;
  59097. this.lensFlares = new Array();
  59098. this.borderLimit = 300;
  59099. this.viewportBorder = 0;
  59100. this.layerMask = 0x0FFFFFFF;
  59101. this._vertexBuffers = {};
  59102. this._isEnabled = true;
  59103. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59104. this._emitter = emitter;
  59105. this.id = name;
  59106. scene.lensFlareSystems.push(this);
  59107. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  59108. var engine = scene.getEngine();
  59109. // VBO
  59110. var vertices = [];
  59111. vertices.push(1, 1);
  59112. vertices.push(-1, 1);
  59113. vertices.push(-1, -1);
  59114. vertices.push(1, -1);
  59115. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59116. // Indices
  59117. var indices = [];
  59118. indices.push(0);
  59119. indices.push(1);
  59120. indices.push(2);
  59121. indices.push(0);
  59122. indices.push(2);
  59123. indices.push(3);
  59124. this._indexBuffer = engine.createIndexBuffer(indices);
  59125. // Effects
  59126. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  59127. }
  59128. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  59129. get: function () {
  59130. return this._isEnabled;
  59131. },
  59132. set: function (value) {
  59133. this._isEnabled = value;
  59134. },
  59135. enumerable: true,
  59136. configurable: true
  59137. });
  59138. LensFlareSystem.prototype.getScene = function () {
  59139. return this._scene;
  59140. };
  59141. LensFlareSystem.prototype.getEmitter = function () {
  59142. return this._emitter;
  59143. };
  59144. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  59145. this._emitter = newEmitter;
  59146. };
  59147. LensFlareSystem.prototype.getEmitterPosition = function () {
  59148. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  59149. };
  59150. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  59151. var position = this.getEmitterPosition();
  59152. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  59153. this._positionX = position.x;
  59154. this._positionY = position.y;
  59155. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  59156. if (this.viewportBorder > 0) {
  59157. globalViewport.x -= this.viewportBorder;
  59158. globalViewport.y -= this.viewportBorder;
  59159. globalViewport.width += this.viewportBorder * 2;
  59160. globalViewport.height += this.viewportBorder * 2;
  59161. position.x += this.viewportBorder;
  59162. position.y += this.viewportBorder;
  59163. this._positionX += this.viewportBorder;
  59164. this._positionY += this.viewportBorder;
  59165. }
  59166. if (position.z > 0) {
  59167. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  59168. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  59169. return true;
  59170. }
  59171. return true;
  59172. }
  59173. return false;
  59174. };
  59175. LensFlareSystem.prototype._isVisible = function () {
  59176. if (!this._isEnabled) {
  59177. return false;
  59178. }
  59179. var emitterPosition = this.getEmitterPosition();
  59180. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  59181. var distance = direction.length();
  59182. direction.normalize();
  59183. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  59184. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  59185. return !pickInfo.hit || pickInfo.distance > distance;
  59186. };
  59187. LensFlareSystem.prototype.render = function () {
  59188. if (!this._effect.isReady())
  59189. return false;
  59190. var engine = this._scene.getEngine();
  59191. var viewport = this._scene.activeCamera.viewport;
  59192. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  59193. // Position
  59194. if (!this.computeEffectivePosition(globalViewport)) {
  59195. return false;
  59196. }
  59197. // Visibility
  59198. if (!this._isVisible()) {
  59199. return false;
  59200. }
  59201. // Intensity
  59202. var awayX;
  59203. var awayY;
  59204. if (this._positionX < this.borderLimit + globalViewport.x) {
  59205. awayX = this.borderLimit + globalViewport.x - this._positionX;
  59206. }
  59207. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  59208. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  59209. }
  59210. else {
  59211. awayX = 0;
  59212. }
  59213. if (this._positionY < this.borderLimit + globalViewport.y) {
  59214. awayY = this.borderLimit + globalViewport.y - this._positionY;
  59215. }
  59216. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  59217. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  59218. }
  59219. else {
  59220. awayY = 0;
  59221. }
  59222. var away = (awayX > awayY) ? awayX : awayY;
  59223. away -= this.viewportBorder;
  59224. if (away > this.borderLimit) {
  59225. away = this.borderLimit;
  59226. }
  59227. var intensity = 1.0 - (away / this.borderLimit);
  59228. if (intensity < 0) {
  59229. return false;
  59230. }
  59231. if (intensity > 1.0) {
  59232. intensity = 1.0;
  59233. }
  59234. if (this.viewportBorder > 0) {
  59235. globalViewport.x += this.viewportBorder;
  59236. globalViewport.y += this.viewportBorder;
  59237. globalViewport.width -= this.viewportBorder * 2;
  59238. globalViewport.height -= this.viewportBorder * 2;
  59239. this._positionX -= this.viewportBorder;
  59240. this._positionY -= this.viewportBorder;
  59241. }
  59242. // Position
  59243. var centerX = globalViewport.x + globalViewport.width / 2;
  59244. var centerY = globalViewport.y + globalViewport.height / 2;
  59245. var distX = centerX - this._positionX;
  59246. var distY = centerY - this._positionY;
  59247. // Effects
  59248. engine.enableEffect(this._effect);
  59249. engine.setState(false);
  59250. engine.setDepthBuffer(false);
  59251. // VBOs
  59252. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59253. // Flares
  59254. for (var index = 0; index < this.lensFlares.length; index++) {
  59255. var flare = this.lensFlares[index];
  59256. engine.setAlphaMode(flare.alphaMode);
  59257. var x = centerX - (distX * flare.position);
  59258. var y = centerY - (distY * flare.position);
  59259. var cw = flare.size;
  59260. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  59261. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  59262. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  59263. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  59264. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  59265. // Texture
  59266. this._effect.setTexture("textureSampler", flare.texture);
  59267. // Color
  59268. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  59269. // Draw order
  59270. engine.draw(true, 0, 6);
  59271. }
  59272. engine.setDepthBuffer(true);
  59273. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59274. return true;
  59275. };
  59276. LensFlareSystem.prototype.dispose = function () {
  59277. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59278. if (vertexBuffer) {
  59279. vertexBuffer.dispose();
  59280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59281. }
  59282. if (this._indexBuffer) {
  59283. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59284. this._indexBuffer = null;
  59285. }
  59286. while (this.lensFlares.length) {
  59287. this.lensFlares[0].dispose();
  59288. }
  59289. // Remove from scene
  59290. var index = this._scene.lensFlareSystems.indexOf(this);
  59291. this._scene.lensFlareSystems.splice(index, 1);
  59292. };
  59293. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  59294. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  59295. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  59296. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  59297. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  59298. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  59299. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  59300. var parsedFlare = parsedLensFlareSystem.flares[index];
  59301. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  59302. }
  59303. return lensFlareSystem;
  59304. };
  59305. LensFlareSystem.prototype.serialize = function () {
  59306. var serializationObject = {};
  59307. serializationObject.id = this.id;
  59308. serializationObject.name = this.name;
  59309. serializationObject.emitterId = this.getEmitter().id;
  59310. serializationObject.borderLimit = this.borderLimit;
  59311. serializationObject.flares = [];
  59312. for (var index = 0; index < this.lensFlares.length; index++) {
  59313. var flare = this.lensFlares[index];
  59314. serializationObject.flares.push({
  59315. size: flare.size,
  59316. position: flare.position,
  59317. color: flare.color.asArray(),
  59318. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  59319. });
  59320. }
  59321. return serializationObject;
  59322. };
  59323. return LensFlareSystem;
  59324. }());
  59325. BABYLON.LensFlareSystem = LensFlareSystem;
  59326. })(BABYLON || (BABYLON = {}));
  59327. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  59328. var BABYLON;
  59329. (function (BABYLON) {
  59330. /**
  59331. * This is a holder class for the physics joint created by the physics plugin.
  59332. * It holds a set of functions to control the underlying joint.
  59333. */
  59334. var PhysicsJoint = (function () {
  59335. function PhysicsJoint(type, jointData) {
  59336. this.type = type;
  59337. this.jointData = jointData;
  59338. jointData.nativeParams = jointData.nativeParams || {};
  59339. }
  59340. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  59341. get: function () {
  59342. return this._physicsJoint;
  59343. },
  59344. set: function (newJoint) {
  59345. if (this._physicsJoint) {
  59346. //remove from the wolrd
  59347. }
  59348. this._physicsJoint = newJoint;
  59349. },
  59350. enumerable: true,
  59351. configurable: true
  59352. });
  59353. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  59354. set: function (physicsPlugin) {
  59355. this._physicsPlugin = physicsPlugin;
  59356. },
  59357. enumerable: true,
  59358. configurable: true
  59359. });
  59360. /**
  59361. * Execute a function that is physics-plugin specific.
  59362. * @param {Function} func the function that will be executed.
  59363. * It accepts two parameters: the physics world and the physics joint.
  59364. */
  59365. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  59366. func(this._physicsPlugin.world, this._physicsJoint);
  59367. };
  59368. //TODO check if the native joints are the same
  59369. //Joint Types
  59370. PhysicsJoint.DistanceJoint = 0;
  59371. PhysicsJoint.HingeJoint = 1;
  59372. PhysicsJoint.BallAndSocketJoint = 2;
  59373. PhysicsJoint.WheelJoint = 3;
  59374. PhysicsJoint.SliderJoint = 4;
  59375. //OIMO
  59376. PhysicsJoint.PrismaticJoint = 5;
  59377. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  59378. PhysicsJoint.UniversalJoint = 6;
  59379. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  59380. //Cannon
  59381. //Similar to a Ball-Joint. Different in params
  59382. PhysicsJoint.PointToPointJoint = 8;
  59383. //Cannon only at the moment
  59384. PhysicsJoint.SpringJoint = 9;
  59385. PhysicsJoint.LockJoint = 10;
  59386. return PhysicsJoint;
  59387. }());
  59388. BABYLON.PhysicsJoint = PhysicsJoint;
  59389. /**
  59390. * A class representing a physics distance joint.
  59391. */
  59392. var DistanceJoint = (function (_super) {
  59393. __extends(DistanceJoint, _super);
  59394. function DistanceJoint(jointData) {
  59395. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  59396. }
  59397. /**
  59398. * Update the predefined distance.
  59399. */
  59400. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  59401. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  59402. };
  59403. return DistanceJoint;
  59404. }(PhysicsJoint));
  59405. BABYLON.DistanceJoint = DistanceJoint;
  59406. var MotorEnabledJoint = (function (_super) {
  59407. __extends(MotorEnabledJoint, _super);
  59408. function MotorEnabledJoint(type, jointData) {
  59409. return _super.call(this, type, jointData) || this;
  59410. }
  59411. /**
  59412. * Set the motor values.
  59413. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59414. * @param {number} force the force to apply
  59415. * @param {number} maxForce max force for this motor.
  59416. */
  59417. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  59418. this._physicsPlugin.setMotor(this, force, maxForce);
  59419. };
  59420. /**
  59421. * Set the motor's limits.
  59422. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59423. */
  59424. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  59425. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  59426. };
  59427. return MotorEnabledJoint;
  59428. }(PhysicsJoint));
  59429. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  59430. /**
  59431. * This class represents a single hinge physics joint
  59432. */
  59433. var HingeJoint = (function (_super) {
  59434. __extends(HingeJoint, _super);
  59435. function HingeJoint(jointData) {
  59436. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  59437. }
  59438. /**
  59439. * Set the motor values.
  59440. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59441. * @param {number} force the force to apply
  59442. * @param {number} maxForce max force for this motor.
  59443. */
  59444. HingeJoint.prototype.setMotor = function (force, maxForce) {
  59445. this._physicsPlugin.setMotor(this, force, maxForce);
  59446. };
  59447. /**
  59448. * Set the motor's limits.
  59449. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59450. */
  59451. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  59452. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  59453. };
  59454. return HingeJoint;
  59455. }(MotorEnabledJoint));
  59456. BABYLON.HingeJoint = HingeJoint;
  59457. /**
  59458. * This class represents a dual hinge physics joint (same as wheel joint)
  59459. */
  59460. var Hinge2Joint = (function (_super) {
  59461. __extends(Hinge2Joint, _super);
  59462. function Hinge2Joint(jointData) {
  59463. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  59464. }
  59465. /**
  59466. * Set the motor values.
  59467. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59468. * @param {number} force the force to apply
  59469. * @param {number} maxForce max force for this motor.
  59470. * @param {motorIndex} the motor's index, 0 or 1.
  59471. */
  59472. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  59473. if (motorIndex === void 0) { motorIndex = 0; }
  59474. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  59475. };
  59476. /**
  59477. * Set the motor limits.
  59478. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59479. * @param {number} upperLimit the upper limit
  59480. * @param {number} lowerLimit lower limit
  59481. * @param {motorIndex} the motor's index, 0 or 1.
  59482. */
  59483. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  59484. if (motorIndex === void 0) { motorIndex = 0; }
  59485. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  59486. };
  59487. return Hinge2Joint;
  59488. }(MotorEnabledJoint));
  59489. BABYLON.Hinge2Joint = Hinge2Joint;
  59490. })(BABYLON || (BABYLON = {}));
  59491. //# sourceMappingURL=babylon.physicsJoint.js.map
  59492. var BABYLON;
  59493. (function (BABYLON) {
  59494. var PhysicsImpostor = (function () {
  59495. function PhysicsImpostor(object, type, _options, _scene) {
  59496. if (_options === void 0) { _options = { mass: 0 }; }
  59497. var _this = this;
  59498. this.object = object;
  59499. this.type = type;
  59500. this._options = _options;
  59501. this._scene = _scene;
  59502. this._bodyUpdateRequired = false;
  59503. this._onBeforePhysicsStepCallbacks = new Array();
  59504. this._onAfterPhysicsStepCallbacks = new Array();
  59505. this._onPhysicsCollideCallbacks = [];
  59506. this._deltaPosition = BABYLON.Vector3.Zero();
  59507. this._isDisposed = false;
  59508. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  59509. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  59510. /**
  59511. * this function is executed by the physics engine.
  59512. */
  59513. this.beforeStep = function () {
  59514. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  59515. //conjugate deltaRotation
  59516. if (_this._deltaRotationConjugated) {
  59517. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  59518. }
  59519. else {
  59520. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  59521. }
  59522. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  59523. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  59524. func(_this);
  59525. });
  59526. };
  59527. /**
  59528. * this function is executed by the physics engine.
  59529. */
  59530. this.afterStep = function () {
  59531. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  59532. func(_this);
  59533. });
  59534. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  59535. _this.object.position.addInPlace(_this._deltaPosition);
  59536. if (_this._deltaRotation) {
  59537. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  59538. }
  59539. };
  59540. /**
  59541. * Legacy collision detection event support
  59542. */
  59543. this.onCollideEvent = null;
  59544. //event and body object due to cannon's event-based architecture.
  59545. this.onCollide = function (e) {
  59546. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  59547. return;
  59548. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  59549. if (otherImpostor) {
  59550. // Legacy collision detection event support
  59551. if (_this.onCollideEvent) {
  59552. _this.onCollideEvent(_this, otherImpostor);
  59553. }
  59554. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  59555. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  59556. }).forEach(function (obj) {
  59557. obj.callback(_this, otherImpostor);
  59558. });
  59559. }
  59560. };
  59561. //sanity check!
  59562. if (!this.object) {
  59563. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  59564. return;
  59565. }
  59566. //legacy support for old syntax.
  59567. if (!this._scene && object.getScene) {
  59568. this._scene = object.getScene();
  59569. }
  59570. this._physicsEngine = this._scene.getPhysicsEngine();
  59571. if (!this._physicsEngine) {
  59572. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  59573. }
  59574. else {
  59575. //set the object's quaternion, if not set
  59576. if (!this.object.rotationQuaternion) {
  59577. if (this.object.rotation) {
  59578. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  59579. }
  59580. else {
  59581. this.object.rotationQuaternion = new BABYLON.Quaternion();
  59582. }
  59583. }
  59584. //default options params
  59585. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  59586. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  59587. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  59588. this._joints = [];
  59589. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  59590. if (!this.object.parent) {
  59591. this._init();
  59592. }
  59593. else if (this.object.parent.physicsImpostor) {
  59594. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  59595. }
  59596. }
  59597. }
  59598. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  59599. get: function () {
  59600. return this._isDisposed;
  59601. },
  59602. enumerable: true,
  59603. configurable: true
  59604. });
  59605. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  59606. get: function () {
  59607. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  59608. },
  59609. set: function (value) {
  59610. this.setMass(value);
  59611. },
  59612. enumerable: true,
  59613. configurable: true
  59614. });
  59615. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  59616. get: function () {
  59617. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  59618. },
  59619. set: function (value) {
  59620. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  59621. },
  59622. enumerable: true,
  59623. configurable: true
  59624. });
  59625. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  59626. get: function () {
  59627. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  59628. },
  59629. set: function (value) {
  59630. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  59631. },
  59632. enumerable: true,
  59633. configurable: true
  59634. });
  59635. /**
  59636. * This function will completly initialize this impostor.
  59637. * It will create a new body - but only if this mesh has no parent.
  59638. * If it has, this impostor will not be used other than to define the impostor
  59639. * of the child mesh.
  59640. */
  59641. PhysicsImpostor.prototype._init = function () {
  59642. this._physicsEngine.removeImpostor(this);
  59643. this.physicsBody = null;
  59644. this._parent = this._parent || this._getPhysicsParent();
  59645. if (!this.parent) {
  59646. this._physicsEngine.addImpostor(this);
  59647. }
  59648. };
  59649. PhysicsImpostor.prototype._getPhysicsParent = function () {
  59650. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  59651. var parentMesh = this.object.parent;
  59652. return parentMesh.physicsImpostor;
  59653. }
  59654. return;
  59655. };
  59656. /**
  59657. * Should a new body be generated.
  59658. */
  59659. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  59660. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  59661. };
  59662. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  59663. this.forceUpdate();
  59664. };
  59665. /**
  59666. * Force a regeneration of this or the parent's impostor's body.
  59667. * Use under cautious - This will remove all joints already implemented.
  59668. */
  59669. PhysicsImpostor.prototype.forceUpdate = function () {
  59670. this._init();
  59671. if (this.parent) {
  59672. this.parent.forceUpdate();
  59673. }
  59674. };
  59675. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  59676. /*public get mesh(): AbstractMesh {
  59677. return this._mesh;
  59678. }*/
  59679. /**
  59680. * Gets the body that holds this impostor. Either its own, or its parent.
  59681. */
  59682. get: function () {
  59683. return this._parent ? this._parent.physicsBody : this._physicsBody;
  59684. },
  59685. /**
  59686. * Set the physics body. Used mainly by the physics engine/plugin
  59687. */
  59688. set: function (physicsBody) {
  59689. if (this._physicsBody) {
  59690. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  59691. }
  59692. this._physicsBody = physicsBody;
  59693. this.resetUpdateFlags();
  59694. },
  59695. enumerable: true,
  59696. configurable: true
  59697. });
  59698. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  59699. get: function () {
  59700. return this._parent;
  59701. },
  59702. set: function (value) {
  59703. this._parent = value;
  59704. },
  59705. enumerable: true,
  59706. configurable: true
  59707. });
  59708. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  59709. this._bodyUpdateRequired = false;
  59710. };
  59711. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  59712. if (this.object.getBoundingInfo) {
  59713. var q = this.object.rotationQuaternion;
  59714. //reset rotation
  59715. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  59716. //calculate the world matrix with no rotation
  59717. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  59718. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  59719. //bring back the rotation
  59720. this.object.rotationQuaternion = q;
  59721. //calculate the world matrix with the new rotation
  59722. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  59723. return size;
  59724. }
  59725. else {
  59726. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  59727. }
  59728. };
  59729. PhysicsImpostor.prototype.getObjectCenter = function () {
  59730. if (this.object.getBoundingInfo) {
  59731. return this.object.getBoundingInfo().boundingBox.centerWorld;
  59732. }
  59733. else {
  59734. return this.object.position;
  59735. }
  59736. };
  59737. /**
  59738. * Get a specific parametes from the options parameter.
  59739. */
  59740. PhysicsImpostor.prototype.getParam = function (paramName) {
  59741. return this._options[paramName];
  59742. };
  59743. /**
  59744. * Sets a specific parameter in the options given to the physics plugin
  59745. */
  59746. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  59747. this._options[paramName] = value;
  59748. this._bodyUpdateRequired = true;
  59749. };
  59750. /**
  59751. * Specifically change the body's mass option. Won't recreate the physics body object
  59752. */
  59753. PhysicsImpostor.prototype.setMass = function (mass) {
  59754. if (this.getParam("mass") !== mass) {
  59755. this.setParam("mass", mass);
  59756. }
  59757. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  59758. };
  59759. PhysicsImpostor.prototype.getLinearVelocity = function () {
  59760. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  59761. };
  59762. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  59763. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  59764. };
  59765. PhysicsImpostor.prototype.getAngularVelocity = function () {
  59766. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  59767. };
  59768. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  59769. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  59770. };
  59771. /**
  59772. * Execute a function with the physics plugin native code.
  59773. * Provide a function the will have two variables - the world object and the physics body object.
  59774. */
  59775. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  59776. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  59777. };
  59778. /**
  59779. * Register a function that will be executed before the physics world is stepping forward.
  59780. */
  59781. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  59782. this._onBeforePhysicsStepCallbacks.push(func);
  59783. };
  59784. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  59785. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  59786. if (index > -1) {
  59787. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  59788. }
  59789. else {
  59790. BABYLON.Tools.Warn("Function to remove was not found");
  59791. }
  59792. };
  59793. /**
  59794. * Register a function that will be executed after the physics step
  59795. */
  59796. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  59797. this._onAfterPhysicsStepCallbacks.push(func);
  59798. };
  59799. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  59800. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  59801. if (index > -1) {
  59802. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  59803. }
  59804. else {
  59805. BABYLON.Tools.Warn("Function to remove was not found");
  59806. }
  59807. };
  59808. /**
  59809. * register a function that will be executed when this impostor collides against a different body.
  59810. */
  59811. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  59812. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  59813. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  59814. };
  59815. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  59816. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  59817. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  59818. if (index > -1) {
  59819. this._onPhysicsCollideCallbacks.splice(index, 1);
  59820. }
  59821. else {
  59822. BABYLON.Tools.Warn("Function to remove was not found");
  59823. }
  59824. };
  59825. /**
  59826. * Apply a force
  59827. */
  59828. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  59829. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  59830. };
  59831. /**
  59832. * Apply an impulse
  59833. */
  59834. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  59835. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  59836. };
  59837. /**
  59838. * A help function to create a joint.
  59839. */
  59840. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  59841. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  59842. this.addJoint(otherImpostor, joint);
  59843. };
  59844. /**
  59845. * Add a joint to this impostor with a different impostor.
  59846. */
  59847. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  59848. this._joints.push({
  59849. otherImpostor: otherImpostor,
  59850. joint: joint
  59851. });
  59852. this._physicsEngine.addJoint(this, otherImpostor, joint);
  59853. };
  59854. /**
  59855. * Will keep this body still, in a sleep mode.
  59856. */
  59857. PhysicsImpostor.prototype.sleep = function () {
  59858. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  59859. };
  59860. /**
  59861. * Wake the body up.
  59862. */
  59863. PhysicsImpostor.prototype.wakeUp = function () {
  59864. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  59865. };
  59866. PhysicsImpostor.prototype.clone = function (newObject) {
  59867. if (!newObject)
  59868. return null;
  59869. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  59870. };
  59871. PhysicsImpostor.prototype.dispose = function () {
  59872. var _this = this;
  59873. //no dispose if no physics engine is available.
  59874. if (!this._physicsEngine) {
  59875. return;
  59876. }
  59877. this._joints.forEach(function (j) {
  59878. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  59879. });
  59880. //dispose the physics body
  59881. this._physicsEngine.removeImpostor(this);
  59882. if (this.parent) {
  59883. this.parent.forceUpdate();
  59884. }
  59885. else {
  59886. /*this._object.getChildMeshes().forEach(function(mesh) {
  59887. if (mesh.physicsImpostor) {
  59888. if (disposeChildren) {
  59889. mesh.physicsImpostor.dispose();
  59890. mesh.physicsImpostor = null;
  59891. }
  59892. }
  59893. })*/
  59894. }
  59895. this._isDisposed = true;
  59896. };
  59897. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  59898. this._deltaPosition.copyFrom(position);
  59899. };
  59900. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  59901. if (!this._deltaRotation) {
  59902. this._deltaRotation = new BABYLON.Quaternion();
  59903. }
  59904. this._deltaRotation.copyFrom(rotation);
  59905. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  59906. };
  59907. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  59908. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  59909. };
  59910. PhysicsImpostor.prototype.getRadius = function () {
  59911. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  59912. };
  59913. /**
  59914. * Sync a bone with this impostor
  59915. * @param bone The bone to sync to the impostor.
  59916. * @param boneMesh The mesh that the bone is influencing.
  59917. * @param jointPivot The pivot of the joint / bone in local space.
  59918. * @param distToJoint Optional distance from the impostor to the joint.
  59919. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  59920. */
  59921. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  59922. var tempVec = PhysicsImpostor._tmpVecs[0];
  59923. var mesh = this.object;
  59924. if (adjustRotation) {
  59925. var tempQuat = PhysicsImpostor._tmpQuat;
  59926. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  59927. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  59928. }
  59929. else {
  59930. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  59931. }
  59932. tempVec.x = 0;
  59933. tempVec.y = 0;
  59934. tempVec.z = 0;
  59935. if (jointPivot) {
  59936. tempVec.x = jointPivot.x;
  59937. tempVec.y = jointPivot.y;
  59938. tempVec.z = jointPivot.z;
  59939. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  59940. if (distToJoint === undefined || distToJoint === null) {
  59941. distToJoint = jointPivot.length();
  59942. }
  59943. tempVec.x *= distToJoint;
  59944. tempVec.y *= distToJoint;
  59945. tempVec.z *= distToJoint;
  59946. }
  59947. if (bone.getParent()) {
  59948. tempVec.addInPlace(mesh.getAbsolutePosition());
  59949. bone.setAbsolutePosition(tempVec, boneMesh);
  59950. }
  59951. else {
  59952. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  59953. boneMesh.position.x -= tempVec.x;
  59954. boneMesh.position.y -= tempVec.y;
  59955. boneMesh.position.z -= tempVec.z;
  59956. }
  59957. };
  59958. /**
  59959. * Sync impostor to a bone
  59960. * @param bone The bone that the impostor will be synced to.
  59961. * @param boneMesh The mesh that the bone is influencing.
  59962. * @param jointPivot The pivot of the joint / bone in local space.
  59963. * @param distToJoint Optional distance from the impostor to the joint.
  59964. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  59965. * @param boneAxis Optional vector3 axis the bone is aligned with
  59966. */
  59967. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  59968. var mesh = this.object;
  59969. if (adjustRotation) {
  59970. var tempQuat = PhysicsImpostor._tmpQuat;
  59971. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  59972. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  59973. }
  59974. else {
  59975. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  59976. }
  59977. var pos = PhysicsImpostor._tmpVecs[0];
  59978. var boneDir = PhysicsImpostor._tmpVecs[1];
  59979. if (!boneAxis) {
  59980. boneAxis = PhysicsImpostor._tmpVecs[2];
  59981. boneAxis.x = 0;
  59982. boneAxis.y = 1;
  59983. boneAxis.z = 0;
  59984. }
  59985. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  59986. bone.getAbsolutePositionToRef(boneMesh, pos);
  59987. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  59988. distToJoint = jointPivot.length();
  59989. }
  59990. if (distToJoint !== undefined && distToJoint !== null) {
  59991. pos.x += boneDir.x * distToJoint;
  59992. pos.y += boneDir.y * distToJoint;
  59993. pos.z += boneDir.z * distToJoint;
  59994. }
  59995. mesh.setAbsolutePosition(pos);
  59996. };
  59997. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  59998. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  59999. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60000. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  60001. //Impostor types
  60002. PhysicsImpostor.NoImpostor = 0;
  60003. PhysicsImpostor.SphereImpostor = 1;
  60004. PhysicsImpostor.BoxImpostor = 2;
  60005. PhysicsImpostor.PlaneImpostor = 3;
  60006. PhysicsImpostor.MeshImpostor = 4;
  60007. PhysicsImpostor.CylinderImpostor = 7;
  60008. PhysicsImpostor.ParticleImpostor = 8;
  60009. PhysicsImpostor.HeightmapImpostor = 9;
  60010. return PhysicsImpostor;
  60011. }());
  60012. BABYLON.PhysicsImpostor = PhysicsImpostor;
  60013. })(BABYLON || (BABYLON = {}));
  60014. //# sourceMappingURL=babylon.physicsImpostor.js.map
  60015. var BABYLON;
  60016. (function (BABYLON) {
  60017. var PhysicsEngine = (function () {
  60018. function PhysicsEngine(gravity, _physicsPlugin) {
  60019. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  60020. this._physicsPlugin = _physicsPlugin;
  60021. //new methods and parameters
  60022. this._impostors = [];
  60023. this._joints = [];
  60024. if (!this._physicsPlugin.isSupported()) {
  60025. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  60026. + "Please make sure it is included.");
  60027. }
  60028. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  60029. this.setGravity(gravity);
  60030. this.setTimeStep();
  60031. }
  60032. PhysicsEngine.prototype.setGravity = function (gravity) {
  60033. this.gravity = gravity;
  60034. this._physicsPlugin.setGravity(this.gravity);
  60035. };
  60036. /**
  60037. * Set the time step of the physics engine.
  60038. * default is 1/60.
  60039. * To slow it down, enter 1/600 for example.
  60040. * To speed it up, 1/30
  60041. * @param {number} newTimeStep the new timestep to apply to this world.
  60042. */
  60043. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  60044. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  60045. this._physicsPlugin.setTimeStep(newTimeStep);
  60046. };
  60047. /**
  60048. * Get the time step of the physics engine.
  60049. */
  60050. PhysicsEngine.prototype.getTimeStep = function () {
  60051. return this._physicsPlugin.getTimeStep();
  60052. };
  60053. PhysicsEngine.prototype.dispose = function () {
  60054. this._impostors.forEach(function (impostor) {
  60055. impostor.dispose();
  60056. });
  60057. this._physicsPlugin.dispose();
  60058. };
  60059. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  60060. return this._physicsPlugin.name;
  60061. };
  60062. /**
  60063. * Adding a new impostor for the impostor tracking.
  60064. * This will be done by the impostor itself.
  60065. * @param {PhysicsImpostor} impostor the impostor to add
  60066. */
  60067. PhysicsEngine.prototype.addImpostor = function (impostor) {
  60068. impostor.uniqueId = this._impostors.push(impostor);
  60069. //if no parent, generate the body
  60070. if (!impostor.parent) {
  60071. this._physicsPlugin.generatePhysicsBody(impostor);
  60072. }
  60073. };
  60074. /**
  60075. * Remove an impostor from the engine.
  60076. * This impostor and its mesh will not longer be updated by the physics engine.
  60077. * @param {PhysicsImpostor} impostor the impostor to remove
  60078. */
  60079. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  60080. var index = this._impostors.indexOf(impostor);
  60081. if (index > -1) {
  60082. var removed = this._impostors.splice(index, 1);
  60083. //Is it needed?
  60084. if (removed.length) {
  60085. //this will also remove it from the world.
  60086. removed[0].physicsBody = null;
  60087. }
  60088. }
  60089. };
  60090. /**
  60091. * Add a joint to the physics engine
  60092. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  60093. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  60094. * @param {PhysicsJoint} the joint that will connect both impostors.
  60095. */
  60096. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  60097. var impostorJoint = {
  60098. mainImpostor: mainImpostor,
  60099. connectedImpostor: connectedImpostor,
  60100. joint: joint
  60101. };
  60102. joint.physicsPlugin = this._physicsPlugin;
  60103. this._joints.push(impostorJoint);
  60104. this._physicsPlugin.generateJoint(impostorJoint);
  60105. };
  60106. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  60107. var matchingJoints = this._joints.filter(function (impostorJoint) {
  60108. return (impostorJoint.connectedImpostor === connectedImpostor
  60109. && impostorJoint.joint === joint
  60110. && impostorJoint.mainImpostor === mainImpostor);
  60111. });
  60112. if (matchingJoints.length) {
  60113. this._physicsPlugin.removeJoint(matchingJoints[0]);
  60114. //TODO remove it from the list as well
  60115. }
  60116. };
  60117. /**
  60118. * Called by the scene. no need to call it.
  60119. */
  60120. PhysicsEngine.prototype._step = function (delta) {
  60121. var _this = this;
  60122. //check if any mesh has no body / requires an update
  60123. this._impostors.forEach(function (impostor) {
  60124. if (impostor.isBodyInitRequired()) {
  60125. _this._physicsPlugin.generatePhysicsBody(impostor);
  60126. }
  60127. });
  60128. if (delta > 0.1) {
  60129. delta = 0.1;
  60130. }
  60131. else if (delta <= 0) {
  60132. delta = 1.0 / 60.0;
  60133. }
  60134. this._physicsPlugin.executeStep(delta, this._impostors);
  60135. };
  60136. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  60137. return this._physicsPlugin;
  60138. };
  60139. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  60140. for (var i = 0; i < this._impostors.length; ++i) {
  60141. if (this._impostors[i].object === object) {
  60142. return this._impostors[i];
  60143. }
  60144. }
  60145. };
  60146. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  60147. for (var i = 0; i < this._impostors.length; ++i) {
  60148. if (this._impostors[i].physicsBody === body) {
  60149. return this._impostors[i];
  60150. }
  60151. }
  60152. };
  60153. // Statics
  60154. PhysicsEngine.Epsilon = 0.001;
  60155. return PhysicsEngine;
  60156. }());
  60157. BABYLON.PhysicsEngine = PhysicsEngine;
  60158. })(BABYLON || (BABYLON = {}));
  60159. //# sourceMappingURL=babylon.physicsEngine.js.map
  60160. var BABYLON;
  60161. (function (BABYLON) {
  60162. var CannonJSPlugin = (function () {
  60163. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  60164. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  60165. if (iterations === void 0) { iterations = 10; }
  60166. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  60167. this.name = "CannonJSPlugin";
  60168. this._physicsMaterials = [];
  60169. this._fixedTimeStep = 1 / 60;
  60170. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60171. this._currentCollisionGroup = 2;
  60172. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  60173. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  60174. this._tmpPosition = BABYLON.Vector3.Zero();
  60175. this._tmpQuaternion = new BABYLON.Quaternion();
  60176. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  60177. this._tmpDeltaRotation = new BABYLON.Quaternion();
  60178. this._tmpUnityRotation = new BABYLON.Quaternion();
  60179. if (!this.isSupported()) {
  60180. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  60181. return;
  60182. }
  60183. this.world = new CANNON.World();
  60184. this.world.broadphase = new CANNON.NaiveBroadphase();
  60185. this.world.solver.iterations = iterations;
  60186. }
  60187. CannonJSPlugin.prototype.setGravity = function (gravity) {
  60188. this.world.gravity.copy(gravity);
  60189. };
  60190. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  60191. this._fixedTimeStep = timeStep;
  60192. };
  60193. CannonJSPlugin.prototype.getTimeStep = function () {
  60194. return this._fixedTimeStep;
  60195. };
  60196. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  60197. // Delta is in seconds, should be provided in milliseconds
  60198. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  60199. };
  60200. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  60201. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60202. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  60203. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  60204. };
  60205. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  60206. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60207. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  60208. impostor.physicsBody.applyForce(impulse, worldPoint);
  60209. };
  60210. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  60211. //parent-child relationship. Does this impostor has a parent impostor?
  60212. if (impostor.parent) {
  60213. if (impostor.physicsBody) {
  60214. this.removePhysicsBody(impostor);
  60215. //TODO is that needed?
  60216. impostor.forceUpdate();
  60217. }
  60218. return;
  60219. }
  60220. //should a new body be created for this impostor?
  60221. if (impostor.isBodyInitRequired()) {
  60222. var shape = this._createShape(impostor);
  60223. //unregister events, if body is being changed
  60224. var oldBody = impostor.physicsBody;
  60225. if (oldBody) {
  60226. this.removePhysicsBody(impostor);
  60227. }
  60228. //create the body and material
  60229. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  60230. var bodyCreationObject = {
  60231. mass: impostor.getParam("mass"),
  60232. material: material
  60233. };
  60234. // A simple extend, in case native options were used.
  60235. var nativeOptions = impostor.getParam("nativeOptions");
  60236. for (var key in nativeOptions) {
  60237. if (nativeOptions.hasOwnProperty(key)) {
  60238. bodyCreationObject[key] = nativeOptions[key];
  60239. }
  60240. }
  60241. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  60242. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  60243. this.world.addEventListener("preStep", impostor.beforeStep);
  60244. this.world.addEventListener("postStep", impostor.afterStep);
  60245. impostor.physicsBody.addShape(shape);
  60246. this.world.add(impostor.physicsBody);
  60247. //try to keep the body moving in the right direction by taking old properties.
  60248. //Should be tested!
  60249. if (oldBody) {
  60250. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  60251. impostor.physicsBody[param].copy(oldBody[param]);
  60252. });
  60253. }
  60254. this._processChildMeshes(impostor);
  60255. }
  60256. //now update the body's transformation
  60257. this._updatePhysicsBodyTransformation(impostor);
  60258. };
  60259. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  60260. var _this = this;
  60261. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  60262. if (meshChildren.length) {
  60263. var processMesh = function (localPosition, mesh) {
  60264. var childImpostor = mesh.getPhysicsImpostor();
  60265. if (childImpostor) {
  60266. var parent = childImpostor.parent;
  60267. if (parent !== mainImpostor) {
  60268. var localPosition = mesh.position;
  60269. if (childImpostor.physicsBody) {
  60270. _this.removePhysicsBody(childImpostor);
  60271. childImpostor.physicsBody = null;
  60272. }
  60273. childImpostor.parent = mainImpostor;
  60274. childImpostor.resetUpdateFlags();
  60275. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  60276. //Add the mass of the children.
  60277. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  60278. }
  60279. }
  60280. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  60281. };
  60282. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  60283. }
  60284. };
  60285. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  60286. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  60287. this.world.removeEventListener("preStep", impostor.beforeStep);
  60288. this.world.removeEventListener("postStep", impostor.afterStep);
  60289. this.world.remove(impostor.physicsBody);
  60290. };
  60291. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  60292. var mainBody = impostorJoint.mainImpostor.physicsBody;
  60293. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  60294. if (!mainBody || !connectedBody) {
  60295. return;
  60296. }
  60297. var constraint;
  60298. var jointData = impostorJoint.joint.jointData;
  60299. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60300. var constraintData = {
  60301. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  60302. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  60303. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  60304. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  60305. maxForce: jointData.nativeParams.maxForce,
  60306. collideConnected: !!jointData.collision
  60307. };
  60308. switch (impostorJoint.joint.type) {
  60309. case BABYLON.PhysicsJoint.HingeJoint:
  60310. case BABYLON.PhysicsJoint.Hinge2Joint:
  60311. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  60312. break;
  60313. case BABYLON.PhysicsJoint.DistanceJoint:
  60314. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  60315. break;
  60316. case BABYLON.PhysicsJoint.SpringJoint:
  60317. var springData = jointData;
  60318. constraint = new CANNON.Spring(mainBody, connectedBody, {
  60319. restLength: springData.length,
  60320. stiffness: springData.stiffness,
  60321. damping: springData.damping,
  60322. localAnchorA: constraintData.pivotA,
  60323. localAnchorB: constraintData.pivotB
  60324. });
  60325. break;
  60326. case BABYLON.PhysicsJoint.LockJoint:
  60327. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  60328. break;
  60329. case BABYLON.PhysicsJoint.PointToPointJoint:
  60330. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  60331. default:
  60332. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  60333. break;
  60334. }
  60335. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  60336. constraint.collideConnected = !!jointData.collision;
  60337. impostorJoint.joint.physicsJoint = constraint;
  60338. //don't add spring as constraint, as it is not one.
  60339. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  60340. this.world.addConstraint(constraint);
  60341. }
  60342. else {
  60343. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  60344. constraint.applyForce();
  60345. });
  60346. }
  60347. };
  60348. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  60349. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  60350. };
  60351. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  60352. var index;
  60353. var mat;
  60354. for (index = 0; index < this._physicsMaterials.length; index++) {
  60355. mat = this._physicsMaterials[index];
  60356. if (mat.friction === friction && mat.restitution === restitution) {
  60357. return mat;
  60358. }
  60359. }
  60360. var currentMat = new CANNON.Material(name);
  60361. currentMat.friction = friction;
  60362. currentMat.restitution = restitution;
  60363. this._physicsMaterials.push(currentMat);
  60364. return currentMat;
  60365. };
  60366. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  60367. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  60368. };
  60369. CannonJSPlugin.prototype._createShape = function (impostor) {
  60370. var object = impostor.object;
  60371. var returnValue;
  60372. var extendSize = impostor.getObjectExtendSize();
  60373. switch (impostor.type) {
  60374. case BABYLON.PhysicsImpostor.SphereImpostor:
  60375. var radiusX = extendSize.x;
  60376. var radiusY = extendSize.y;
  60377. var radiusZ = extendSize.z;
  60378. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  60379. break;
  60380. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  60381. case BABYLON.PhysicsImpostor.CylinderImpostor:
  60382. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  60383. break;
  60384. case BABYLON.PhysicsImpostor.BoxImpostor:
  60385. var box = extendSize.scale(0.5);
  60386. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  60387. break;
  60388. case BABYLON.PhysicsImpostor.PlaneImpostor:
  60389. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  60390. returnValue = new CANNON.Plane();
  60391. break;
  60392. case BABYLON.PhysicsImpostor.MeshImpostor:
  60393. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  60394. var rawFaces = object.getIndices ? object.getIndices() : [];
  60395. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  60396. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  60397. break;
  60398. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  60399. returnValue = this._createHeightmap(object);
  60400. break;
  60401. case BABYLON.PhysicsImpostor.ParticleImpostor:
  60402. returnValue = new CANNON.Particle();
  60403. break;
  60404. }
  60405. return returnValue;
  60406. };
  60407. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  60408. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60409. var matrix = [];
  60410. //For now pointDepth will not be used and will be automatically calculated.
  60411. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  60412. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  60413. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  60414. var elementSize = dim * 2 / arraySize;
  60415. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  60416. for (var i = 0; i < pos.length; i = i + 3) {
  60417. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  60418. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  60419. var y = pos[i + 1] + minY;
  60420. if (!matrix[x]) {
  60421. matrix[x] = [];
  60422. }
  60423. if (!matrix[x][z]) {
  60424. matrix[x][z] = y;
  60425. }
  60426. matrix[x][z] = Math.max(y, matrix[x][z]);
  60427. }
  60428. for (var x = 0; x <= arraySize; ++x) {
  60429. if (!matrix[x]) {
  60430. var loc = 1;
  60431. while (!matrix[(x + loc) % arraySize]) {
  60432. loc++;
  60433. }
  60434. matrix[x] = matrix[(x + loc) % arraySize].slice();
  60435. //console.log("missing x", x);
  60436. }
  60437. for (var z = 0; z <= arraySize; ++z) {
  60438. if (!matrix[x][z]) {
  60439. var loc = 1;
  60440. var newValue;
  60441. while (newValue === undefined) {
  60442. newValue = matrix[x][(z + loc++) % arraySize];
  60443. }
  60444. matrix[x][z] = newValue;
  60445. }
  60446. }
  60447. }
  60448. var shape = new CANNON.Heightfield(matrix, {
  60449. elementSize: elementSize
  60450. });
  60451. //For future reference, needed for body transformation
  60452. shape.minY = minY;
  60453. return shape;
  60454. };
  60455. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  60456. var object = impostor.object;
  60457. //make sure it is updated...
  60458. object.computeWorldMatrix && object.computeWorldMatrix(true);
  60459. // The delta between the mesh position and the mesh bounding box center
  60460. var center = impostor.getObjectCenter();
  60461. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  60462. this._tmpPosition.copyFrom(center);
  60463. var quaternion = object.rotationQuaternion;
  60464. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  60465. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  60466. //-90 DEG in X, precalculated
  60467. quaternion = quaternion.multiply(this._minus90X);
  60468. //Invert! (Precalculated, 90 deg in X)
  60469. //No need to clone. this will never change.
  60470. impostor.setDeltaRotation(this._plus90X);
  60471. }
  60472. //If it is a heightfield, if should be centered.
  60473. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  60474. var mesh = object;
  60475. //calculate the correct body position:
  60476. var rotationQuaternion = mesh.rotationQuaternion;
  60477. mesh.rotationQuaternion = this._tmpUnityRotation;
  60478. mesh.computeWorldMatrix(true);
  60479. //get original center with no rotation
  60480. var c = center.clone();
  60481. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  60482. //rotation is back
  60483. mesh.rotationQuaternion = rotationQuaternion;
  60484. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  60485. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  60486. mesh.setPivotMatrix(p);
  60487. mesh.computeWorldMatrix(true);
  60488. //calculate the translation
  60489. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  60490. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  60491. //add it inverted to the delta
  60492. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  60493. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  60494. mesh.setPivotMatrix(oldPivot);
  60495. mesh.computeWorldMatrix(true);
  60496. }
  60497. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  60498. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  60499. this._tmpPosition.copyFrom(object.position);
  60500. }
  60501. impostor.setDeltaPosition(this._tmpDeltaPosition);
  60502. //Now update the impostor object
  60503. impostor.physicsBody.position.copy(this._tmpPosition);
  60504. impostor.physicsBody.quaternion.copy(quaternion);
  60505. };
  60506. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  60507. impostor.object.position.copyFrom(impostor.physicsBody.position);
  60508. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  60509. };
  60510. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  60511. impostor.physicsBody.position.copy(newPosition);
  60512. impostor.physicsBody.quaternion.copy(newRotation);
  60513. };
  60514. CannonJSPlugin.prototype.isSupported = function () {
  60515. return window.CANNON !== undefined;
  60516. };
  60517. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  60518. impostor.physicsBody.velocity.copy(velocity);
  60519. };
  60520. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  60521. impostor.physicsBody.angularVelocity.copy(velocity);
  60522. };
  60523. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  60524. var v = impostor.physicsBody.velocity;
  60525. if (!v)
  60526. return null;
  60527. return new BABYLON.Vector3(v.x, v.y, v.z);
  60528. };
  60529. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  60530. var v = impostor.physicsBody.angularVelocity;
  60531. if (!v)
  60532. return null;
  60533. return new BABYLON.Vector3(v.x, v.y, v.z);
  60534. };
  60535. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  60536. impostor.physicsBody.mass = mass;
  60537. impostor.physicsBody.updateMassProperties();
  60538. };
  60539. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  60540. return impostor.physicsBody.mass;
  60541. };
  60542. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  60543. return impostor.physicsBody.material.friction;
  60544. };
  60545. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  60546. impostor.physicsBody.material.friction = friction;
  60547. };
  60548. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  60549. return impostor.physicsBody.material.restitution;
  60550. };
  60551. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  60552. impostor.physicsBody.material.restitution = restitution;
  60553. };
  60554. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  60555. impostor.physicsBody.sleep();
  60556. };
  60557. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  60558. impostor.physicsBody.wakeUp();
  60559. };
  60560. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  60561. joint.physicsJoint.distance = maxDistance;
  60562. };
  60563. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  60564. if (!motorIndex) {
  60565. joint.physicsJoint.enableMotor();
  60566. }
  60567. };
  60568. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  60569. if (!motorIndex) {
  60570. joint.physicsJoint.disableMotor();
  60571. }
  60572. };
  60573. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  60574. if (!motorIndex) {
  60575. joint.physicsJoint.enableMotor();
  60576. joint.physicsJoint.setMotorSpeed(speed);
  60577. if (maxForce) {
  60578. this.setLimit(joint, maxForce);
  60579. }
  60580. }
  60581. };
  60582. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  60583. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  60584. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  60585. };
  60586. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  60587. var body = impostor.physicsBody;
  60588. mesh.position.x = body.position.x;
  60589. mesh.position.y = body.position.y;
  60590. mesh.position.z = body.position.z;
  60591. mesh.rotationQuaternion.x = body.quaternion.x;
  60592. mesh.rotationQuaternion.y = body.quaternion.y;
  60593. mesh.rotationQuaternion.z = body.quaternion.z;
  60594. mesh.rotationQuaternion.w = body.quaternion.w;
  60595. };
  60596. CannonJSPlugin.prototype.getRadius = function (impostor) {
  60597. var shape = impostor.physicsBody.shapes[0];
  60598. return shape.boundingSphereRadius;
  60599. };
  60600. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  60601. var shape = impostor.physicsBody.shapes[0];
  60602. result.x = shape.halfExtents.x * 2;
  60603. result.y = shape.halfExtents.y * 2;
  60604. result.z = shape.halfExtents.z * 2;
  60605. };
  60606. CannonJSPlugin.prototype.dispose = function () {
  60607. };
  60608. return CannonJSPlugin;
  60609. }());
  60610. BABYLON.CannonJSPlugin = CannonJSPlugin;
  60611. })(BABYLON || (BABYLON = {}));
  60612. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  60613. var BABYLON;
  60614. (function (BABYLON) {
  60615. var OimoJSPlugin = (function () {
  60616. function OimoJSPlugin(iterations) {
  60617. this.name = "OimoJSPlugin";
  60618. this._tmpImpostorsArray = [];
  60619. this._tmpPositionVector = BABYLON.Vector3.Zero();
  60620. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  60621. this.world.worldscale(1);
  60622. this.world.clear();
  60623. //making sure no stats are calculated
  60624. this.world.isNoStat = true;
  60625. }
  60626. OimoJSPlugin.prototype.setGravity = function (gravity) {
  60627. this.world.gravity.copy(gravity);
  60628. };
  60629. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  60630. this.world.timeStep = timeStep;
  60631. };
  60632. OimoJSPlugin.prototype.getTimeStep = function () {
  60633. return this.world.timeStep;
  60634. };
  60635. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  60636. var _this = this;
  60637. impostors.forEach(function (impostor) {
  60638. impostor.beforeStep();
  60639. });
  60640. this.world.step();
  60641. impostors.forEach(function (impostor) {
  60642. impostor.afterStep();
  60643. //update the ordered impostors array
  60644. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  60645. });
  60646. //check for collisions
  60647. var contact = this.world.contacts;
  60648. while (contact !== null) {
  60649. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  60650. contact = contact.next;
  60651. continue;
  60652. }
  60653. //is this body colliding with any other? get the impostor
  60654. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  60655. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  60656. if (!mainImpostor || !collidingImpostor) {
  60657. contact = contact.next;
  60658. continue;
  60659. }
  60660. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  60661. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  60662. contact = contact.next;
  60663. }
  60664. };
  60665. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  60666. var mass = impostor.physicsBody.massInfo.mass;
  60667. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  60668. };
  60669. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  60670. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  60671. this.applyImpulse(impostor, force, contactPoint);
  60672. };
  60673. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  60674. var _this = this;
  60675. //parent-child relationship. Does this impostor has a parent impostor?
  60676. if (impostor.parent) {
  60677. if (impostor.physicsBody) {
  60678. this.removePhysicsBody(impostor);
  60679. //TODO is that needed?
  60680. impostor.forceUpdate();
  60681. }
  60682. return;
  60683. }
  60684. if (impostor.isBodyInitRequired()) {
  60685. var bodyConfig = {
  60686. name: impostor.uniqueId,
  60687. //Oimo must have mass, also for static objects.
  60688. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  60689. size: [],
  60690. type: [],
  60691. pos: [],
  60692. rot: [],
  60693. move: impostor.getParam("mass") !== 0,
  60694. //Supporting older versions of Oimo
  60695. world: this.world
  60696. };
  60697. var impostors = [impostor];
  60698. var addToArray = function (parent) {
  60699. if (!parent.getChildMeshes)
  60700. return;
  60701. parent.getChildMeshes().forEach(function (m) {
  60702. if (m.physicsImpostor) {
  60703. impostors.push(m.physicsImpostor);
  60704. m.physicsImpostor._init();
  60705. }
  60706. });
  60707. };
  60708. addToArray(impostor.object);
  60709. var checkWithEpsilon_1 = function (value) {
  60710. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  60711. };
  60712. impostors.forEach(function (i) {
  60713. //get the correct bounding box
  60714. var oldQuaternion = i.object.rotationQuaternion;
  60715. var rot = new OIMO.Euler().setFromQuaternion({
  60716. x: impostor.object.rotationQuaternion.x,
  60717. y: impostor.object.rotationQuaternion.y,
  60718. z: impostor.object.rotationQuaternion.z,
  60719. s: impostor.object.rotationQuaternion.w
  60720. });
  60721. var extendSize = i.getObjectExtendSize();
  60722. if (i === impostor) {
  60723. var center = impostor.getObjectCenter();
  60724. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  60725. //Can also use Array.prototype.push.apply
  60726. bodyConfig.pos.push(center.x);
  60727. bodyConfig.pos.push(center.y);
  60728. bodyConfig.pos.push(center.z);
  60729. //tmp solution
  60730. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  60731. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  60732. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  60733. }
  60734. else {
  60735. bodyConfig.pos.push(i.object.position.x);
  60736. bodyConfig.pos.push(i.object.position.y);
  60737. bodyConfig.pos.push(i.object.position.z);
  60738. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  60739. bodyConfig.rot.push(0);
  60740. bodyConfig.rot.push(0);
  60741. bodyConfig.rot.push(0);
  60742. }
  60743. // register mesh
  60744. switch (i.type) {
  60745. case BABYLON.PhysicsImpostor.ParticleImpostor:
  60746. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  60747. case BABYLON.PhysicsImpostor.SphereImpostor:
  60748. var radiusX = extendSize.x;
  60749. var radiusY = extendSize.y;
  60750. var radiusZ = extendSize.z;
  60751. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  60752. bodyConfig.type.push('sphere');
  60753. //due to the way oimo works with compounds, add 3 times
  60754. bodyConfig.size.push(size);
  60755. bodyConfig.size.push(size);
  60756. bodyConfig.size.push(size);
  60757. break;
  60758. case BABYLON.PhysicsImpostor.CylinderImpostor:
  60759. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  60760. var sizeY = checkWithEpsilon_1(extendSize.y);
  60761. bodyConfig.type.push('cylinder');
  60762. bodyConfig.size.push(sizeX);
  60763. bodyConfig.size.push(sizeY);
  60764. //due to the way oimo works with compounds, add one more value.
  60765. bodyConfig.size.push(sizeY);
  60766. break;
  60767. case BABYLON.PhysicsImpostor.PlaneImpostor:
  60768. case BABYLON.PhysicsImpostor.BoxImpostor:
  60769. default:
  60770. var sizeX = checkWithEpsilon_1(extendSize.x);
  60771. var sizeY = checkWithEpsilon_1(extendSize.y);
  60772. var sizeZ = checkWithEpsilon_1(extendSize.z);
  60773. bodyConfig.type.push('box');
  60774. bodyConfig.size.push(sizeX);
  60775. bodyConfig.size.push(sizeY);
  60776. bodyConfig.size.push(sizeZ);
  60777. break;
  60778. }
  60779. //actually not needed, but hey...
  60780. i.object.rotationQuaternion = oldQuaternion;
  60781. });
  60782. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  60783. }
  60784. else {
  60785. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  60786. }
  60787. impostor.setDeltaPosition(this._tmpPositionVector);
  60788. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  60789. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  60790. };
  60791. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  60792. //impostor.physicsBody.dispose();
  60793. //Same as : (older oimo versions)
  60794. this.world.removeRigidBody(impostor.physicsBody);
  60795. };
  60796. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  60797. var mainBody = impostorJoint.mainImpostor.physicsBody;
  60798. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  60799. if (!mainBody || !connectedBody) {
  60800. return;
  60801. }
  60802. var jointData = impostorJoint.joint.jointData;
  60803. var options = jointData.nativeParams || {};
  60804. var type;
  60805. var nativeJointData = {
  60806. body1: mainBody,
  60807. body2: connectedBody,
  60808. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  60809. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  60810. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  60811. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  60812. min: options.min,
  60813. max: options.max,
  60814. collision: options.collision || jointData.collision,
  60815. spring: options.spring,
  60816. //supporting older version of Oimo
  60817. world: this.world
  60818. };
  60819. switch (impostorJoint.joint.type) {
  60820. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  60821. type = "jointBall";
  60822. break;
  60823. case BABYLON.PhysicsJoint.SpringJoint:
  60824. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  60825. var springData = jointData;
  60826. nativeJointData.min = springData.length || nativeJointData.min;
  60827. //Max should also be set, just make sure it is at least min
  60828. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  60829. case BABYLON.PhysicsJoint.DistanceJoint:
  60830. type = "jointDistance";
  60831. nativeJointData.max = jointData.maxDistance;
  60832. break;
  60833. case BABYLON.PhysicsJoint.PrismaticJoint:
  60834. type = "jointPrisme";
  60835. break;
  60836. case BABYLON.PhysicsJoint.SliderJoint:
  60837. type = "jointSlide";
  60838. break;
  60839. case BABYLON.PhysicsJoint.WheelJoint:
  60840. type = "jointWheel";
  60841. break;
  60842. case BABYLON.PhysicsJoint.HingeJoint:
  60843. default:
  60844. type = "jointHinge";
  60845. break;
  60846. }
  60847. nativeJointData.type = type;
  60848. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  60849. };
  60850. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  60851. //Bug in Oimo prevents us from disposing a joint in the playground
  60852. //joint.joint.physicsJoint.dispose();
  60853. //So we will bruteforce it!
  60854. try {
  60855. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  60856. }
  60857. catch (e) {
  60858. BABYLON.Tools.Warn(e);
  60859. }
  60860. };
  60861. OimoJSPlugin.prototype.isSupported = function () {
  60862. return OIMO !== undefined;
  60863. };
  60864. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  60865. if (!impostor.physicsBody.sleeping) {
  60866. //TODO check that
  60867. if (impostor.physicsBody.shapes.next) {
  60868. var parentShape = this._getLastShape(impostor.physicsBody);
  60869. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  60870. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  60871. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  60872. }
  60873. else {
  60874. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  60875. }
  60876. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  60877. impostor.object.rotationQuaternion.normalize();
  60878. }
  60879. };
  60880. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  60881. var body = impostor.physicsBody;
  60882. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  60883. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  60884. body.syncShapes();
  60885. body.awake();
  60886. };
  60887. OimoJSPlugin.prototype._getLastShape = function (body) {
  60888. var lastShape = body.shapes;
  60889. while (lastShape.next) {
  60890. lastShape = lastShape.next;
  60891. }
  60892. return lastShape;
  60893. };
  60894. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  60895. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  60896. };
  60897. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  60898. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  60899. };
  60900. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  60901. var v = impostor.physicsBody.linearVelocity;
  60902. if (!v)
  60903. return null;
  60904. return new BABYLON.Vector3(v.x, v.y, v.z);
  60905. };
  60906. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  60907. var v = impostor.physicsBody.angularVelocity;
  60908. if (!v)
  60909. return null;
  60910. return new BABYLON.Vector3(v.x, v.y, v.z);
  60911. };
  60912. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  60913. var staticBody = mass === 0;
  60914. //this will actually set the body's density and not its mass.
  60915. //But this is how oimo treats the mass variable.
  60916. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  60917. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  60918. };
  60919. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  60920. return impostor.physicsBody.shapes.density;
  60921. };
  60922. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  60923. return impostor.physicsBody.shapes.friction;
  60924. };
  60925. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  60926. impostor.physicsBody.shapes.friction = friction;
  60927. };
  60928. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  60929. return impostor.physicsBody.shapes.restitution;
  60930. };
  60931. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  60932. impostor.physicsBody.shapes.restitution = restitution;
  60933. };
  60934. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  60935. impostor.physicsBody.sleep();
  60936. };
  60937. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  60938. impostor.physicsBody.awake();
  60939. };
  60940. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  60941. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  60942. if (minDistance !== void 0) {
  60943. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  60944. }
  60945. };
  60946. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  60947. //TODO separate rotational and transational motors.
  60948. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  60949. if (motor) {
  60950. motor.setMotor(speed, maxForce);
  60951. }
  60952. };
  60953. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  60954. //TODO separate rotational and transational motors.
  60955. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  60956. if (motor) {
  60957. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  60958. }
  60959. };
  60960. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  60961. var body = impostor.physicsBody;
  60962. mesh.position.x = body.position.x;
  60963. mesh.position.y = body.position.y;
  60964. mesh.position.z = body.position.z;
  60965. mesh.rotationQuaternion.x = body.orientation.x;
  60966. mesh.rotationQuaternion.y = body.orientation.y;
  60967. mesh.rotationQuaternion.z = body.orientation.z;
  60968. mesh.rotationQuaternion.w = body.orientation.s;
  60969. };
  60970. OimoJSPlugin.prototype.getRadius = function (impostor) {
  60971. return impostor.physicsBody.shapes.radius;
  60972. };
  60973. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  60974. var shape = impostor.physicsBody.shapes;
  60975. result.x = shape.halfWidth * 2;
  60976. result.y = shape.halfHeight * 2;
  60977. result.z = shape.halfDepth * 2;
  60978. };
  60979. OimoJSPlugin.prototype.dispose = function () {
  60980. this.world.clear();
  60981. };
  60982. return OimoJSPlugin;
  60983. }());
  60984. BABYLON.OimoJSPlugin = OimoJSPlugin;
  60985. })(BABYLON || (BABYLON = {}));
  60986. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  60987. var BABYLON;
  60988. (function (BABYLON) {
  60989. var Internals;
  60990. (function (Internals) {
  60991. /*
  60992. * Based on jsTGALoader - Javascript loader for TGA file
  60993. * By Vincent Thibault
  60994. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  60995. */
  60996. var TGATools = (function () {
  60997. function TGATools() {
  60998. }
  60999. TGATools.GetTGAHeader = function (data) {
  61000. var offset = 0;
  61001. var header = {
  61002. id_length: data[offset++],
  61003. colormap_type: data[offset++],
  61004. image_type: data[offset++],
  61005. colormap_index: data[offset++] | data[offset++] << 8,
  61006. colormap_length: data[offset++] | data[offset++] << 8,
  61007. colormap_size: data[offset++],
  61008. origin: [
  61009. data[offset++] | data[offset++] << 8,
  61010. data[offset++] | data[offset++] << 8
  61011. ],
  61012. width: data[offset++] | data[offset++] << 8,
  61013. height: data[offset++] | data[offset++] << 8,
  61014. pixel_size: data[offset++],
  61015. flags: data[offset++]
  61016. };
  61017. return header;
  61018. };
  61019. TGATools.UploadContent = function (gl, data) {
  61020. // Not enough data to contain header ?
  61021. if (data.length < 19) {
  61022. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  61023. return;
  61024. }
  61025. // Read Header
  61026. var offset = 18;
  61027. var header = TGATools.GetTGAHeader(data);
  61028. // Assume it's a valid Targa file.
  61029. if (header.id_length + offset > data.length) {
  61030. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  61031. return;
  61032. }
  61033. // Skip not needed data
  61034. offset += header.id_length;
  61035. var use_rle = false;
  61036. var use_pal = false;
  61037. var use_rgb = false;
  61038. var use_grey = false;
  61039. // Get some informations.
  61040. switch (header.image_type) {
  61041. case TGATools._TYPE_RLE_INDEXED:
  61042. use_rle = true;
  61043. case TGATools._TYPE_INDEXED:
  61044. use_pal = true;
  61045. break;
  61046. case TGATools._TYPE_RLE_RGB:
  61047. use_rle = true;
  61048. case TGATools._TYPE_RGB:
  61049. use_rgb = true;
  61050. break;
  61051. case TGATools._TYPE_RLE_GREY:
  61052. use_rle = true;
  61053. case TGATools._TYPE_GREY:
  61054. use_grey = true;
  61055. break;
  61056. }
  61057. var pixel_data;
  61058. var numAlphaBits = header.flags & 0xf;
  61059. var pixel_size = header.pixel_size >> 3;
  61060. var pixel_total = header.width * header.height * pixel_size;
  61061. // Read palettes
  61062. var palettes;
  61063. if (use_pal) {
  61064. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  61065. }
  61066. // Read LRE
  61067. if (use_rle) {
  61068. pixel_data = new Uint8Array(pixel_total);
  61069. var c, count, i;
  61070. var localOffset = 0;
  61071. var pixels = new Uint8Array(pixel_size);
  61072. while (offset < pixel_total && localOffset < pixel_total) {
  61073. c = data[offset++];
  61074. count = (c & 0x7f) + 1;
  61075. // RLE pixels
  61076. if (c & 0x80) {
  61077. // Bind pixel tmp array
  61078. for (i = 0; i < pixel_size; ++i) {
  61079. pixels[i] = data[offset++];
  61080. }
  61081. // Copy pixel array
  61082. for (i = 0; i < count; ++i) {
  61083. pixel_data.set(pixels, localOffset + i * pixel_size);
  61084. }
  61085. localOffset += pixel_size * count;
  61086. }
  61087. else {
  61088. count *= pixel_size;
  61089. for (i = 0; i < count; ++i) {
  61090. pixel_data[localOffset + i] = data[offset++];
  61091. }
  61092. localOffset += count;
  61093. }
  61094. }
  61095. }
  61096. else {
  61097. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  61098. }
  61099. // Load to texture
  61100. var x_start, y_start, x_step, y_step, y_end, x_end;
  61101. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  61102. default:
  61103. case TGATools._ORIGIN_UL:
  61104. x_start = 0;
  61105. x_step = 1;
  61106. x_end = header.width;
  61107. y_start = 0;
  61108. y_step = 1;
  61109. y_end = header.height;
  61110. break;
  61111. case TGATools._ORIGIN_BL:
  61112. x_start = 0;
  61113. x_step = 1;
  61114. x_end = header.width;
  61115. y_start = header.height - 1;
  61116. y_step = -1;
  61117. y_end = -1;
  61118. break;
  61119. case TGATools._ORIGIN_UR:
  61120. x_start = header.width - 1;
  61121. x_step = -1;
  61122. x_end = -1;
  61123. y_start = 0;
  61124. y_step = 1;
  61125. y_end = header.height;
  61126. break;
  61127. case TGATools._ORIGIN_BR:
  61128. x_start = header.width - 1;
  61129. x_step = -1;
  61130. x_end = -1;
  61131. y_start = header.height - 1;
  61132. y_step = -1;
  61133. y_end = -1;
  61134. break;
  61135. }
  61136. // Load the specify method
  61137. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  61138. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  61139. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  61140. };
  61141. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61142. var image = pixel_data, colormap = palettes;
  61143. var width = header.width, height = header.height;
  61144. var color, i = 0, x, y;
  61145. var imageData = new Uint8Array(width * height * 4);
  61146. for (y = y_start; y !== y_end; y += y_step) {
  61147. for (x = x_start; x !== x_end; x += x_step, i++) {
  61148. color = image[i];
  61149. imageData[(x + width * y) * 4 + 3] = 255;
  61150. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  61151. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  61152. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  61153. }
  61154. }
  61155. return imageData;
  61156. };
  61157. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61158. var image = pixel_data;
  61159. var width = header.width, height = header.height;
  61160. var color, i = 0, x, y;
  61161. var imageData = new Uint8Array(width * height * 4);
  61162. for (y = y_start; y !== y_end; y += y_step) {
  61163. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  61164. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  61165. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  61166. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  61167. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  61168. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  61169. }
  61170. }
  61171. return imageData;
  61172. };
  61173. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61174. var image = pixel_data;
  61175. var width = header.width, height = header.height;
  61176. var i = 0, x, y;
  61177. var imageData = new Uint8Array(width * height * 4);
  61178. for (y = y_start; y !== y_end; y += y_step) {
  61179. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  61180. imageData[(x + width * y) * 4 + 3] = 255;
  61181. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61182. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  61183. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  61184. }
  61185. }
  61186. return imageData;
  61187. };
  61188. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61189. var image = pixel_data;
  61190. var width = header.width, height = header.height;
  61191. var i = 0, x, y;
  61192. var imageData = new Uint8Array(width * height * 4);
  61193. for (y = y_start; y !== y_end; y += y_step) {
  61194. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  61195. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61196. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  61197. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  61198. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  61199. }
  61200. }
  61201. return imageData;
  61202. };
  61203. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61204. var image = pixel_data;
  61205. var width = header.width, height = header.height;
  61206. var color, i = 0, x, y;
  61207. var imageData = new Uint8Array(width * height * 4);
  61208. for (y = y_start; y !== y_end; y += y_step) {
  61209. for (x = x_start; x !== x_end; x += x_step, i++) {
  61210. color = image[i];
  61211. imageData[(x + width * y) * 4 + 0] = color;
  61212. imageData[(x + width * y) * 4 + 1] = color;
  61213. imageData[(x + width * y) * 4 + 2] = color;
  61214. imageData[(x + width * y) * 4 + 3] = 255;
  61215. }
  61216. }
  61217. return imageData;
  61218. };
  61219. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61220. var image = pixel_data;
  61221. var width = header.width, height = header.height;
  61222. var i = 0, x, y;
  61223. var imageData = new Uint8Array(width * height * 4);
  61224. for (y = y_start; y !== y_end; y += y_step) {
  61225. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  61226. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  61227. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  61228. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61229. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  61230. }
  61231. }
  61232. return imageData;
  61233. };
  61234. TGATools._TYPE_NO_DATA = 0;
  61235. TGATools._TYPE_INDEXED = 1;
  61236. TGATools._TYPE_RGB = 2;
  61237. TGATools._TYPE_GREY = 3;
  61238. TGATools._TYPE_RLE_INDEXED = 9;
  61239. TGATools._TYPE_RLE_RGB = 10;
  61240. TGATools._TYPE_RLE_GREY = 11;
  61241. TGATools._ORIGIN_MASK = 0x30;
  61242. TGATools._ORIGIN_SHIFT = 0x04;
  61243. TGATools._ORIGIN_BL = 0x00;
  61244. TGATools._ORIGIN_BR = 0x01;
  61245. TGATools._ORIGIN_UL = 0x02;
  61246. TGATools._ORIGIN_UR = 0x03;
  61247. return TGATools;
  61248. }());
  61249. Internals.TGATools = TGATools;
  61250. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61251. })(BABYLON || (BABYLON = {}));
  61252. //# sourceMappingURL=babylon.tga.js.map
  61253. var BABYLON;
  61254. (function (BABYLON) {
  61255. var Internals;
  61256. (function (Internals) {
  61257. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  61258. // All values and structures referenced from:
  61259. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  61260. var DDS_MAGIC = 0x20534444;
  61261. 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;
  61262. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  61263. 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;
  61264. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  61265. function FourCCToInt32(value) {
  61266. return value.charCodeAt(0) +
  61267. (value.charCodeAt(1) << 8) +
  61268. (value.charCodeAt(2) << 16) +
  61269. (value.charCodeAt(3) << 24);
  61270. }
  61271. function Int32ToFourCC(value) {
  61272. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  61273. }
  61274. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  61275. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  61276. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  61277. var FOURCC_DX10 = FourCCToInt32("DX10");
  61278. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  61279. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  61280. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  61281. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  61282. var headerLengthInt = 31; // The header length in 32 bit ints
  61283. // Offsets into the header array
  61284. var off_magic = 0;
  61285. var off_size = 1;
  61286. var off_flags = 2;
  61287. var off_height = 3;
  61288. var off_width = 4;
  61289. var off_mipmapCount = 7;
  61290. var off_pfFlags = 20;
  61291. var off_pfFourCC = 21;
  61292. var off_RGBbpp = 22;
  61293. var off_RMask = 23;
  61294. var off_GMask = 24;
  61295. var off_BMask = 25;
  61296. var off_AMask = 26;
  61297. var off_caps1 = 27;
  61298. var off_caps2 = 28;
  61299. var off_caps3 = 29;
  61300. var off_caps4 = 30;
  61301. var off_dxgiFormat = 32;
  61302. ;
  61303. var DDSTools = (function () {
  61304. function DDSTools() {
  61305. }
  61306. DDSTools.GetDDSInfo = function (arrayBuffer) {
  61307. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  61308. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  61309. var mipmapCount = 1;
  61310. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  61311. mipmapCount = Math.max(1, header[off_mipmapCount]);
  61312. }
  61313. var fourCC = header[off_pfFourCC];
  61314. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  61315. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61316. switch (fourCC) {
  61317. case FOURCC_D3DFMT_R16G16B16A16F:
  61318. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61319. break;
  61320. case FOURCC_D3DFMT_R32G32B32A32F:
  61321. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61322. break;
  61323. case FOURCC_DX10:
  61324. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  61325. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61326. break;
  61327. }
  61328. }
  61329. return {
  61330. width: header[off_width],
  61331. height: header[off_height],
  61332. mipmapCount: mipmapCount,
  61333. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  61334. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  61335. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  61336. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  61337. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  61338. dxgiFormat: dxgiFormat,
  61339. textureType: textureType
  61340. };
  61341. };
  61342. DDSTools._ToHalfFloat = function (value) {
  61343. if (!DDSTools._FloatView) {
  61344. DDSTools._FloatView = new Float32Array(1);
  61345. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  61346. }
  61347. DDSTools._FloatView[0] = value;
  61348. var x = DDSTools._Int32View[0];
  61349. var bits = (x >> 16) & 0x8000; /* Get the sign */
  61350. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  61351. var e = (x >> 23) & 0xff; /* Using int is faster here */
  61352. /* If zero, or denormal, or exponent underflows too much for a denormal
  61353. * half, return signed zero. */
  61354. if (e < 103) {
  61355. return bits;
  61356. }
  61357. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  61358. if (e > 142) {
  61359. bits |= 0x7c00;
  61360. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  61361. * not Inf, so make sure we set one mantissa bit too. */
  61362. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  61363. return bits;
  61364. }
  61365. /* If exponent underflows but not too much, return a denormal */
  61366. if (e < 113) {
  61367. m |= 0x0800;
  61368. /* Extra rounding may overflow and set mantissa to 0 and exponent
  61369. * to 1, which is OK. */
  61370. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  61371. return bits;
  61372. }
  61373. bits |= ((e - 112) << 10) | (m >> 1);
  61374. bits += m & 1;
  61375. return bits;
  61376. };
  61377. DDSTools._FromHalfFloat = function (value) {
  61378. var s = (value & 0x8000) >> 15;
  61379. var e = (value & 0x7C00) >> 10;
  61380. var f = value & 0x03FF;
  61381. if (e === 0) {
  61382. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  61383. }
  61384. else if (e == 0x1F) {
  61385. return f ? NaN : ((s ? -1 : 1) * Infinity);
  61386. }
  61387. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  61388. };
  61389. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61390. var destArray = new Float32Array(dataLength);
  61391. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61392. var index = 0;
  61393. for (var y = 0; y < height; y++) {
  61394. for (var x = 0; x < width; x++) {
  61395. var srcPos = (x + y * width) * 4;
  61396. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  61397. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  61398. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  61399. if (DDSTools.StoreLODInAlphaChannel) {
  61400. destArray[index + 3] = lod;
  61401. }
  61402. else {
  61403. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  61404. }
  61405. index += 4;
  61406. }
  61407. }
  61408. return destArray;
  61409. };
  61410. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61411. if (DDSTools.StoreLODInAlphaChannel) {
  61412. var destArray = new Uint16Array(dataLength);
  61413. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61414. var index = 0;
  61415. for (var y = 0; y < height; y++) {
  61416. for (var x = 0; x < width; x++) {
  61417. var srcPos = (x + y * width) * 4;
  61418. destArray[index] = srcData[srcPos];
  61419. destArray[index + 1] = srcData[srcPos + 1];
  61420. destArray[index + 2] = srcData[srcPos + 2];
  61421. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  61422. index += 4;
  61423. }
  61424. }
  61425. return destArray;
  61426. }
  61427. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  61428. };
  61429. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61430. if (DDSTools.StoreLODInAlphaChannel) {
  61431. var destArray = new Float32Array(dataLength);
  61432. var srcData = new Float32Array(arrayBuffer, dataOffset);
  61433. var index = 0;
  61434. for (var y = 0; y < height; y++) {
  61435. for (var x = 0; x < width; x++) {
  61436. var srcPos = (x + y * width) * 4;
  61437. destArray[index] = srcData[srcPos];
  61438. destArray[index + 1] = srcData[srcPos + 1];
  61439. destArray[index + 2] = srcData[srcPos + 2];
  61440. destArray[index + 3] = lod;
  61441. index += 4;
  61442. }
  61443. }
  61444. return destArray;
  61445. }
  61446. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  61447. };
  61448. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61449. var destArray = new Uint8Array(dataLength);
  61450. var srcData = new Float32Array(arrayBuffer, dataOffset);
  61451. var index = 0;
  61452. for (var y = 0; y < height; y++) {
  61453. for (var x = 0; x < width; x++) {
  61454. var srcPos = (x + y * width) * 4;
  61455. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  61456. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  61457. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  61458. if (DDSTools.StoreLODInAlphaChannel) {
  61459. destArray[index + 3] = lod;
  61460. }
  61461. else {
  61462. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  61463. }
  61464. index += 4;
  61465. }
  61466. }
  61467. return destArray;
  61468. };
  61469. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61470. var destArray = new Uint8Array(dataLength);
  61471. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61472. var index = 0;
  61473. for (var y = 0; y < height; y++) {
  61474. for (var x = 0; x < width; x++) {
  61475. var srcPos = (x + y * width) * 4;
  61476. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  61477. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  61478. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  61479. if (DDSTools.StoreLODInAlphaChannel) {
  61480. destArray[index + 3] = lod;
  61481. }
  61482. else {
  61483. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  61484. }
  61485. index += 4;
  61486. }
  61487. }
  61488. return destArray;
  61489. };
  61490. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61491. var byteArray = new Uint8Array(dataLength);
  61492. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61493. var index = 0;
  61494. for (var y = 0; y < height; y++) {
  61495. for (var x = 0; x < width; x++) {
  61496. var srcPos = (x + y * width) * 4;
  61497. byteArray[index] = srcData[srcPos + 2];
  61498. byteArray[index + 1] = srcData[srcPos + 1];
  61499. byteArray[index + 2] = srcData[srcPos];
  61500. byteArray[index + 3] = srcData[srcPos + 3];
  61501. index += 4;
  61502. }
  61503. }
  61504. return byteArray;
  61505. };
  61506. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61507. var byteArray = new Uint8Array(dataLength);
  61508. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61509. var index = 0;
  61510. for (var y = 0; y < height; y++) {
  61511. for (var x = 0; x < width; x++) {
  61512. var srcPos = (x + y * width) * 3;
  61513. byteArray[index] = srcData[srcPos + 2];
  61514. byteArray[index + 1] = srcData[srcPos + 1];
  61515. byteArray[index + 2] = srcData[srcPos];
  61516. index += 3;
  61517. }
  61518. }
  61519. return byteArray;
  61520. };
  61521. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61522. var byteArray = new Uint8Array(dataLength);
  61523. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61524. var index = 0;
  61525. for (var y = 0; y < height; y++) {
  61526. for (var x = 0; x < width; x++) {
  61527. var srcPos = (x + y * width);
  61528. byteArray[index] = srcData[srcPos];
  61529. index++;
  61530. }
  61531. }
  61532. return byteArray;
  61533. };
  61534. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  61535. if (lodIndex === void 0) { lodIndex = -1; }
  61536. var gl = engine._gl;
  61537. var ext = engine.getCaps().s3tc;
  61538. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  61539. if (header[off_magic] != DDS_MAGIC) {
  61540. BABYLON.Tools.Error("Invalid magic number in DDS header");
  61541. return;
  61542. }
  61543. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  61544. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  61545. return;
  61546. }
  61547. if (info.isCompressed && !ext) {
  61548. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  61549. return;
  61550. }
  61551. var bpp = header[off_RGBbpp];
  61552. dataOffset = header[off_size] + 4;
  61553. var computeFormats = false;
  61554. if (info.isFourCC) {
  61555. fourCC = header[off_pfFourCC];
  61556. switch (fourCC) {
  61557. case FOURCC_DXT1:
  61558. blockBytes = 8;
  61559. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  61560. break;
  61561. case FOURCC_DXT3:
  61562. blockBytes = 16;
  61563. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  61564. break;
  61565. case FOURCC_DXT5:
  61566. blockBytes = 16;
  61567. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  61568. break;
  61569. case FOURCC_D3DFMT_R16G16B16A16F:
  61570. computeFormats = true;
  61571. break;
  61572. case FOURCC_D3DFMT_R32G32B32A32F:
  61573. computeFormats = true;
  61574. break;
  61575. case FOURCC_DX10:
  61576. // There is an additionnal header so dataOffset need to be changed
  61577. dataOffset += 5 * 4; // 5 uints
  61578. var supported = false;
  61579. switch (info.dxgiFormat) {
  61580. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  61581. computeFormats = true;
  61582. supported = true;
  61583. break;
  61584. case DXGI_FORMAT_B8G8R8X8_UNORM:
  61585. info.isRGB = true;
  61586. info.isFourCC = false;
  61587. bpp = 32;
  61588. supported = true;
  61589. break;
  61590. }
  61591. if (supported) {
  61592. break;
  61593. }
  61594. default:
  61595. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  61596. return;
  61597. }
  61598. }
  61599. if (computeFormats) {
  61600. format = engine._getWebGLTextureType(info.textureType);
  61601. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61602. }
  61603. mipmapCount = 1;
  61604. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  61605. mipmapCount = Math.max(1, header[off_mipmapCount]);
  61606. }
  61607. for (var face = 0; face < faces; face++) {
  61608. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  61609. width = header[off_width];
  61610. height = header[off_height];
  61611. for (mip = 0; mip < mipmapCount; ++mip) {
  61612. if (lodIndex === -1 || lodIndex === mip) {
  61613. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  61614. var i = (lodIndex === -1) ? mip : 0;
  61615. if (!info.isCompressed && info.isFourCC) {
  61616. dataLength = width * height * 4;
  61617. var floatArray;
  61618. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  61619. if (bpp === 128) {
  61620. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61621. }
  61622. else if (bpp === 64) {
  61623. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61624. }
  61625. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61626. format = engine._getWebGLTextureType(info.textureType);
  61627. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61628. }
  61629. else {
  61630. if (bpp === 128) {
  61631. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61632. }
  61633. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  61634. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61635. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61636. format = engine._getWebGLTextureType(info.textureType);
  61637. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  61638. }
  61639. else {
  61640. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  61641. }
  61642. }
  61643. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  61644. }
  61645. else if (info.isRGB) {
  61646. if (bpp === 24) {
  61647. dataLength = width * height * 3;
  61648. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61649. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  61650. }
  61651. else {
  61652. dataLength = width * height * 4;
  61653. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61654. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  61655. }
  61656. }
  61657. else if (info.isLuminance) {
  61658. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  61659. var unpaddedRowSize = width;
  61660. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  61661. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  61662. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  61663. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  61664. }
  61665. else {
  61666. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  61667. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  61668. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  61669. }
  61670. }
  61671. dataOffset += width * height * (bpp / 8);
  61672. width *= 0.5;
  61673. height *= 0.5;
  61674. width = Math.max(1.0, width);
  61675. height = Math.max(1.0, height);
  61676. }
  61677. }
  61678. };
  61679. DDSTools.StoreLODInAlphaChannel = false;
  61680. return DDSTools;
  61681. }());
  61682. Internals.DDSTools = DDSTools;
  61683. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61684. })(BABYLON || (BABYLON = {}));
  61685. //# sourceMappingURL=babylon.dds.js.map
  61686. var BABYLON;
  61687. (function (BABYLON) {
  61688. var Internals;
  61689. (function (Internals) {
  61690. /**
  61691. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  61692. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  61693. */
  61694. var KhronosTextureContainer = (function () {
  61695. /**
  61696. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  61697. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  61698. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  61699. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  61700. */
  61701. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  61702. this.arrayBuffer = arrayBuffer;
  61703. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  61704. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  61705. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  61706. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  61707. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  61708. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  61709. BABYLON.Tools.Error("texture missing KTX identifier");
  61710. return;
  61711. }
  61712. // load the reset of the header in native 32 bit int
  61713. var header = new Int32Array(this.arrayBuffer, 12, 13);
  61714. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  61715. var oppositeEndianess = header[0] === 0x01020304;
  61716. // read all the header elements in order they exist in the file, without modification (sans endainness)
  61717. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  61718. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  61719. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  61720. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  61721. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  61722. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  61723. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  61724. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  61725. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  61726. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  61727. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  61728. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  61729. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  61730. if (this.glType !== 0) {
  61731. BABYLON.Tools.Error("only compressed formats currently supported");
  61732. return;
  61733. }
  61734. else {
  61735. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  61736. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  61737. }
  61738. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  61739. BABYLON.Tools.Error("only 2D textures currently supported");
  61740. return;
  61741. }
  61742. if (this.numberOfArrayElements !== 0) {
  61743. BABYLON.Tools.Error("texture arrays not currently supported");
  61744. return;
  61745. }
  61746. if (this.numberOfFaces !== facesExpected) {
  61747. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  61748. return;
  61749. }
  61750. // we now have a completely validated file, so could use existence of loadType as success
  61751. // would need to make this more elaborate & adjust checks above to support more than one load type
  61752. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  61753. }
  61754. // not as fast hardware based, but will probably never need to use
  61755. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  61756. return ((val & 0xFF) << 24)
  61757. | ((val & 0xFF00) << 8)
  61758. | ((val >> 8) & 0xFF00)
  61759. | ((val >> 24) & 0xFF);
  61760. };
  61761. /**
  61762. * It is assumed that the texture has already been created & is currently bound
  61763. */
  61764. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  61765. switch (this.loadType) {
  61766. case KhronosTextureContainer.COMPRESSED_2D:
  61767. this._upload2DCompressedLevels(gl, loadMipmaps);
  61768. break;
  61769. case KhronosTextureContainer.TEX_2D:
  61770. case KhronosTextureContainer.COMPRESSED_3D:
  61771. case KhronosTextureContainer.TEX_3D:
  61772. }
  61773. };
  61774. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  61775. // initialize width & height for level 1
  61776. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  61777. var width = this.pixelWidth;
  61778. var height = this.pixelHeight;
  61779. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  61780. for (var level = 0; level < mipmapCount; level++) {
  61781. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  61782. for (var face = 0; face < this.numberOfFaces; face++) {
  61783. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  61784. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  61785. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  61786. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  61787. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  61788. }
  61789. width = Math.max(1.0, width * 0.5);
  61790. height = Math.max(1.0, height * 0.5);
  61791. }
  61792. };
  61793. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  61794. // load types
  61795. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  61796. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  61797. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  61798. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  61799. return KhronosTextureContainer;
  61800. }());
  61801. Internals.KhronosTextureContainer = KhronosTextureContainer;
  61802. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61803. })(BABYLON || (BABYLON = {}));
  61804. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  61805. var BABYLON;
  61806. (function (BABYLON) {
  61807. var DynamicFloatArrayElementInfo = (function () {
  61808. function DynamicFloatArrayElementInfo() {
  61809. }
  61810. return DynamicFloatArrayElementInfo;
  61811. }());
  61812. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  61813. /**
  61814. * 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.
  61815. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  61816. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  61817. * 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.
  61818. * 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.
  61819. * 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".
  61820. */
  61821. var DynamicFloatArray = (function () {
  61822. /**
  61823. * Construct an instance of the dynamic float array
  61824. * @param stride size of one element in float (i.e. not bytes!)
  61825. * @param initialElementCount the number of available entries at construction
  61826. */
  61827. function DynamicFloatArray(stride, initialElementCount) {
  61828. this.compareValueOffset = null;
  61829. this.sortingAscending = true;
  61830. this._stride = stride;
  61831. this.buffer = new Float32Array(stride * initialElementCount);
  61832. this._lastUsed = 0;
  61833. this._firstFree = 0;
  61834. this._allEntries = new Array(initialElementCount);
  61835. this._freeEntries = new Array(initialElementCount);
  61836. for (var i = 0; i < initialElementCount; i++) {
  61837. var element = new DynamicFloatArrayElementInfo();
  61838. element.offset = i * stride;
  61839. this._allEntries[i] = element;
  61840. this._freeEntries[initialElementCount - i - 1] = element;
  61841. }
  61842. }
  61843. /**
  61844. * Allocate an element in the array.
  61845. * @return the element info instance that contains the offset into the main buffer of the element's location.
  61846. * Beware, this offset may change when you call pack()
  61847. */
  61848. DynamicFloatArray.prototype.allocElement = function () {
  61849. if (this._freeEntries.length === 0) {
  61850. this._growBuffer();
  61851. }
  61852. var el = this._freeEntries.pop();
  61853. this._lastUsed = Math.max(el.offset, this._lastUsed);
  61854. if (el.offset === this._firstFree) {
  61855. if (this._freeEntries.length > 0) {
  61856. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  61857. }
  61858. else {
  61859. this._firstFree += this._stride;
  61860. }
  61861. }
  61862. return el;
  61863. };
  61864. /**
  61865. * Free the element corresponding to the given element info
  61866. * @param elInfo the element that describe the allocated element
  61867. */
  61868. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  61869. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  61870. this._freeEntries.push(elInfo);
  61871. };
  61872. /**
  61873. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  61874. * 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().
  61875. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  61876. */
  61877. DynamicFloatArray.prototype.pack = function () {
  61878. // no free slot? no need to pack
  61879. if (this._freeEntries.length === 0) {
  61880. return this.buffer;
  61881. }
  61882. // If the buffer is already packed the last used will always be lower than the first free
  61883. // 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.
  61884. if (this._lastUsed < this._firstFree) {
  61885. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  61886. return elementsBuffer_1;
  61887. }
  61888. var s = this._stride;
  61889. // 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
  61890. var lastFree = new DynamicFloatArrayElementInfo();
  61891. lastFree.offset = this.totalElementCount * s;
  61892. this._freeEntries.push(lastFree);
  61893. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  61894. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61895. var firstFreeSlotOffset = sortedFree[0].offset;
  61896. var freeZoneSize = 1;
  61897. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  61898. var prevOffset = sortedFree[0].offset;
  61899. for (var i = 1; i < sortedFree.length; i++) {
  61900. // 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
  61901. if (firstFreeSlotOffset >= occupiedZoneSize) {
  61902. break;
  61903. }
  61904. var curFree = sortedFree[i];
  61905. var curOffset = curFree.offset;
  61906. // Compute the distance between this offset and the previous
  61907. var distance = curOffset - prevOffset;
  61908. // If the distance is the stride size, they are adjacent, it good, move to the next
  61909. if (distance === s) {
  61910. // Free zone is one element bigger
  61911. ++freeZoneSize;
  61912. // as we're about to iterate to the next, the cur becomes the previous...
  61913. prevOffset = curOffset;
  61914. continue;
  61915. }
  61916. // Distance is bigger, which means there's x element between the previous free and this one
  61917. var usedRange = (distance / s) - 1;
  61918. // Two cases the free zone is smaller than the data to move or bigger
  61919. // Copy what can fit in the free zone
  61920. var curMoveOffset = curOffset - s;
  61921. var copyCount = Math.min(freeZoneSize, usedRange);
  61922. for (var j = 0; j < copyCount; j++) {
  61923. var freeI = firstFreeSlotOffset / s;
  61924. var curI = curMoveOffset / s;
  61925. var moveEl = sortedAll[curI];
  61926. this._moveElement(moveEl, firstFreeSlotOffset);
  61927. var replacedEl = sortedAll[freeI];
  61928. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  61929. replacedEl.offset = curMoveOffset;
  61930. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  61931. sortedAll[freeI] = moveEl;
  61932. sortedAll[curI] = replacedEl;
  61933. curMoveOffset -= s;
  61934. firstFreeSlotOffset += s;
  61935. }
  61936. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  61937. if (freeZoneSize <= usedRange) {
  61938. firstFreeSlotOffset = curMoveOffset + s;
  61939. freeZoneSize = 1 + copyCount;
  61940. }
  61941. else {
  61942. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  61943. }
  61944. // as we're about to iterate to the next, the cur becomes the previous...
  61945. prevOffset = curOffset;
  61946. }
  61947. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  61948. this._lastUsed = firstFreeSlotOffset - s;
  61949. this._firstFree = firstFreeSlotOffset;
  61950. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  61951. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  61952. this._allEntries = sortedAll;
  61953. return elementsBuffer;
  61954. };
  61955. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  61956. for (var i = 0; i < this._stride; i++) {
  61957. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  61958. }
  61959. element.offset = destOffset;
  61960. };
  61961. DynamicFloatArray.prototype._growBuffer = function () {
  61962. // Allocate the new buffer with 50% more entries, copy the content of the current one
  61963. var newElCount = Math.floor(this.totalElementCount * 1.5);
  61964. var newBuffer = new Float32Array(newElCount * this._stride);
  61965. newBuffer.set(this.buffer);
  61966. var curCount = this.totalElementCount;
  61967. var addedCount = newElCount - this.totalElementCount;
  61968. for (var i = 0; i < addedCount; i++) {
  61969. var element = new DynamicFloatArrayElementInfo();
  61970. element.offset = (curCount + i) * this.stride;
  61971. this._allEntries.push(element);
  61972. this._freeEntries[addedCount - i - 1] = element;
  61973. }
  61974. this._firstFree = curCount * this.stride;
  61975. this.buffer = newBuffer;
  61976. };
  61977. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  61978. /**
  61979. * Get the total count of entries that can fit in the current buffer
  61980. * @returns the elements count
  61981. */
  61982. get: function () {
  61983. return this._allEntries.length;
  61984. },
  61985. enumerable: true,
  61986. configurable: true
  61987. });
  61988. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  61989. /**
  61990. * Get the count of free entries that can still be allocated without resizing the buffer
  61991. * @returns the free elements count
  61992. */
  61993. get: function () {
  61994. return this._freeEntries.length;
  61995. },
  61996. enumerable: true,
  61997. configurable: true
  61998. });
  61999. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  62000. /**
  62001. * Get the count of allocated elements
  62002. * @returns the allocated elements count
  62003. */
  62004. get: function () {
  62005. return this._allEntries.length - this._freeEntries.length;
  62006. },
  62007. enumerable: true,
  62008. configurable: true
  62009. });
  62010. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  62011. /**
  62012. * Return the size of one element in float
  62013. * @returns the size in float
  62014. */
  62015. get: function () {
  62016. return this._stride;
  62017. },
  62018. enumerable: true,
  62019. configurable: true
  62020. });
  62021. DynamicFloatArray.prototype.sort = function () {
  62022. var _this = this;
  62023. if (!this.compareValueOffset) {
  62024. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  62025. }
  62026. var count = this.usedElementCount;
  62027. // Do we have to (re)create the sort table?
  62028. if (!this._sortTable || this._sortTable.length < count) {
  62029. // 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...
  62030. var newCount = Math.min(this.totalElementCount, count * 2);
  62031. this._sortTable = new Array(newCount);
  62032. }
  62033. if (!this._sortedTable || this._sortedTable.length !== count) {
  62034. this._sortedTable = new Array(count);
  62035. }
  62036. // Because, you know...
  62037. this.pack();
  62038. //let stride = this.stride;
  62039. //for (let i = 0; i < count; i++) {
  62040. // let si = this._sortTable[i];
  62041. // if (!si) {
  62042. // si = new SortInfo();
  62043. // this._sortTable[i] = si;
  62044. // }
  62045. // si.entry = this._allEntries[i];
  62046. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  62047. // si.swapedOffset = null;
  62048. // this._sortedTable[i] = si;
  62049. //}
  62050. var curOffset = 0;
  62051. var stride = this.stride;
  62052. for (var i = 0; i < count; i++, curOffset += stride) {
  62053. var si = this._sortTable[i];
  62054. if (!si) {
  62055. si = new SortInfo();
  62056. this._sortTable[i] = si;
  62057. }
  62058. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  62059. si.offset = curOffset;
  62060. si.swapedOffset = null;
  62061. this._sortedTable[i] = si;
  62062. }
  62063. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  62064. if (this.sortingAscending) {
  62065. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  62066. }
  62067. else {
  62068. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  62069. }
  62070. var swapElements = function (src, dst) {
  62071. for (var i = 0; i < stride; i++) {
  62072. var tps = _this.buffer[dst + i];
  62073. _this.buffer[dst + i] = _this.buffer[src + i];
  62074. _this.buffer[src + i] = tps;
  62075. }
  62076. };
  62077. // 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:
  62078. // 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),
  62079. // and I still want something with a good algorithm complexity.
  62080. // 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,
  62081. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  62082. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  62083. // 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
  62084. // until we find a SortInfo object without a swapedOffset which means we got the right location
  62085. // 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
  62086. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  62087. for (var i = 0; i < count; i++) {
  62088. // Get the element to move
  62089. var sourceSI = this._sortedTable[i];
  62090. var destSI = this._sortTable[i];
  62091. var sourceOff = sourceSI.offset;
  62092. // If the source changed location, find the new one
  62093. if (sourceSI.swapedOffset) {
  62094. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  62095. var curSI = sourceSI;
  62096. while (curSI.swapedOffset) {
  62097. curSI = this._sortTable[curSI.swapedOffset / stride];
  62098. }
  62099. // Finally get the right location
  62100. sourceOff = curSI.offset;
  62101. }
  62102. // Tag the element being replaced with its new location
  62103. destSI.swapedOffset = sourceOff;
  62104. // Swap elements (only if needed)
  62105. if (sourceOff !== destSI.offset) {
  62106. swapElements(sourceOff, destSI.offset);
  62107. }
  62108. // Update the offset in the corresponding DFAE
  62109. //sourceSI.entry.offset = destSI.entry.offset;
  62110. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  62111. }
  62112. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62113. return true;
  62114. };
  62115. return DynamicFloatArray;
  62116. }());
  62117. BABYLON.DynamicFloatArray = DynamicFloatArray;
  62118. var SortInfo = (function () {
  62119. function SortInfo() {
  62120. this.compareData = this.offset = this.swapedOffset = null;
  62121. }
  62122. return SortInfo;
  62123. }());
  62124. })(BABYLON || (BABYLON = {}));
  62125. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  62126. var BABYLON;
  62127. (function (BABYLON) {
  62128. var Debug;
  62129. (function (Debug) {
  62130. /**
  62131. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  62132. */
  62133. var SkeletonViewer = (function () {
  62134. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  62135. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62136. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62137. this.skeleton = skeleton;
  62138. this.mesh = mesh;
  62139. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62140. this.renderingGroupId = renderingGroupId;
  62141. this.color = BABYLON.Color3.White();
  62142. this._debugLines = [];
  62143. this._isEnabled = false;
  62144. this._scene = scene;
  62145. this.update();
  62146. this._renderFunction = this.update.bind(this);
  62147. }
  62148. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62149. get: function () {
  62150. return this._isEnabled;
  62151. },
  62152. set: function (value) {
  62153. if (this._isEnabled === value) {
  62154. return;
  62155. }
  62156. this._isEnabled = value;
  62157. if (value) {
  62158. this._scene.registerBeforeRender(this._renderFunction);
  62159. }
  62160. else {
  62161. this._scene.unregisterBeforeRender(this._renderFunction);
  62162. }
  62163. },
  62164. enumerable: true,
  62165. configurable: true
  62166. });
  62167. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62168. if (x === void 0) { x = 0; }
  62169. if (y === void 0) { y = 0; }
  62170. if (z === void 0) { z = 0; }
  62171. var tmat = BABYLON.Tmp.Matrix[0];
  62172. var parentBone = bone.getParent();
  62173. tmat.copyFrom(bone.getLocalMatrix());
  62174. if (x !== 0 || y !== 0 || z !== 0) {
  62175. var tmat2 = BABYLON.Tmp.Matrix[1];
  62176. BABYLON.Matrix.IdentityToRef(tmat2);
  62177. tmat2.m[12] = x;
  62178. tmat2.m[13] = y;
  62179. tmat2.m[14] = z;
  62180. tmat2.multiplyToRef(tmat, tmat);
  62181. }
  62182. if (parentBone) {
  62183. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62184. }
  62185. tmat.multiplyToRef(meshMat, tmat);
  62186. position.x = tmat.m[12];
  62187. position.y = tmat.m[13];
  62188. position.z = tmat.m[14];
  62189. };
  62190. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62191. var len = bones.length;
  62192. var meshPos = this.mesh.position;
  62193. for (var i = 0; i < len; i++) {
  62194. var bone = bones[i];
  62195. var points = this._debugLines[i];
  62196. if (!points) {
  62197. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62198. this._debugLines[i] = points;
  62199. }
  62200. this._getBonePosition(points[0], bone, meshMat);
  62201. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62202. points[0].subtractInPlace(meshPos);
  62203. points[1].subtractInPlace(meshPos);
  62204. }
  62205. };
  62206. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62207. var len = bones.length;
  62208. var boneNum = 0;
  62209. var meshPos = this.mesh.position;
  62210. for (var i = len - 1; i >= 0; i--) {
  62211. var childBone = bones[i];
  62212. var parentBone = childBone.getParent();
  62213. if (!parentBone) {
  62214. continue;
  62215. }
  62216. var points = this._debugLines[boneNum];
  62217. if (!points) {
  62218. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62219. this._debugLines[boneNum] = points;
  62220. }
  62221. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62222. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62223. points[0].subtractInPlace(meshPos);
  62224. points[1].subtractInPlace(meshPos);
  62225. boneNum++;
  62226. }
  62227. };
  62228. SkeletonViewer.prototype.update = function () {
  62229. if (this.autoUpdateBonesMatrices) {
  62230. this.skeleton.computeAbsoluteTransforms();
  62231. }
  62232. if (this.skeleton.bones[0].length === undefined) {
  62233. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62234. }
  62235. else {
  62236. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62237. }
  62238. if (!this._debugMesh) {
  62239. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  62240. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62241. }
  62242. else {
  62243. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62244. }
  62245. this._debugMesh.position.copyFrom(this.mesh.position);
  62246. this._debugMesh.color = this.color;
  62247. };
  62248. SkeletonViewer.prototype.dispose = function () {
  62249. if (this._debugMesh) {
  62250. this.isEnabled = false;
  62251. this._debugMesh.dispose();
  62252. this._debugMesh = null;
  62253. }
  62254. };
  62255. return SkeletonViewer;
  62256. }());
  62257. Debug.SkeletonViewer = SkeletonViewer;
  62258. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62259. })(BABYLON || (BABYLON = {}));
  62260. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62261. var BABYLON;
  62262. (function (BABYLON) {
  62263. var Debug;
  62264. (function (Debug) {
  62265. var AxesViewer = (function () {
  62266. function AxesViewer(scene, scaleLines) {
  62267. if (scaleLines === void 0) { scaleLines = 1; }
  62268. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62269. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62270. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62271. this.scaleLines = 1;
  62272. this.scaleLines = scaleLines;
  62273. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62274. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62275. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62276. this._xmesh.renderingGroupId = 2;
  62277. this._ymesh.renderingGroupId = 2;
  62278. this._zmesh.renderingGroupId = 2;
  62279. this._xmesh.material.checkReadyOnlyOnce = true;
  62280. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62281. this._ymesh.material.checkReadyOnlyOnce = true;
  62282. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62283. this._zmesh.material.checkReadyOnlyOnce = true;
  62284. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62285. this.scene = scene;
  62286. }
  62287. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62288. var scaleLines = this.scaleLines;
  62289. this._xmesh.position.copyFrom(position);
  62290. this._ymesh.position.copyFrom(position);
  62291. this._zmesh.position.copyFrom(position);
  62292. var point2 = this._xline[1];
  62293. point2.x = xaxis.x * scaleLines;
  62294. point2.y = xaxis.y * scaleLines;
  62295. point2.z = xaxis.z * scaleLines;
  62296. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  62297. point2 = this._yline[1];
  62298. point2.x = yaxis.x * scaleLines;
  62299. point2.y = yaxis.y * scaleLines;
  62300. point2.z = yaxis.z * scaleLines;
  62301. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  62302. point2 = this._zline[1];
  62303. point2.x = zaxis.x * scaleLines;
  62304. point2.y = zaxis.y * scaleLines;
  62305. point2.z = zaxis.z * scaleLines;
  62306. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  62307. };
  62308. AxesViewer.prototype.dispose = function () {
  62309. if (this._xmesh) {
  62310. this._xmesh.dispose();
  62311. this._ymesh.dispose();
  62312. this._zmesh.dispose();
  62313. this._xmesh = null;
  62314. this._ymesh = null;
  62315. this._zmesh = null;
  62316. this._xline = null;
  62317. this._yline = null;
  62318. this._zline = null;
  62319. this.scene = null;
  62320. }
  62321. };
  62322. return AxesViewer;
  62323. }());
  62324. Debug.AxesViewer = AxesViewer;
  62325. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62326. })(BABYLON || (BABYLON = {}));
  62327. //# sourceMappingURL=babylon.axesViewer.js.map
  62328. var BABYLON;
  62329. (function (BABYLON) {
  62330. var Debug;
  62331. (function (Debug) {
  62332. var BoneAxesViewer = (function (_super) {
  62333. __extends(BoneAxesViewer, _super);
  62334. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62335. if (scaleLines === void 0) { scaleLines = 1; }
  62336. var _this = _super.call(this, scene, scaleLines) || this;
  62337. _this.pos = BABYLON.Vector3.Zero();
  62338. _this.xaxis = BABYLON.Vector3.Zero();
  62339. _this.yaxis = BABYLON.Vector3.Zero();
  62340. _this.zaxis = BABYLON.Vector3.Zero();
  62341. _this.mesh = mesh;
  62342. _this.bone = bone;
  62343. return _this;
  62344. }
  62345. BoneAxesViewer.prototype.update = function () {
  62346. var bone = this.bone;
  62347. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62348. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62349. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62350. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62351. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62352. };
  62353. BoneAxesViewer.prototype.dispose = function () {
  62354. if (this.pos) {
  62355. this.pos = null;
  62356. this.xaxis = null;
  62357. this.yaxis = null;
  62358. this.zaxis = null;
  62359. this.mesh = null;
  62360. this.bone = null;
  62361. _super.prototype.dispose.call(this);
  62362. }
  62363. };
  62364. return BoneAxesViewer;
  62365. }(Debug.AxesViewer));
  62366. Debug.BoneAxesViewer = BoneAxesViewer;
  62367. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62368. })(BABYLON || (BABYLON = {}));
  62369. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62370. var BABYLON;
  62371. (function (BABYLON) {
  62372. var RayHelper = (function () {
  62373. function RayHelper(ray) {
  62374. this.ray = ray;
  62375. }
  62376. RayHelper.CreateAndShow = function (ray, scene, color) {
  62377. var helper = new RayHelper(ray);
  62378. helper.show(scene, color);
  62379. return helper;
  62380. };
  62381. RayHelper.prototype.show = function (scene, color) {
  62382. if (!this._renderFunction) {
  62383. var ray = this.ray;
  62384. this._renderFunction = this._render.bind(this);
  62385. this._scene = scene;
  62386. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62387. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62388. this._scene.registerBeforeRender(this._renderFunction);
  62389. }
  62390. if (color) {
  62391. this._renderLine.color.copyFrom(color);
  62392. }
  62393. };
  62394. RayHelper.prototype.hide = function () {
  62395. if (this._renderFunction) {
  62396. this._scene.unregisterBeforeRender(this._renderFunction);
  62397. this._scene = null;
  62398. this._renderFunction = null;
  62399. this._renderLine.dispose();
  62400. this._renderLine = null;
  62401. this._renderPoints = null;
  62402. }
  62403. };
  62404. RayHelper.prototype._render = function () {
  62405. var ray = this.ray;
  62406. var point = this._renderPoints[1];
  62407. var len = Math.min(ray.length, 1000000);
  62408. point.copyFrom(ray.direction);
  62409. point.scaleInPlace(len);
  62410. point.addInPlace(ray.origin);
  62411. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62412. };
  62413. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62414. this._attachedToMesh = mesh;
  62415. var ray = this.ray;
  62416. if (!ray.direction) {
  62417. ray.direction = BABYLON.Vector3.Zero();
  62418. }
  62419. if (!ray.origin) {
  62420. ray.origin = BABYLON.Vector3.Zero();
  62421. }
  62422. if (length) {
  62423. ray.length = length;
  62424. }
  62425. if (!meshSpaceOrigin) {
  62426. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62427. }
  62428. if (!meshSpaceDirection) {
  62429. // -1 so that this will work with Mesh.lookAt
  62430. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62431. }
  62432. if (!this._meshSpaceDirection) {
  62433. this._meshSpaceDirection = meshSpaceDirection.clone();
  62434. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62435. }
  62436. else {
  62437. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62438. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62439. }
  62440. if (!this._updateToMeshFunction) {
  62441. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62442. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62443. }
  62444. this._updateToMesh();
  62445. };
  62446. RayHelper.prototype.detachFromMesh = function () {
  62447. if (this._attachedToMesh) {
  62448. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62449. this._attachedToMesh = null;
  62450. this._updateToMeshFunction = null;
  62451. }
  62452. };
  62453. RayHelper.prototype._updateToMesh = function () {
  62454. var ray = this.ray;
  62455. if (this._attachedToMesh._isDisposed) {
  62456. this.detachFromMesh();
  62457. return;
  62458. }
  62459. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62460. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62461. };
  62462. RayHelper.prototype.dispose = function () {
  62463. this.hide();
  62464. this.detachFromMesh();
  62465. this.ray = null;
  62466. };
  62467. return RayHelper;
  62468. }());
  62469. BABYLON.RayHelper = RayHelper;
  62470. })(BABYLON || (BABYLON = {}));
  62471. //# sourceMappingURL=babylon.rayHelper.js.map
  62472. var BABYLON;
  62473. (function (BABYLON) {
  62474. var DebugLayer = (function () {
  62475. function DebugLayer(scene) {
  62476. this._scene = scene;
  62477. }
  62478. /** Creates the inspector window. */
  62479. DebugLayer.prototype._createInspector = function (config) {
  62480. if (config === void 0) { config = {}; }
  62481. var popup = config.popup || false;
  62482. var initialTab = config.initialTab || 0;
  62483. var parentElement = config.parentElement || null;
  62484. if (!this._inspector) {
  62485. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62486. } // else nothing to do,; instance is already existing
  62487. };
  62488. DebugLayer.prototype.isVisible = function () {
  62489. if (!this._inspector) {
  62490. return false;
  62491. }
  62492. return true;
  62493. };
  62494. DebugLayer.prototype.hide = function () {
  62495. if (this._inspector) {
  62496. try {
  62497. this._inspector.dispose();
  62498. }
  62499. catch (e) {
  62500. // If the inspector has been removed directly from the inspector tool
  62501. }
  62502. this._inspector = null;
  62503. }
  62504. };
  62505. DebugLayer.prototype.show = function (config) {
  62506. if (config === void 0) { config = {}; }
  62507. if (typeof INSPECTOR == 'undefined') {
  62508. // Load inspector and add it to the DOM
  62509. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62510. }
  62511. else {
  62512. // Otherwise creates the inspector
  62513. this._createInspector(config);
  62514. }
  62515. };
  62516. // Get protocol used - http or https
  62517. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62518. return DebugLayer;
  62519. }());
  62520. BABYLON.DebugLayer = DebugLayer;
  62521. })(BABYLON || (BABYLON = {}));
  62522. //# sourceMappingURL=babylon.debugLayer.js.map
  62523. var BABYLON;
  62524. (function (BABYLON) {
  62525. var Debug;
  62526. (function (Debug) {
  62527. var PhysicsViewer = (function () {
  62528. function PhysicsViewer(scene) {
  62529. this._impostors = [];
  62530. this._meshes = [];
  62531. this._numMeshes = 0;
  62532. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62533. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  62534. }
  62535. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62536. var plugin = this._physicsEnginePlugin;
  62537. for (var i = 0; i < this._numMeshes; i++) {
  62538. if (this._impostors[i].isDisposed) {
  62539. this.hideImpostor(this._impostors[i--]);
  62540. }
  62541. else {
  62542. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  62543. }
  62544. }
  62545. };
  62546. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62547. for (var i = 0; i < this._numMeshes; i++) {
  62548. if (this._impostors[i] == impostor) {
  62549. return;
  62550. }
  62551. }
  62552. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62553. if (debugMesh) {
  62554. this._impostors[this._numMeshes] = impostor;
  62555. this._meshes[this._numMeshes] = debugMesh;
  62556. if (this._numMeshes === 0) {
  62557. this._renderFunction = this._updateDebugMeshes.bind(this);
  62558. this._scene.registerBeforeRender(this._renderFunction);
  62559. }
  62560. this._numMeshes++;
  62561. }
  62562. };
  62563. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62564. var removed = false;
  62565. for (var i = 0; i < this._numMeshes; i++) {
  62566. if (this._impostors[i] == impostor) {
  62567. this._scene.removeMesh(this._meshes[i]);
  62568. this._meshes[i].dispose();
  62569. this._numMeshes--;
  62570. if (this._numMeshes > 0) {
  62571. this._meshes[i] = this._meshes[this._numMeshes];
  62572. this._impostors[i] = this._impostors[this._numMeshes];
  62573. this._meshes[this._numMeshes] = null;
  62574. this._impostors[this._numMeshes] = null;
  62575. }
  62576. else {
  62577. this._meshes[0] = null;
  62578. this._impostors[0] = null;
  62579. }
  62580. removed = true;
  62581. break;
  62582. }
  62583. }
  62584. if (removed && this._numMeshes === 0) {
  62585. this._scene.unregisterBeforeRender(this._renderFunction);
  62586. }
  62587. };
  62588. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62589. if (!this._debugMaterial) {
  62590. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62591. this._debugMaterial.wireframe = true;
  62592. }
  62593. return this._debugMaterial;
  62594. };
  62595. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62596. if (!this._debugBoxMesh) {
  62597. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62598. this._debugBoxMesh.renderingGroupId = 1;
  62599. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62600. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62601. scene.removeMesh(this._debugBoxMesh);
  62602. }
  62603. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62604. };
  62605. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62606. if (!this._debugSphereMesh) {
  62607. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62608. this._debugSphereMesh.renderingGroupId = 1;
  62609. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62610. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62611. scene.removeMesh(this._debugSphereMesh);
  62612. }
  62613. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62614. };
  62615. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62616. var body = impostor.physicsBody;
  62617. var shape = body.shapes[0];
  62618. var mesh;
  62619. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62620. mesh = this._getDebugBoxMesh(scene);
  62621. impostor.getBoxSizeToRef(mesh.scaling);
  62622. }
  62623. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62624. mesh = this._getDebugSphereMesh(scene);
  62625. var radius = impostor.getRadius();
  62626. mesh.scaling.x = radius * 2;
  62627. mesh.scaling.y = radius * 2;
  62628. mesh.scaling.z = radius * 2;
  62629. }
  62630. return mesh;
  62631. };
  62632. PhysicsViewer.prototype.dispose = function () {
  62633. for (var i = 0; i < this._numMeshes; i++) {
  62634. this.hideImpostor(this._impostors[i]);
  62635. }
  62636. if (this._debugBoxMesh) {
  62637. this._debugBoxMesh.dispose();
  62638. }
  62639. if (this._debugSphereMesh) {
  62640. this._debugSphereMesh.dispose();
  62641. }
  62642. if (this._debugMaterial) {
  62643. this._debugMaterial.dispose();
  62644. }
  62645. this._impostors.length = 0;
  62646. this._scene = null;
  62647. this._physicsEnginePlugin = null;
  62648. };
  62649. return PhysicsViewer;
  62650. }());
  62651. Debug.PhysicsViewer = PhysicsViewer;
  62652. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62653. })(BABYLON || (BABYLON = {}));
  62654. //# sourceMappingURL=babylon.physicsViewer.js.map
  62655. var BABYLON;
  62656. (function (BABYLON) {
  62657. var BoundingBoxRenderer = (function () {
  62658. function BoundingBoxRenderer(scene) {
  62659. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62660. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62661. this.showBackLines = true;
  62662. this.renderList = new BABYLON.SmartArray(32);
  62663. this._vertexBuffers = {};
  62664. this._scene = scene;
  62665. }
  62666. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62667. if (this._colorShader) {
  62668. return;
  62669. }
  62670. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  62671. attributes: [BABYLON.VertexBuffer.PositionKind],
  62672. uniforms: ["world", "viewProjection", "color"]
  62673. });
  62674. var engine = this._scene.getEngine();
  62675. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62676. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62677. 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]);
  62678. };
  62679. BoundingBoxRenderer.prototype.reset = function () {
  62680. this.renderList.reset();
  62681. };
  62682. BoundingBoxRenderer.prototype.render = function () {
  62683. if (this.renderList.length === 0) {
  62684. return;
  62685. }
  62686. this._prepareRessources();
  62687. if (!this._colorShader.isReady()) {
  62688. return;
  62689. }
  62690. var engine = this._scene.getEngine();
  62691. engine.setDepthWrite(false);
  62692. this._colorShader._preBind();
  62693. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62694. var boundingBox = this.renderList.data[boundingBoxIndex];
  62695. var min = boundingBox.minimum;
  62696. var max = boundingBox.maximum;
  62697. var diff = max.subtract(min);
  62698. var median = min.add(diff.scale(0.5));
  62699. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62700. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62701. .multiply(boundingBox.getWorldMatrix());
  62702. // VBOs
  62703. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62704. if (this.showBackLines) {
  62705. // Back
  62706. engine.setDepthFunctionToGreaterOrEqual();
  62707. this._scene.resetCachedMaterial();
  62708. this._colorShader.setColor4("color", this.backColor.toColor4());
  62709. this._colorShader.bind(worldMatrix);
  62710. // Draw order
  62711. engine.draw(false, 0, 24);
  62712. }
  62713. // Front
  62714. engine.setDepthFunctionToLess();
  62715. this._scene.resetCachedMaterial();
  62716. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62717. this._colorShader.bind(worldMatrix);
  62718. // Draw order
  62719. engine.draw(false, 0, 24);
  62720. }
  62721. this._colorShader.unbind();
  62722. engine.setDepthFunctionToLessOrEqual();
  62723. engine.setDepthWrite(true);
  62724. };
  62725. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  62726. this._prepareRessources();
  62727. if (!this._colorShader.isReady()) {
  62728. return;
  62729. }
  62730. var engine = this._scene.getEngine();
  62731. engine.setDepthWrite(false);
  62732. engine.setColorWrite(false);
  62733. this._colorShader._preBind();
  62734. var boundingBox = mesh._boundingInfo.boundingBox;
  62735. var min = boundingBox.minimum;
  62736. var max = boundingBox.maximum;
  62737. var diff = max.subtract(min);
  62738. var median = min.add(diff.scale(0.5));
  62739. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62740. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62741. .multiply(boundingBox.getWorldMatrix());
  62742. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62743. engine.setDepthFunctionToLess();
  62744. this._scene.resetCachedMaterial();
  62745. this._colorShader.bind(worldMatrix);
  62746. engine.draw(false, 0, 24);
  62747. this._colorShader.unbind();
  62748. engine.setDepthFunctionToLessOrEqual();
  62749. engine.setDepthWrite(true);
  62750. engine.setColorWrite(true);
  62751. };
  62752. BoundingBoxRenderer.prototype.dispose = function () {
  62753. if (!this._colorShader) {
  62754. return;
  62755. }
  62756. this.renderList.dispose();
  62757. this._colorShader.dispose();
  62758. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62759. if (buffer) {
  62760. buffer.dispose();
  62761. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62762. }
  62763. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62764. };
  62765. return BoundingBoxRenderer;
  62766. }());
  62767. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  62768. })(BABYLON || (BABYLON = {}));
  62769. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  62770. var BABYLON;
  62771. (function (BABYLON) {
  62772. var MorphTarget = (function () {
  62773. function MorphTarget(name, influence) {
  62774. if (influence === void 0) { influence = 0; }
  62775. this.name = name;
  62776. this.animations = new Array();
  62777. this.onInfluenceChanged = new BABYLON.Observable();
  62778. this.influence = influence;
  62779. }
  62780. Object.defineProperty(MorphTarget.prototype, "influence", {
  62781. get: function () {
  62782. return this._influence;
  62783. },
  62784. set: function (influence) {
  62785. if (this._influence === influence) {
  62786. return;
  62787. }
  62788. var previous = this._influence;
  62789. this._influence = influence;
  62790. if (this.onInfluenceChanged.hasObservers) {
  62791. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  62792. }
  62793. },
  62794. enumerable: true,
  62795. configurable: true
  62796. });
  62797. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  62798. get: function () {
  62799. return this._normals !== undefined;
  62800. },
  62801. enumerable: true,
  62802. configurable: true
  62803. });
  62804. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  62805. get: function () {
  62806. return this._tangents !== undefined;
  62807. },
  62808. enumerable: true,
  62809. configurable: true
  62810. });
  62811. MorphTarget.prototype.setPositions = function (data) {
  62812. this._positions = new Float32Array(data);
  62813. };
  62814. MorphTarget.prototype.getPositions = function () {
  62815. return this._positions;
  62816. };
  62817. MorphTarget.prototype.setNormals = function (data) {
  62818. this._normals = new Float32Array(data);
  62819. };
  62820. MorphTarget.prototype.getNormals = function () {
  62821. return this._normals;
  62822. };
  62823. MorphTarget.prototype.setTangents = function (data) {
  62824. this._tangents = new Float32Array(data);
  62825. };
  62826. MorphTarget.prototype.getTangents = function () {
  62827. return this._tangents;
  62828. };
  62829. /**
  62830. * Serializes the current target into a Serialization object.
  62831. * Returns the serialized object.
  62832. */
  62833. MorphTarget.prototype.serialize = function () {
  62834. var serializationObject = {};
  62835. serializationObject.name = this.name;
  62836. serializationObject.influence = this.influence;
  62837. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  62838. if (this.hasNormals) {
  62839. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  62840. }
  62841. if (this.hasTangents) {
  62842. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  62843. }
  62844. return serializationObject;
  62845. };
  62846. // Statics
  62847. MorphTarget.Parse = function (serializationObject) {
  62848. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  62849. result.setPositions(serializationObject.positions);
  62850. if (serializationObject.normals) {
  62851. result.setNormals(serializationObject.normals);
  62852. }
  62853. if (serializationObject.tangents) {
  62854. result.setTangents(serializationObject.tangents);
  62855. }
  62856. return result;
  62857. };
  62858. MorphTarget.FromMesh = function (mesh, name, influence) {
  62859. if (!name) {
  62860. name = mesh.name;
  62861. }
  62862. var result = new MorphTarget(name, influence);
  62863. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  62864. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62865. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  62866. }
  62867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  62868. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  62869. }
  62870. return result;
  62871. };
  62872. return MorphTarget;
  62873. }());
  62874. BABYLON.MorphTarget = MorphTarget;
  62875. })(BABYLON || (BABYLON = {}));
  62876. //# sourceMappingURL=babylon.morphTarget.js.map
  62877. var BABYLON;
  62878. (function (BABYLON) {
  62879. var MorphTargetManager = (function () {
  62880. function MorphTargetManager(scene) {
  62881. this._targets = new Array();
  62882. this._targetObservable = new Array();
  62883. this._activeTargets = new BABYLON.SmartArray(16);
  62884. this._supportsNormals = false;
  62885. this._supportsTangents = false;
  62886. this._vertexCount = 0;
  62887. this._uniqueId = 0;
  62888. this._tempInfluences = new Array();
  62889. if (!scene) {
  62890. scene = BABYLON.Engine.LastCreatedScene;
  62891. }
  62892. this._scene = scene;
  62893. this._scene.morphTargetManagers.push(this);
  62894. this._uniqueId = scene.getUniqueId();
  62895. }
  62896. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  62897. get: function () {
  62898. return this._uniqueId;
  62899. },
  62900. enumerable: true,
  62901. configurable: true
  62902. });
  62903. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  62904. get: function () {
  62905. return this._vertexCount;
  62906. },
  62907. enumerable: true,
  62908. configurable: true
  62909. });
  62910. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  62911. get: function () {
  62912. return this._supportsNormals;
  62913. },
  62914. enumerable: true,
  62915. configurable: true
  62916. });
  62917. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  62918. get: function () {
  62919. return this._supportsTangents;
  62920. },
  62921. enumerable: true,
  62922. configurable: true
  62923. });
  62924. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  62925. get: function () {
  62926. return this._targets.length;
  62927. },
  62928. enumerable: true,
  62929. configurable: true
  62930. });
  62931. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  62932. get: function () {
  62933. return this._activeTargets.length;
  62934. },
  62935. enumerable: true,
  62936. configurable: true
  62937. });
  62938. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  62939. get: function () {
  62940. return this._influences;
  62941. },
  62942. enumerable: true,
  62943. configurable: true
  62944. });
  62945. MorphTargetManager.prototype.getActiveTarget = function (index) {
  62946. return this._activeTargets.data[index];
  62947. };
  62948. MorphTargetManager.prototype.getTarget = function (index) {
  62949. return this._targets[index];
  62950. };
  62951. MorphTargetManager.prototype.addTarget = function (target) {
  62952. var _this = this;
  62953. if (this._vertexCount) {
  62954. if (this._vertexCount !== target.getPositions().length / 3) {
  62955. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  62956. return;
  62957. }
  62958. }
  62959. this._targets.push(target);
  62960. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  62961. _this._syncActiveTargets(needUpdate);
  62962. }));
  62963. this._syncActiveTargets(true);
  62964. };
  62965. MorphTargetManager.prototype.removeTarget = function (target) {
  62966. var index = this._targets.indexOf(target);
  62967. if (index >= 0) {
  62968. this._targets.splice(index, 1);
  62969. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  62970. this._vertexCount = 0;
  62971. this._syncActiveTargets(true);
  62972. }
  62973. };
  62974. /**
  62975. * Serializes the current manager into a Serialization object.
  62976. * Returns the serialized object.
  62977. */
  62978. MorphTargetManager.prototype.serialize = function () {
  62979. var serializationObject = {};
  62980. serializationObject.id = this.uniqueId;
  62981. serializationObject.targets = [];
  62982. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  62983. var target = _a[_i];
  62984. serializationObject.targets.push(target.serialize());
  62985. }
  62986. return serializationObject;
  62987. };
  62988. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  62989. this._syncActiveTargets(needUpdate);
  62990. };
  62991. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  62992. var influenceCount = 0;
  62993. this._activeTargets.reset();
  62994. this._supportsNormals = true;
  62995. this._supportsTangents = true;
  62996. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  62997. var target = _a[_i];
  62998. if (target.influence > 0) {
  62999. this._activeTargets.push(target);
  63000. this._tempInfluences[influenceCount++] = target.influence;
  63001. this._supportsNormals = this._supportsNormals && target.hasNormals;
  63002. this._supportsTangents = this._supportsTangents && target.hasTangents;
  63003. if (this._vertexCount === 0) {
  63004. this._vertexCount = target.getPositions().length / 3;
  63005. }
  63006. }
  63007. }
  63008. if (!this._influences || this._influences.length !== influenceCount) {
  63009. this._influences = new Float32Array(influenceCount);
  63010. }
  63011. for (var index = 0; index < influenceCount; index++) {
  63012. this._influences[index] = this._tempInfluences[index];
  63013. }
  63014. if (needUpdate) {
  63015. // Flag meshes as dirty to resync with the active targets
  63016. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  63017. var mesh = _c[_b];
  63018. if (mesh.morphTargetManager === this) {
  63019. mesh._syncGeometryWithMorphTargetManager();
  63020. }
  63021. }
  63022. }
  63023. };
  63024. // Statics
  63025. MorphTargetManager.Parse = function (serializationObject, scene) {
  63026. var result = new MorphTargetManager(scene);
  63027. result._uniqueId = serializationObject.id;
  63028. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  63029. var targetData = _a[_i];
  63030. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  63031. }
  63032. return result;
  63033. };
  63034. return MorphTargetManager;
  63035. }());
  63036. BABYLON.MorphTargetManager = MorphTargetManager;
  63037. })(BABYLON || (BABYLON = {}));
  63038. //# sourceMappingURL=babylon.morphTargetManager.js.map
  63039. var BABYLON;
  63040. (function (BABYLON) {
  63041. /**
  63042. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  63043. * It can help converting any input color in a desired output one. This can then be used to create effects
  63044. * from sepia, black and white to sixties or futuristic rendering...
  63045. *
  63046. * The only supported format is currently 3dl.
  63047. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  63048. */
  63049. var ColorGradingTexture = (function (_super) {
  63050. __extends(ColorGradingTexture, _super);
  63051. /**
  63052. * Instantiates a ColorGradingTexture from the following parameters.
  63053. *
  63054. * @param url The location of the color gradind data (currently only supporting 3dl)
  63055. * @param scene The scene the texture will be used in
  63056. */
  63057. function ColorGradingTexture(url, scene) {
  63058. var _this = _super.call(this, scene) || this;
  63059. if (!url) {
  63060. return _this;
  63061. }
  63062. _this._textureMatrix = BABYLON.Matrix.Identity();
  63063. _this.name = url;
  63064. _this.url = url;
  63065. _this.hasAlpha = false;
  63066. _this.isCube = false;
  63067. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63068. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63069. _this.anisotropicFilteringLevel = 1;
  63070. _this._texture = _this._getFromCache(url, true);
  63071. if (!_this._texture) {
  63072. if (!scene.useDelayedTextureLoading) {
  63073. _this.loadTexture();
  63074. }
  63075. else {
  63076. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63077. }
  63078. }
  63079. return _this;
  63080. }
  63081. /**
  63082. * Returns the texture matrix used in most of the material.
  63083. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  63084. */
  63085. ColorGradingTexture.prototype.getTextureMatrix = function () {
  63086. return this._textureMatrix;
  63087. };
  63088. /**
  63089. * Occurs when the file being loaded is a .3dl LUT file.
  63090. */
  63091. ColorGradingTexture.prototype.load3dlTexture = function () {
  63092. var _this = this;
  63093. var mipLevels = 0;
  63094. var floatArrayView = null;
  63095. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63096. this._texture = texture;
  63097. var callback = function (text) {
  63098. var data;
  63099. var tempData;
  63100. var line;
  63101. var lines = text.split('\n');
  63102. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  63103. var maxColor = 0;
  63104. for (var i = 0; i < lines.length; i++) {
  63105. line = lines[i];
  63106. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  63107. continue;
  63108. if (line.indexOf('#') === 0)
  63109. continue;
  63110. var words = line.split(" ");
  63111. if (size === 0) {
  63112. // Number of space + one
  63113. size = words.length;
  63114. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  63115. tempData = new Float32Array(size * size * size * 4);
  63116. continue;
  63117. }
  63118. if (size != 0) {
  63119. var r = Math.max(parseInt(words[0]), 0);
  63120. var g = Math.max(parseInt(words[1]), 0);
  63121. var b = Math.max(parseInt(words[2]), 0);
  63122. maxColor = Math.max(r, maxColor);
  63123. maxColor = Math.max(g, maxColor);
  63124. maxColor = Math.max(b, maxColor);
  63125. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  63126. tempData[pixelStorageIndex + 0] = r;
  63127. tempData[pixelStorageIndex + 1] = g;
  63128. tempData[pixelStorageIndex + 2] = b;
  63129. pixelIndexSlice++;
  63130. if (pixelIndexSlice % size == 0) {
  63131. pixelIndexH++;
  63132. pixelIndexSlice = 0;
  63133. if (pixelIndexH % size == 0) {
  63134. pixelIndexW++;
  63135. pixelIndexH = 0;
  63136. }
  63137. }
  63138. }
  63139. }
  63140. for (var i = 0; i < tempData.length; i++) {
  63141. if (i > 0 && (i + 1) % 4 === 0) {
  63142. data[i] = 255;
  63143. }
  63144. else {
  63145. var value = tempData[i];
  63146. data[i] = (value / maxColor * 255);
  63147. }
  63148. }
  63149. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  63150. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  63151. };
  63152. BABYLON.Tools.LoadFile(this.url, callback);
  63153. return this._texture;
  63154. };
  63155. /**
  63156. * Starts the loading process of the texture.
  63157. */
  63158. ColorGradingTexture.prototype.loadTexture = function () {
  63159. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  63160. this.load3dlTexture();
  63161. }
  63162. };
  63163. /**
  63164. * Clones the color gradind texture.
  63165. */
  63166. ColorGradingTexture.prototype.clone = function () {
  63167. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  63168. // Base texture
  63169. newTexture.level = this.level;
  63170. return newTexture;
  63171. };
  63172. /**
  63173. * Called during delayed load for textures.
  63174. */
  63175. ColorGradingTexture.prototype.delayLoad = function () {
  63176. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63177. return;
  63178. }
  63179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63180. this._texture = this._getFromCache(this.url, true);
  63181. if (!this._texture) {
  63182. this.loadTexture();
  63183. }
  63184. };
  63185. /**
  63186. * Parses a color grading texture serialized by Babylon.
  63187. * @param parsedTexture The texture information being parsedTexture
  63188. * @param scene The scene to load the texture in
  63189. * @param rootUrl The root url of the data assets to load
  63190. * @return A color gradind texture
  63191. */
  63192. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63193. var texture = null;
  63194. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63195. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  63196. texture.name = parsedTexture.name;
  63197. texture.level = parsedTexture.level;
  63198. }
  63199. return texture;
  63200. };
  63201. /**
  63202. * Serializes the LUT texture to json format.
  63203. */
  63204. ColorGradingTexture.prototype.serialize = function () {
  63205. if (!this.name) {
  63206. return null;
  63207. }
  63208. var serializationObject = {};
  63209. serializationObject.name = this.name;
  63210. serializationObject.level = this.level;
  63211. serializationObject.customType = "BABYLON.ColorGradingTexture";
  63212. return serializationObject;
  63213. };
  63214. /**
  63215. * Empty line regex stored for GC.
  63216. */
  63217. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  63218. return ColorGradingTexture;
  63219. }(BABYLON.BaseTexture));
  63220. BABYLON.ColorGradingTexture = ColorGradingTexture;
  63221. })(BABYLON || (BABYLON = {}));
  63222. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  63223. var BABYLON;
  63224. (function (BABYLON) {
  63225. /**
  63226. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  63227. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  63228. * 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;
  63229. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  63230. */
  63231. var ColorCurves = (function () {
  63232. function ColorCurves() {
  63233. this._dirty = true;
  63234. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  63235. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  63236. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  63237. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  63238. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  63239. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  63240. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  63241. this._globalHue = 30;
  63242. this._globalDensity = 0;
  63243. this._globalSaturation = 0;
  63244. this._globalExposure = 0;
  63245. this._highlightsHue = 30;
  63246. this._highlightsDensity = 0;
  63247. this._highlightsSaturation = 0;
  63248. this._highlightsExposure = 0;
  63249. this._midtonesHue = 30;
  63250. this._midtonesDensity = 0;
  63251. this._midtonesSaturation = 0;
  63252. this._midtonesExposure = 0;
  63253. this._shadowsHue = 30;
  63254. this._shadowsDensity = 0;
  63255. this._shadowsSaturation = 0;
  63256. this._shadowsExposure = 0;
  63257. }
  63258. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  63259. /**
  63260. * Gets the global Hue value.
  63261. * 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).
  63262. */
  63263. get: function () {
  63264. return this._globalHue;
  63265. },
  63266. /**
  63267. * Sets the global Hue value.
  63268. * 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).
  63269. */
  63270. set: function (value) {
  63271. this._globalHue = value;
  63272. this._dirty = true;
  63273. },
  63274. enumerable: true,
  63275. configurable: true
  63276. });
  63277. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  63278. /**
  63279. * Gets the global Density value.
  63280. * 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.
  63281. * Values less than zero provide a filter of opposite hue.
  63282. */
  63283. get: function () {
  63284. return this._globalDensity;
  63285. },
  63286. /**
  63287. * Sets the global Density value.
  63288. * 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.
  63289. * Values less than zero provide a filter of opposite hue.
  63290. */
  63291. set: function (value) {
  63292. this._globalDensity = value;
  63293. this._dirty = true;
  63294. },
  63295. enumerable: true,
  63296. configurable: true
  63297. });
  63298. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  63299. /**
  63300. * Gets the global Saturation value.
  63301. * 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.
  63302. */
  63303. get: function () {
  63304. return this._globalSaturation;
  63305. },
  63306. /**
  63307. * Sets the global Saturation value.
  63308. * 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.
  63309. */
  63310. set: function (value) {
  63311. this._globalSaturation = value;
  63312. this._dirty = true;
  63313. },
  63314. enumerable: true,
  63315. configurable: true
  63316. });
  63317. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  63318. /**
  63319. * Gets the highlights Hue value.
  63320. * 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).
  63321. */
  63322. get: function () {
  63323. return this._highlightsHue;
  63324. },
  63325. /**
  63326. * Sets the highlights Hue value.
  63327. * 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).
  63328. */
  63329. set: function (value) {
  63330. this._highlightsHue = value;
  63331. this._dirty = true;
  63332. },
  63333. enumerable: true,
  63334. configurable: true
  63335. });
  63336. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  63337. /**
  63338. * Gets the highlights Density value.
  63339. * 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.
  63340. * Values less than zero provide a filter of opposite hue.
  63341. */
  63342. get: function () {
  63343. return this._highlightsDensity;
  63344. },
  63345. /**
  63346. * Sets the highlights Density value.
  63347. * 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.
  63348. * Values less than zero provide a filter of opposite hue.
  63349. */
  63350. set: function (value) {
  63351. this._highlightsDensity = value;
  63352. this._dirty = true;
  63353. },
  63354. enumerable: true,
  63355. configurable: true
  63356. });
  63357. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  63358. /**
  63359. * Gets the highlights Saturation value.
  63360. * 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.
  63361. */
  63362. get: function () {
  63363. return this._highlightsSaturation;
  63364. },
  63365. /**
  63366. * Sets the highlights Saturation value.
  63367. * 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.
  63368. */
  63369. set: function (value) {
  63370. this._highlightsSaturation = value;
  63371. this._dirty = true;
  63372. },
  63373. enumerable: true,
  63374. configurable: true
  63375. });
  63376. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  63377. /**
  63378. * Gets the highlights Exposure value.
  63379. * 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.
  63380. */
  63381. get: function () {
  63382. return this._highlightsExposure;
  63383. },
  63384. /**
  63385. * Sets the highlights Exposure value.
  63386. * 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.
  63387. */
  63388. set: function (value) {
  63389. this._highlightsExposure = value;
  63390. this._dirty = true;
  63391. },
  63392. enumerable: true,
  63393. configurable: true
  63394. });
  63395. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  63396. /**
  63397. * Gets the midtones Hue value.
  63398. * 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).
  63399. */
  63400. get: function () {
  63401. return this._midtonesHue;
  63402. },
  63403. /**
  63404. * Sets the midtones Hue value.
  63405. * 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).
  63406. */
  63407. set: function (value) {
  63408. this._midtonesHue = value;
  63409. this._dirty = true;
  63410. },
  63411. enumerable: true,
  63412. configurable: true
  63413. });
  63414. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  63415. /**
  63416. * Gets the midtones Density value.
  63417. * 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.
  63418. * Values less than zero provide a filter of opposite hue.
  63419. */
  63420. get: function () {
  63421. return this._midtonesDensity;
  63422. },
  63423. /**
  63424. * Sets the midtones Density value.
  63425. * 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.
  63426. * Values less than zero provide a filter of opposite hue.
  63427. */
  63428. set: function (value) {
  63429. this._midtonesDensity = value;
  63430. this._dirty = true;
  63431. },
  63432. enumerable: true,
  63433. configurable: true
  63434. });
  63435. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  63436. /**
  63437. * Gets the midtones Saturation value.
  63438. * 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.
  63439. */
  63440. get: function () {
  63441. return this._midtonesSaturation;
  63442. },
  63443. /**
  63444. * Sets the midtones Saturation value.
  63445. * 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.
  63446. */
  63447. set: function (value) {
  63448. this._midtonesSaturation = value;
  63449. this._dirty = true;
  63450. },
  63451. enumerable: true,
  63452. configurable: true
  63453. });
  63454. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  63455. /**
  63456. * Gets the midtones Exposure value.
  63457. * 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.
  63458. */
  63459. get: function () {
  63460. return this._midtonesExposure;
  63461. },
  63462. /**
  63463. * Sets the midtones Exposure value.
  63464. * 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.
  63465. */
  63466. set: function (value) {
  63467. this._midtonesExposure = value;
  63468. this._dirty = true;
  63469. },
  63470. enumerable: true,
  63471. configurable: true
  63472. });
  63473. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  63474. /**
  63475. * Gets the shadows Hue value.
  63476. * 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).
  63477. */
  63478. get: function () {
  63479. return this._shadowsHue;
  63480. },
  63481. /**
  63482. * Sets the shadows Hue value.
  63483. * 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).
  63484. */
  63485. set: function (value) {
  63486. this._shadowsHue = value;
  63487. this._dirty = true;
  63488. },
  63489. enumerable: true,
  63490. configurable: true
  63491. });
  63492. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  63493. /**
  63494. * Gets the shadows Density value.
  63495. * 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.
  63496. * Values less than zero provide a filter of opposite hue.
  63497. */
  63498. get: function () {
  63499. return this._shadowsDensity;
  63500. },
  63501. /**
  63502. * Sets the shadows Density value.
  63503. * 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.
  63504. * Values less than zero provide a filter of opposite hue.
  63505. */
  63506. set: function (value) {
  63507. this._shadowsDensity = value;
  63508. this._dirty = true;
  63509. },
  63510. enumerable: true,
  63511. configurable: true
  63512. });
  63513. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  63514. /**
  63515. * Gets the shadows Saturation value.
  63516. * 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.
  63517. */
  63518. get: function () {
  63519. return this._shadowsSaturation;
  63520. },
  63521. /**
  63522. * Sets the shadows Saturation value.
  63523. * 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.
  63524. */
  63525. set: function (value) {
  63526. this._shadowsSaturation = value;
  63527. this._dirty = true;
  63528. },
  63529. enumerable: true,
  63530. configurable: true
  63531. });
  63532. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  63533. /**
  63534. * Gets the shadows Exposure value.
  63535. * 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.
  63536. */
  63537. get: function () {
  63538. return this._shadowsExposure;
  63539. },
  63540. /**
  63541. * Sets the shadows Exposure value.
  63542. * 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.
  63543. */
  63544. set: function (value) {
  63545. this._shadowsExposure = value;
  63546. this._dirty = true;
  63547. },
  63548. enumerable: true,
  63549. configurable: true
  63550. });
  63551. ColorCurves.prototype.getClassName = function () {
  63552. return "ColorCurves";
  63553. };
  63554. /**
  63555. * Binds the color curves to the shader.
  63556. * @param colorCurves The color curve to bind
  63557. * @param effect The effect to bind to
  63558. */
  63559. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  63560. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  63561. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  63562. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  63563. if (colorCurves._dirty) {
  63564. colorCurves._dirty = false;
  63565. // Fill in global info.
  63566. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  63567. // Compute highlights info.
  63568. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  63569. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  63570. // Compute midtones info.
  63571. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  63572. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  63573. // Compute shadows info.
  63574. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  63575. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  63576. // Compute deltas (neutral is midtones).
  63577. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  63578. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  63579. }
  63580. if (effect) {
  63581. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  63582. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  63583. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  63584. }
  63585. };
  63586. /**
  63587. * Prepare the list of uniforms associated with the ColorCurves effects.
  63588. * @param uniformsList The list of uniforms used in the effect
  63589. */
  63590. ColorCurves.PrepareUniforms = function (uniformsList) {
  63591. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  63592. };
  63593. /**
  63594. * Returns color grading data based on a hue, density, saturation and exposure value.
  63595. * @param filterHue The hue of the color filter.
  63596. * @param filterDensity The density of the color filter.
  63597. * @param saturation The saturation.
  63598. * @param exposure The exposure.
  63599. * @param result The result data container.
  63600. */
  63601. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  63602. if (hue == null) {
  63603. return;
  63604. }
  63605. hue = ColorCurves.clamp(hue, 0, 360);
  63606. density = ColorCurves.clamp(density, -100, 100);
  63607. saturation = ColorCurves.clamp(saturation, -100, 100);
  63608. exposure = ColorCurves.clamp(exposure, -100, 100);
  63609. // Remap the slider/config filter density with non-linear mapping and also scale by half
  63610. // so that the maximum filter density is only 50% control. This provides fine control
  63611. // for small values and reasonable range.
  63612. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  63613. density *= 0.5;
  63614. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  63615. if (density < 0) {
  63616. density *= -1;
  63617. hue = (hue + 180) % 360;
  63618. }
  63619. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  63620. result.scaleToRef(2, result);
  63621. result.a = 1 + 0.01 * saturation;
  63622. };
  63623. /**
  63624. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  63625. * @param value The input slider value in range [-100,100].
  63626. * @returns Adjusted value.
  63627. */
  63628. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  63629. value /= 100;
  63630. var x = Math.abs(value);
  63631. x = Math.pow(x, 2);
  63632. if (value < 0) {
  63633. x *= -1;
  63634. }
  63635. x *= 100;
  63636. return x;
  63637. };
  63638. /**
  63639. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  63640. * @param hue The hue (H) input.
  63641. * @param saturation The saturation (S) input.
  63642. * @param brightness The brightness (B) input.
  63643. * @result An RGBA color represented as Vector4.
  63644. */
  63645. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  63646. var h = ColorCurves.clamp(hue, 0, 360);
  63647. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  63648. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  63649. if (s === 0) {
  63650. result.r = v;
  63651. result.g = v;
  63652. result.b = v;
  63653. }
  63654. else {
  63655. // sector 0 to 5
  63656. h /= 60;
  63657. var i = Math.floor(h);
  63658. // fractional part of h
  63659. var f = h - i;
  63660. var p = v * (1 - s);
  63661. var q = v * (1 - s * f);
  63662. var t = v * (1 - s * (1 - f));
  63663. switch (i) {
  63664. case 0:
  63665. result.r = v;
  63666. result.g = t;
  63667. result.b = p;
  63668. break;
  63669. case 1:
  63670. result.r = q;
  63671. result.g = v;
  63672. result.b = p;
  63673. break;
  63674. case 2:
  63675. result.r = p;
  63676. result.g = v;
  63677. result.b = t;
  63678. break;
  63679. case 3:
  63680. result.r = p;
  63681. result.g = q;
  63682. result.b = v;
  63683. break;
  63684. case 4:
  63685. result.r = t;
  63686. result.g = p;
  63687. result.b = v;
  63688. break;
  63689. default:// case 5:
  63690. result.r = v;
  63691. result.g = p;
  63692. result.b = q;
  63693. break;
  63694. }
  63695. }
  63696. result.a = 1;
  63697. };
  63698. /**
  63699. * Returns a value clamped between min and max
  63700. * @param value The value to clamp
  63701. * @param min The minimum of value
  63702. * @param max The maximum of value
  63703. * @returns The clamped value.
  63704. */
  63705. ColorCurves.clamp = function (value, min, max) {
  63706. return Math.min(Math.max(value, min), max);
  63707. };
  63708. /**
  63709. * Clones the current color curve instance.
  63710. * @return The cloned curves
  63711. */
  63712. ColorCurves.prototype.clone = function () {
  63713. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  63714. };
  63715. /**
  63716. * Serializes the current color curve instance to a json representation.
  63717. * @return a JSON representation
  63718. */
  63719. ColorCurves.prototype.serialize = function () {
  63720. return BABYLON.SerializationHelper.Serialize(this);
  63721. };
  63722. /**
  63723. * Parses the color curve from a json representation.
  63724. * @param source the JSON source to parse
  63725. * @return The parsed curves
  63726. */
  63727. ColorCurves.Parse = function (source) {
  63728. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  63729. };
  63730. __decorate([
  63731. BABYLON.serialize()
  63732. ], ColorCurves.prototype, "_globalHue", void 0);
  63733. __decorate([
  63734. BABYLON.serialize()
  63735. ], ColorCurves.prototype, "_globalDensity", void 0);
  63736. __decorate([
  63737. BABYLON.serialize()
  63738. ], ColorCurves.prototype, "_globalSaturation", void 0);
  63739. __decorate([
  63740. BABYLON.serialize()
  63741. ], ColorCurves.prototype, "_globalExposure", void 0);
  63742. __decorate([
  63743. BABYLON.serialize()
  63744. ], ColorCurves.prototype, "_highlightsHue", void 0);
  63745. __decorate([
  63746. BABYLON.serialize()
  63747. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  63748. __decorate([
  63749. BABYLON.serialize()
  63750. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  63751. __decorate([
  63752. BABYLON.serialize()
  63753. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  63754. __decorate([
  63755. BABYLON.serialize()
  63756. ], ColorCurves.prototype, "_midtonesHue", void 0);
  63757. __decorate([
  63758. BABYLON.serialize()
  63759. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  63760. __decorate([
  63761. BABYLON.serialize()
  63762. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  63763. __decorate([
  63764. BABYLON.serialize()
  63765. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  63766. return ColorCurves;
  63767. }());
  63768. BABYLON.ColorCurves = ColorCurves;
  63769. })(BABYLON || (BABYLON = {}));
  63770. //# sourceMappingURL=babylon.colorCurves.js.map
  63771. var BABYLON;
  63772. (function (BABYLON) {
  63773. var Octree = (function () {
  63774. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  63775. if (maxDepth === void 0) { maxDepth = 2; }
  63776. this.maxDepth = maxDepth;
  63777. this.dynamicContent = new Array();
  63778. this._maxBlockCapacity = maxBlockCapacity || 64;
  63779. this._selectionContent = new BABYLON.SmartArray(1024);
  63780. this._creationFunc = creationFunc;
  63781. }
  63782. // Methods
  63783. Octree.prototype.update = function (worldMin, worldMax, entries) {
  63784. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  63785. };
  63786. Octree.prototype.addMesh = function (entry) {
  63787. for (var index = 0; index < this.blocks.length; index++) {
  63788. var block = this.blocks[index];
  63789. block.addEntry(entry);
  63790. }
  63791. };
  63792. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  63793. this._selectionContent.reset();
  63794. for (var index = 0; index < this.blocks.length; index++) {
  63795. var block = this.blocks[index];
  63796. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  63797. }
  63798. if (allowDuplicate) {
  63799. this._selectionContent.concat(this.dynamicContent);
  63800. }
  63801. else {
  63802. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63803. }
  63804. return this._selectionContent;
  63805. };
  63806. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  63807. this._selectionContent.reset();
  63808. for (var index = 0; index < this.blocks.length; index++) {
  63809. var block = this.blocks[index];
  63810. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  63811. }
  63812. if (allowDuplicate) {
  63813. this._selectionContent.concat(this.dynamicContent);
  63814. }
  63815. else {
  63816. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63817. }
  63818. return this._selectionContent;
  63819. };
  63820. Octree.prototype.intersectsRay = function (ray) {
  63821. this._selectionContent.reset();
  63822. for (var index = 0; index < this.blocks.length; index++) {
  63823. var block = this.blocks[index];
  63824. block.intersectsRay(ray, this._selectionContent);
  63825. }
  63826. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  63827. return this._selectionContent;
  63828. };
  63829. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  63830. target.blocks = new Array();
  63831. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  63832. // Segmenting space
  63833. for (var x = 0; x < 2; x++) {
  63834. for (var y = 0; y < 2; y++) {
  63835. for (var z = 0; z < 2; z++) {
  63836. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  63837. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  63838. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  63839. block.addEntries(entries);
  63840. target.blocks.push(block);
  63841. }
  63842. }
  63843. }
  63844. };
  63845. Octree.CreationFuncForMeshes = function (entry, block) {
  63846. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  63847. block.entries.push(entry);
  63848. }
  63849. };
  63850. Octree.CreationFuncForSubMeshes = function (entry, block) {
  63851. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  63852. block.entries.push(entry);
  63853. }
  63854. };
  63855. return Octree;
  63856. }());
  63857. BABYLON.Octree = Octree;
  63858. })(BABYLON || (BABYLON = {}));
  63859. //# sourceMappingURL=babylon.octree.js.map
  63860. var BABYLON;
  63861. (function (BABYLON) {
  63862. var OctreeBlock = (function () {
  63863. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  63864. this.entries = new Array();
  63865. this._boundingVectors = new Array();
  63866. this._capacity = capacity;
  63867. this._depth = depth;
  63868. this._maxDepth = maxDepth;
  63869. this._creationFunc = creationFunc;
  63870. this._minPoint = minPoint;
  63871. this._maxPoint = maxPoint;
  63872. this._boundingVectors.push(minPoint.clone());
  63873. this._boundingVectors.push(maxPoint.clone());
  63874. this._boundingVectors.push(minPoint.clone());
  63875. this._boundingVectors[2].x = maxPoint.x;
  63876. this._boundingVectors.push(minPoint.clone());
  63877. this._boundingVectors[3].y = maxPoint.y;
  63878. this._boundingVectors.push(minPoint.clone());
  63879. this._boundingVectors[4].z = maxPoint.z;
  63880. this._boundingVectors.push(maxPoint.clone());
  63881. this._boundingVectors[5].z = minPoint.z;
  63882. this._boundingVectors.push(maxPoint.clone());
  63883. this._boundingVectors[6].x = minPoint.x;
  63884. this._boundingVectors.push(maxPoint.clone());
  63885. this._boundingVectors[7].y = minPoint.y;
  63886. }
  63887. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  63888. // Property
  63889. get: function () {
  63890. return this._capacity;
  63891. },
  63892. enumerable: true,
  63893. configurable: true
  63894. });
  63895. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  63896. get: function () {
  63897. return this._minPoint;
  63898. },
  63899. enumerable: true,
  63900. configurable: true
  63901. });
  63902. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  63903. get: function () {
  63904. return this._maxPoint;
  63905. },
  63906. enumerable: true,
  63907. configurable: true
  63908. });
  63909. // Methods
  63910. OctreeBlock.prototype.addEntry = function (entry) {
  63911. if (this.blocks) {
  63912. for (var index = 0; index < this.blocks.length; index++) {
  63913. var block = this.blocks[index];
  63914. block.addEntry(entry);
  63915. }
  63916. return;
  63917. }
  63918. this._creationFunc(entry, this);
  63919. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  63920. this.createInnerBlocks();
  63921. }
  63922. };
  63923. OctreeBlock.prototype.addEntries = function (entries) {
  63924. for (var index = 0; index < entries.length; index++) {
  63925. var mesh = entries[index];
  63926. this.addEntry(mesh);
  63927. }
  63928. };
  63929. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  63930. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  63931. if (this.blocks) {
  63932. for (var index = 0; index < this.blocks.length; index++) {
  63933. var block = this.blocks[index];
  63934. block.select(frustumPlanes, selection, allowDuplicate);
  63935. }
  63936. return;
  63937. }
  63938. if (allowDuplicate) {
  63939. selection.concat(this.entries);
  63940. }
  63941. else {
  63942. selection.concatWithNoDuplicate(this.entries);
  63943. }
  63944. }
  63945. };
  63946. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  63947. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  63948. if (this.blocks) {
  63949. for (var index = 0; index < this.blocks.length; index++) {
  63950. var block = this.blocks[index];
  63951. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  63952. }
  63953. return;
  63954. }
  63955. if (allowDuplicate) {
  63956. selection.concat(this.entries);
  63957. }
  63958. else {
  63959. selection.concatWithNoDuplicate(this.entries);
  63960. }
  63961. }
  63962. };
  63963. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  63964. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  63965. if (this.blocks) {
  63966. for (var index = 0; index < this.blocks.length; index++) {
  63967. var block = this.blocks[index];
  63968. block.intersectsRay(ray, selection);
  63969. }
  63970. return;
  63971. }
  63972. selection.concatWithNoDuplicate(this.entries);
  63973. }
  63974. };
  63975. OctreeBlock.prototype.createInnerBlocks = function () {
  63976. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  63977. };
  63978. return OctreeBlock;
  63979. }());
  63980. BABYLON.OctreeBlock = OctreeBlock;
  63981. })(BABYLON || (BABYLON = {}));
  63982. //# sourceMappingURL=babylon.octreeBlock.js.map
  63983. var BABYLON;
  63984. (function (BABYLON) {
  63985. var SIMDVector3 = (function () {
  63986. function SIMDVector3() {
  63987. }
  63988. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  63989. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  63990. };
  63991. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  63992. var m = transformation.m;
  63993. var m0 = SIMD.Float32x4.load(m, 0);
  63994. var m1 = SIMD.Float32x4.load(m, 4);
  63995. var m2 = SIMD.Float32x4.load(m, 8);
  63996. var m3 = SIMD.Float32x4.load(m, 12);
  63997. 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));
  63998. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  63999. result.x = SIMD.Float32x4.extractLane(r, 0);
  64000. result.y = SIMD.Float32x4.extractLane(r, 1);
  64001. result.z = SIMD.Float32x4.extractLane(r, 2);
  64002. };
  64003. return SIMDVector3;
  64004. }());
  64005. var SIMDMatrix = (function () {
  64006. function SIMDMatrix() {
  64007. }
  64008. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  64009. var tm = this.m;
  64010. var om = other.m;
  64011. var m0 = SIMD.Float32x4.load(om, 0);
  64012. var m1 = SIMD.Float32x4.load(om, 4);
  64013. var m2 = SIMD.Float32x4.load(om, 8);
  64014. var m3 = SIMD.Float32x4.load(om, 12);
  64015. for (var i = 0; i < 16; i += 4) {
  64016. 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)))));
  64017. }
  64018. return this;
  64019. };
  64020. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  64021. var src = this.m;
  64022. var dest = other.m;
  64023. // Load the 4 rows
  64024. var src0 = SIMD.Float32x4.load(src, 0);
  64025. var src1 = SIMD.Float32x4.load(src, 4);
  64026. var src2 = SIMD.Float32x4.load(src, 8);
  64027. var src3 = SIMD.Float32x4.load(src, 12);
  64028. // Transpose the source matrix. Sort of. Not a true transpose operation
  64029. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  64030. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  64031. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  64032. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  64033. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  64034. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  64035. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  64036. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  64037. // This is a true transposition, but it will lead to an incorrect result
  64038. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  64039. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  64040. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  64041. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  64042. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  64043. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  64044. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  64045. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  64046. // ----
  64047. tmp1 = SIMD.Float32x4.mul(row2, row3);
  64048. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64049. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  64050. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  64051. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64052. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  64053. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  64054. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  64055. // ----
  64056. tmp1 = SIMD.Float32x4.mul(row1, row2);
  64057. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64058. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  64059. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  64060. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64061. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  64062. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  64063. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  64064. // ----
  64065. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  64066. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64067. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  64068. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  64069. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  64070. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64071. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  64072. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  64073. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  64074. // ----
  64075. tmp1 = SIMD.Float32x4.mul(row0, row1);
  64076. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64077. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  64078. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  64079. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64080. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  64081. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  64082. // ----
  64083. tmp1 = SIMD.Float32x4.mul(row0, row3);
  64084. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64085. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  64086. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  64087. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64088. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  64089. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  64090. // ----
  64091. tmp1 = SIMD.Float32x4.mul(row0, row2);
  64092. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64093. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  64094. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  64095. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64096. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  64097. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  64098. // Compute determinant
  64099. var det = SIMD.Float32x4.mul(row0, minor0);
  64100. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  64101. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  64102. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  64103. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  64104. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  64105. // These shuffles aren't necessary if the faulty transposition is done
  64106. // up at the top of this function.
  64107. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  64108. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  64109. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  64110. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  64111. // Compute final values by multiplying with 1/det
  64112. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  64113. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  64114. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  64115. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  64116. return this;
  64117. };
  64118. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  64119. var out = result.m;
  64120. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  64121. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  64122. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  64123. // cc.kmVec3Subtract(f, pCenter, pEye);
  64124. var f = SIMD.Float32x4.sub(center, eye);
  64125. // cc.kmVec3Normalize(f, f);
  64126. var tmp = SIMD.Float32x4.mul(f, f);
  64127. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64128. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64129. // cc.kmVec3Assign(up, pUp);
  64130. // cc.kmVec3Normalize(up, up);
  64131. tmp = SIMD.Float32x4.mul(up, up);
  64132. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64133. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64134. // cc.kmVec3Cross(s, f, up);
  64135. 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)));
  64136. // cc.kmVec3Normalize(s, s);
  64137. tmp = SIMD.Float32x4.mul(s, s);
  64138. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64139. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64140. // cc.kmVec3Cross(u, s, f);
  64141. 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)));
  64142. // cc.kmVec3Normalize(s, s);
  64143. tmp = SIMD.Float32x4.mul(s, s);
  64144. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64145. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64146. var zero = SIMD.Float32x4.splat(0.0);
  64147. s = SIMD.Float32x4.neg(s);
  64148. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  64149. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  64150. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  64151. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  64152. 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);
  64153. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  64154. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  64155. 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)))));
  64156. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  64157. 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)))));
  64158. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  64159. 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)))));
  64160. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  64161. 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)))));
  64162. };
  64163. return SIMDMatrix;
  64164. }());
  64165. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  64166. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  64167. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  64168. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  64169. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  64170. var SIMDHelper = (function () {
  64171. function SIMDHelper() {
  64172. }
  64173. Object.defineProperty(SIMDHelper, "IsEnabled", {
  64174. get: function () {
  64175. return SIMDHelper._isEnabled;
  64176. },
  64177. enumerable: true,
  64178. configurable: true
  64179. });
  64180. SIMDHelper.DisableSIMD = function () {
  64181. // Replace functions
  64182. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  64183. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  64184. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  64185. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  64186. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  64187. SIMDHelper._isEnabled = false;
  64188. };
  64189. SIMDHelper.EnableSIMD = function () {
  64190. if (self.SIMD === undefined) {
  64191. return;
  64192. }
  64193. // check if polyfills needed
  64194. if (!self.Math.fround) {
  64195. self.Math.fround = (function (array) { return function (x) {
  64196. return array[0] = x, array[0];
  64197. }; })(new Float32Array(1));
  64198. }
  64199. if (!self.Math.imul) {
  64200. self.Math.imul = function (a, b) {
  64201. var ah = (a >>> 16) & 0xffff;
  64202. var al = a & 0xffff;
  64203. var bh = (b >>> 16) & 0xffff;
  64204. var bl = b & 0xffff;
  64205. // the shift by 0 fixes the sign on the high part
  64206. // the final |0 converts the unsigned value into a signed value
  64207. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  64208. };
  64209. }
  64210. // Replace functions
  64211. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  64212. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  64213. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  64214. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  64215. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  64216. SIMDHelper._isEnabled = true;
  64217. };
  64218. SIMDHelper._isEnabled = false;
  64219. return SIMDHelper;
  64220. }());
  64221. BABYLON.SIMDHelper = SIMDHelper;
  64222. })(BABYLON || (BABYLON = {}));
  64223. //# sourceMappingURL=babylon.math.SIMD.js.map
  64224. var BABYLON;
  64225. (function (BABYLON) {
  64226. var VRDistortionCorrectionPostProcess = (function (_super) {
  64227. __extends(VRDistortionCorrectionPostProcess, _super);
  64228. //ANY
  64229. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  64230. var _this = _super.call(this, name, "vrDistortionCorrection", [
  64231. 'LensCenter',
  64232. 'Scale',
  64233. 'ScaleIn',
  64234. 'HmdWarpParam'
  64235. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  64236. _this._isRightEye = isRightEye;
  64237. _this._distortionFactors = vrMetrics.distortionK;
  64238. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  64239. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  64240. _this.onSizeChangedObservable.add(function () {
  64241. _this.aspectRatio = _this.width * .5 / _this.height;
  64242. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  64243. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  64244. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  64245. });
  64246. _this.onApplyObservable.add(function (effect) {
  64247. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  64248. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  64249. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  64250. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  64251. });
  64252. return _this;
  64253. }
  64254. return VRDistortionCorrectionPostProcess;
  64255. }(BABYLON.PostProcess));
  64256. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  64257. })(BABYLON || (BABYLON = {}));
  64258. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  64259. var BABYLON;
  64260. (function (BABYLON) {
  64261. var AnaglyphPostProcess = (function (_super) {
  64262. __extends(AnaglyphPostProcess, _super);
  64263. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  64264. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  64265. _this._passedProcess = rigCameras[0]._rigPostProcess;
  64266. _this.onApplyObservable.add(function (effect) {
  64267. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  64268. });
  64269. return _this;
  64270. }
  64271. return AnaglyphPostProcess;
  64272. }(BABYLON.PostProcess));
  64273. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  64274. })(BABYLON || (BABYLON = {}));
  64275. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  64276. var BABYLON;
  64277. (function (BABYLON) {
  64278. var StereoscopicInterlacePostProcess = (function (_super) {
  64279. __extends(StereoscopicInterlacePostProcess, _super);
  64280. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  64281. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  64282. _this._passedProcess = rigCameras[0]._rigPostProcess;
  64283. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  64284. _this.onSizeChangedObservable.add(function () {
  64285. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  64286. });
  64287. _this.onApplyObservable.add(function (effect) {
  64288. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  64289. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  64290. });
  64291. return _this;
  64292. }
  64293. return StereoscopicInterlacePostProcess;
  64294. }(BABYLON.PostProcess));
  64295. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  64296. })(BABYLON || (BABYLON = {}));
  64297. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  64298. var BABYLON;
  64299. (function (BABYLON) {
  64300. var FreeCameraDeviceOrientationInput = (function () {
  64301. function FreeCameraDeviceOrientationInput() {
  64302. var _this = this;
  64303. this._screenOrientationAngle = 0;
  64304. this._screenQuaternion = new BABYLON.Quaternion();
  64305. this._alpha = 0;
  64306. this._beta = 0;
  64307. this._gamma = 0;
  64308. this._orientationChanged = function () {
  64309. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  64310. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  64311. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  64312. };
  64313. this._deviceOrientation = function (evt) {
  64314. _this._alpha = evt.alpha;
  64315. _this._beta = evt.beta;
  64316. _this._gamma = evt.gamma;
  64317. };
  64318. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  64319. this._orientationChanged();
  64320. }
  64321. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  64322. get: function () {
  64323. return this._camera;
  64324. },
  64325. set: function (camera) {
  64326. this._camera = camera;
  64327. if (!this._camera.rotationQuaternion)
  64328. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  64329. },
  64330. enumerable: true,
  64331. configurable: true
  64332. });
  64333. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  64334. window.addEventListener("orientationchange", this._orientationChanged);
  64335. window.addEventListener("deviceorientation", this._deviceOrientation);
  64336. //In certain cases, the attach control is called AFTER orientation was changed,
  64337. //So this is needed.
  64338. this._orientationChanged();
  64339. };
  64340. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  64341. window.removeEventListener("orientationchange", this._orientationChanged);
  64342. window.removeEventListener("deviceorientation", this._deviceOrientation);
  64343. };
  64344. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  64345. //if no device orientation provided, don't update the rotation.
  64346. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  64347. if (!this._alpha)
  64348. return;
  64349. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  64350. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  64351. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  64352. //Mirror on XY Plane
  64353. this._camera.rotationQuaternion.z *= -1;
  64354. this._camera.rotationQuaternion.w *= -1;
  64355. };
  64356. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  64357. return "FreeCameraDeviceOrientationInput";
  64358. };
  64359. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  64360. return "deviceOrientation";
  64361. };
  64362. return FreeCameraDeviceOrientationInput;
  64363. }());
  64364. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  64365. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  64366. })(BABYLON || (BABYLON = {}));
  64367. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  64368. var BABYLON;
  64369. (function (BABYLON) {
  64370. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  64371. function ArcRotateCameraVRDeviceOrientationInput() {
  64372. this.alphaCorrection = 1;
  64373. this.betaCorrection = 1;
  64374. this.gammaCorrection = 1;
  64375. this._alpha = 0;
  64376. this._beta = 0;
  64377. this._gamma = 0;
  64378. this._dirty = false;
  64379. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  64380. }
  64381. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  64382. this.camera.attachControl(element, noPreventDefault);
  64383. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  64384. };
  64385. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  64386. var camera = this.camera;
  64387. this._alpha = +evt.alpha | 0;
  64388. this._beta = +evt.beta | 0;
  64389. this._gamma = +evt.gamma | 0;
  64390. this._dirty = true;
  64391. };
  64392. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  64393. if (this._dirty) {
  64394. this._dirty = false;
  64395. if (this._gamma < 0) {
  64396. this._gamma = 180 + this._gamma;
  64397. }
  64398. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  64399. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  64400. }
  64401. };
  64402. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  64403. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  64404. };
  64405. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  64406. return "ArcRotateCameraVRDeviceOrientationInput";
  64407. };
  64408. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  64409. return "VRDeviceOrientation";
  64410. };
  64411. return ArcRotateCameraVRDeviceOrientationInput;
  64412. }());
  64413. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  64414. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  64415. })(BABYLON || (BABYLON = {}));
  64416. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  64417. var BABYLON;
  64418. (function (BABYLON) {
  64419. var VRCameraMetrics = (function () {
  64420. function VRCameraMetrics() {
  64421. this.compensateDistortion = true;
  64422. }
  64423. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  64424. get: function () {
  64425. return this.hResolution / (2 * this.vResolution);
  64426. },
  64427. enumerable: true,
  64428. configurable: true
  64429. });
  64430. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  64431. get: function () {
  64432. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  64433. },
  64434. enumerable: true,
  64435. configurable: true
  64436. });
  64437. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  64438. get: function () {
  64439. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  64440. var h = (4 * meters) / this.hScreenSize;
  64441. return BABYLON.Matrix.Translation(h, 0, 0);
  64442. },
  64443. enumerable: true,
  64444. configurable: true
  64445. });
  64446. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  64447. get: function () {
  64448. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  64449. var h = (4 * meters) / this.hScreenSize;
  64450. return BABYLON.Matrix.Translation(-h, 0, 0);
  64451. },
  64452. enumerable: true,
  64453. configurable: true
  64454. });
  64455. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  64456. get: function () {
  64457. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  64458. },
  64459. enumerable: true,
  64460. configurable: true
  64461. });
  64462. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  64463. get: function () {
  64464. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  64465. },
  64466. enumerable: true,
  64467. configurable: true
  64468. });
  64469. VRCameraMetrics.GetDefault = function () {
  64470. var result = new VRCameraMetrics();
  64471. result.hResolution = 1280;
  64472. result.vResolution = 800;
  64473. result.hScreenSize = 0.149759993;
  64474. result.vScreenSize = 0.0935999975;
  64475. result.vScreenCenter = 0.0467999987;
  64476. result.eyeToScreenDistance = 0.0410000011;
  64477. result.lensSeparationDistance = 0.0635000020;
  64478. result.interpupillaryDistance = 0.0640000030;
  64479. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  64480. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  64481. result.postProcessScaleFactor = 1.714605507808412;
  64482. result.lensCenterOffset = 0.151976421;
  64483. return result;
  64484. };
  64485. return VRCameraMetrics;
  64486. }());
  64487. BABYLON.VRCameraMetrics = VRCameraMetrics;
  64488. })(BABYLON || (BABYLON = {}));
  64489. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  64490. var BABYLON;
  64491. (function (BABYLON) {
  64492. var WebVRFreeCamera = (function (_super) {
  64493. __extends(WebVRFreeCamera, _super);
  64494. function WebVRFreeCamera(name, position, scene, webVROptions) {
  64495. if (webVROptions === void 0) { webVROptions = {}; }
  64496. var _this = _super.call(this, name, position, scene) || this;
  64497. _this.webVROptions = webVROptions;
  64498. _this._vrDevice = null;
  64499. _this.rawPose = null;
  64500. _this._vrEnabled = false;
  64501. _this._specsVersion = 1.1;
  64502. _this._attached = false;
  64503. _this._positionOffset = BABYLON.Vector3.Zero();
  64504. _this._descendants = [];
  64505. _this.devicePosition = BABYLON.Vector3.Zero();
  64506. _this.deviceScaleFactor = 1;
  64507. _this.controllers = [];
  64508. _this.nonVRControllers = [];
  64509. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  64510. //legacy support - the compensation boolean was removed.
  64511. if (arguments.length === 5) {
  64512. _this.webVROptions = arguments[4];
  64513. }
  64514. // default webVR options
  64515. if (_this.webVROptions.trackPosition == undefined) {
  64516. _this.webVROptions.trackPosition = true;
  64517. }
  64518. if (_this.webVROptions.controllerMeshes == undefined) {
  64519. _this.webVROptions.controllerMeshes = true;
  64520. }
  64521. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  64522. _this.webVROptions.defaultLightningOnControllers = true;
  64523. }
  64524. _this.rotationQuaternion = new BABYLON.Quaternion();
  64525. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64526. if (_this.webVROptions && _this.webVROptions.positionScale) {
  64527. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  64528. }
  64529. //enable VR
  64530. _this.getEngine().initWebVR();
  64531. //check specs version
  64532. if (!window.VRFrameData) {
  64533. _this._specsVersion = 1.0;
  64534. _this._frameData = {};
  64535. }
  64536. else {
  64537. _this._frameData = new VRFrameData();
  64538. }
  64539. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  64540. if (!device) {
  64541. return;
  64542. }
  64543. _this._vrEnabled = true;
  64544. _this._vrDevice = device;
  64545. //reset the rig parameters.
  64546. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  64547. if (_this._attached) {
  64548. _this.getEngine().enableVR(_this._vrDevice);
  64549. }
  64550. });
  64551. // try to attach the controllers, if found.
  64552. _this.initControllers();
  64553. /**
  64554. * The idea behind the following lines:
  64555. * objects that have the camera as parent should actually have the rig cameras as a parent.
  64556. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  64557. * the second will not show it correctly.
  64558. *
  64559. * To solve this - each object that has the camera as parent will be added to a protected array.
  64560. * When the rig camera renders, it will take this array and set all of those to be its children.
  64561. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  64562. * Amazing!
  64563. */
  64564. scene.onBeforeCameraRenderObservable.add(function (camera) {
  64565. if (camera.parent === _this && _this.rigParenting) {
  64566. _this._descendants = _this.getDescendants(true, function (n) {
  64567. // don't take the cameras or the controllers!
  64568. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  64569. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  64570. return !isController && !isRigCamera;
  64571. });
  64572. _this._descendants.forEach(function (node) {
  64573. node.parent = camera;
  64574. });
  64575. }
  64576. });
  64577. scene.onAfterCameraRenderObservable.add(function (camera) {
  64578. if (camera.parent === _this && _this.rigParenting) {
  64579. _this._descendants.forEach(function (node) {
  64580. node.parent = _this;
  64581. });
  64582. }
  64583. });
  64584. return _this;
  64585. }
  64586. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  64587. set: function (callback) {
  64588. this._onControllersAttached = callback;
  64589. // after setting - if the controllers are already set, execute the callback.
  64590. if (this.controllers.length >= 2) {
  64591. callback(this.controllers);
  64592. }
  64593. },
  64594. enumerable: true,
  64595. configurable: true
  64596. });
  64597. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  64598. set: function (callback) {
  64599. this._onNonVRControllerAttached = callback;
  64600. this.nonVRControllers.forEach(function (controller) {
  64601. callback(controller);
  64602. });
  64603. },
  64604. enumerable: true,
  64605. configurable: true
  64606. });
  64607. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  64608. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  64609. var gp = _a[_i];
  64610. if (gp.hand === name) {
  64611. return gp;
  64612. }
  64613. }
  64614. return undefined;
  64615. };
  64616. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  64617. get: function () {
  64618. if (!this._leftController) {
  64619. this._leftController = this.getControllerByName("left");
  64620. }
  64621. return this._leftController;
  64622. },
  64623. enumerable: true,
  64624. configurable: true
  64625. });
  64626. ;
  64627. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  64628. get: function () {
  64629. if (!this._rightController) {
  64630. this._rightController = this.getControllerByName("right");
  64631. }
  64632. return this._rightController;
  64633. },
  64634. enumerable: true,
  64635. configurable: true
  64636. });
  64637. ;
  64638. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  64639. if (length === void 0) { length = 100; }
  64640. if (this.leftCamera) {
  64641. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  64642. }
  64643. else {
  64644. return _super.prototype.getForwardRay.call(this, length);
  64645. }
  64646. };
  64647. WebVRFreeCamera.prototype._checkInputs = function () {
  64648. if (this._vrEnabled) {
  64649. if (this._specsVersion === 1.1) {
  64650. this._vrDevice.getFrameData(this._frameData);
  64651. }
  64652. else {
  64653. //backwards comp
  64654. var pose = this._vrDevice.getPose();
  64655. this._frameData.pose = pose;
  64656. // calculate view and projection matrix
  64657. }
  64658. this.updateFromDevice(this._frameData.pose);
  64659. }
  64660. _super.prototype._checkInputs.call(this);
  64661. };
  64662. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  64663. if (poseData && poseData.orientation) {
  64664. this.rawPose = poseData;
  64665. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  64666. if (this.getScene().useRightHandedSystem) {
  64667. this.deviceRotationQuaternion.z *= -1;
  64668. this.deviceRotationQuaternion.w *= -1;
  64669. }
  64670. if (this.webVROptions.trackPosition && this.rawPose.position) {
  64671. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  64672. if (this.getScene().useRightHandedSystem) {
  64673. this.devicePosition.z *= -1;
  64674. }
  64675. }
  64676. }
  64677. };
  64678. /**
  64679. * WebVR's attach control will start broadcasting frames to the device.
  64680. * Note that in certain browsers (chrome for example) this function must be called
  64681. * within a user-interaction callback. Example:
  64682. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  64683. *
  64684. * @param {HTMLElement} element
  64685. * @param {boolean} [noPreventDefault]
  64686. *
  64687. * @memberOf WebVRFreeCamera
  64688. */
  64689. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  64690. _super.prototype.attachControl.call(this, element, noPreventDefault);
  64691. this._attached = true;
  64692. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  64693. if (this._vrEnabled) {
  64694. this.getEngine().enableVR(this._vrDevice);
  64695. }
  64696. };
  64697. WebVRFreeCamera.prototype.detachControl = function (element) {
  64698. _super.prototype.detachControl.call(this, element);
  64699. this._vrEnabled = false;
  64700. this._attached = false;
  64701. this.getEngine().disableVR();
  64702. };
  64703. WebVRFreeCamera.prototype.getClassName = function () {
  64704. return "WebVRFreeCamera";
  64705. };
  64706. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  64707. //uses the vrDisplay's "resetPose()".
  64708. //pitch and roll won't be affected.
  64709. this._vrDevice.resetPose();
  64710. };
  64711. WebVRFreeCamera.prototype._updateRigCameras = function () {
  64712. var camLeft = this._rigCameras[0];
  64713. var camRight = this._rigCameras[1];
  64714. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64715. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64716. camLeft.position.copyFrom(this.devicePosition);
  64717. camRight.position.copyFrom(this.devicePosition);
  64718. };
  64719. /**
  64720. * This function is called by the two RIG cameras.
  64721. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  64722. */
  64723. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  64724. var _this = this;
  64725. //WebVR 1.0
  64726. if (this._cameraRigParams["specs"] === 1.0) {
  64727. this._updateCameraRotationMatrix();
  64728. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  64729. // Computing target and final matrix
  64730. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  64731. if (this.getScene().useRightHandedSystem) {
  64732. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  64733. }
  64734. else {
  64735. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  64736. }
  64737. //now move the eye in the right direction
  64738. var eyeParams = this._cameraRigParams["eyeParameters"];
  64739. var offset = eyeParams.offset;
  64740. // it will actually always be 0, but just in case
  64741. if (this.getScene().useRightHandedSystem) {
  64742. offset[2] *= -1;
  64743. }
  64744. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  64745. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  64746. }
  64747. else {
  64748. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  64749. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  64750. if (!this.getScene().useRightHandedSystem) {
  64751. [2, 6, 8, 9, 14].forEach(function (num) {
  64752. _this._webvrViewMatrix.m[num] *= -1;
  64753. });
  64754. }
  64755. // update the camera rotation matrix
  64756. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  64757. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  64758. // Computing target and final matrix
  64759. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  64760. }
  64761. var parentCamera = this._cameraRigParams["parentCamera"];
  64762. // should the view matrix be updated with scale and position offset?
  64763. if (parentCamera.deviceScaleFactor !== 1) {
  64764. this._webvrViewMatrix.invert();
  64765. // scale the position, if set
  64766. if (parentCamera.deviceScaleFactor) {
  64767. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  64768. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  64769. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  64770. }
  64771. this._webvrViewMatrix.invert();
  64772. }
  64773. return this._webvrViewMatrix;
  64774. };
  64775. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  64776. var _this = this;
  64777. if (this._cameraRigParams["specs"] === 1.0) {
  64778. var eyeParams = this._cameraRigParams["eyeParameters"];
  64779. // deprecated!!
  64780. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  64781. }
  64782. else {
  64783. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  64784. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  64785. //babylon compatible matrix
  64786. if (!this.getScene().useRightHandedSystem) {
  64787. [8, 9, 10, 11].forEach(function (num) {
  64788. _this._projectionMatrix.m[num] *= -1;
  64789. });
  64790. }
  64791. }
  64792. return this._projectionMatrix;
  64793. };
  64794. WebVRFreeCamera.prototype.initControllers = function () {
  64795. var _this = this;
  64796. this.controllers = [];
  64797. new BABYLON.Gamepads(function (gp) {
  64798. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  64799. var webVrController = gp;
  64800. if (_this.webVROptions.controllerMeshes) {
  64801. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  64802. if (_this.webVROptions.defaultLightningOnControllers) {
  64803. if (!_this._lightOnControllers) {
  64804. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  64805. }
  64806. loadedMesh.getChildren().forEach(function (mesh) {
  64807. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  64808. });
  64809. }
  64810. });
  64811. }
  64812. webVrController.attachToPoseControlledCamera(_this);
  64813. // since this is async - sanity check. Is the controller already stored?
  64814. if (_this.controllers.indexOf(webVrController) === -1) {
  64815. //add to the controllers array
  64816. _this.controllers.push(webVrController);
  64817. //did we find enough controllers? Great! let the developer know.
  64818. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  64819. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  64820. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  64821. // So we're overriding setting left & right manually to be sure
  64822. var firstViveWandDetected = false;
  64823. for (var i = 0; i < _this.controllers.length; i++) {
  64824. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  64825. if (!firstViveWandDetected) {
  64826. firstViveWandDetected = true;
  64827. _this.controllers[i].hand = "left";
  64828. }
  64829. else {
  64830. _this.controllers[i].hand = "right";
  64831. }
  64832. }
  64833. }
  64834. _this._onControllersAttached(_this.controllers);
  64835. }
  64836. }
  64837. }
  64838. else {
  64839. _this.nonVRControllers.push(gp);
  64840. if (_this._onNonVRControllerAttached) {
  64841. _this._onNonVRControllerAttached(gp);
  64842. }
  64843. }
  64844. });
  64845. };
  64846. return WebVRFreeCamera;
  64847. }(BABYLON.FreeCamera));
  64848. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  64849. })(BABYLON || (BABYLON = {}));
  64850. //# sourceMappingURL=babylon.webVRCamera.js.map
  64851. /// <reference path="babylon.freeCamera.ts" />
  64852. var BABYLON;
  64853. (function (BABYLON) {
  64854. // We're mainly based on the logic defined into the FreeCamera code
  64855. var DeviceOrientationCamera = (function (_super) {
  64856. __extends(DeviceOrientationCamera, _super);
  64857. function DeviceOrientationCamera(name, position, scene) {
  64858. var _this = _super.call(this, name, position, scene) || this;
  64859. _this._quaternionCache = new BABYLON.Quaternion();
  64860. _this.inputs.addDeviceOrientation();
  64861. return _this;
  64862. }
  64863. DeviceOrientationCamera.prototype.getClassName = function () {
  64864. return "DeviceOrientationCamera";
  64865. };
  64866. DeviceOrientationCamera.prototype._checkInputs = function () {
  64867. _super.prototype._checkInputs.call(this);
  64868. this._quaternionCache.copyFrom(this.rotationQuaternion);
  64869. if (this._initialQuaternion) {
  64870. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  64871. }
  64872. };
  64873. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  64874. var _this = this;
  64875. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  64876. //can only work if this camera has a rotation quaternion already.
  64877. if (!this.rotationQuaternion)
  64878. return;
  64879. if (!this._initialQuaternion) {
  64880. this._initialQuaternion = new BABYLON.Quaternion();
  64881. }
  64882. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  64883. ['x', 'y', 'z'].forEach(function (axisName) {
  64884. if (!axis[axisName]) {
  64885. _this._initialQuaternion[axisName] = 0;
  64886. }
  64887. else {
  64888. _this._initialQuaternion[axisName] *= -1;
  64889. }
  64890. });
  64891. this._initialQuaternion.normalize();
  64892. //force rotation update
  64893. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  64894. };
  64895. return DeviceOrientationCamera;
  64896. }(BABYLON.FreeCamera));
  64897. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  64898. })(BABYLON || (BABYLON = {}));
  64899. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  64900. var BABYLON;
  64901. (function (BABYLON) {
  64902. var VRDeviceOrientationFreeCamera = (function (_super) {
  64903. __extends(VRDeviceOrientationFreeCamera, _super);
  64904. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  64905. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64906. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64907. var _this = _super.call(this, name, position, scene) || this;
  64908. vrCameraMetrics.compensateDistortion = compensateDistortion;
  64909. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  64910. return _this;
  64911. }
  64912. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  64913. return "VRDeviceOrientationFreeCamera";
  64914. };
  64915. return VRDeviceOrientationFreeCamera;
  64916. }(BABYLON.DeviceOrientationCamera));
  64917. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  64918. var VRDeviceOrientationGamepadCamera = (function (_super) {
  64919. __extends(VRDeviceOrientationGamepadCamera, _super);
  64920. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  64921. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64922. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64923. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  64924. _this.inputs.addGamepad();
  64925. return _this;
  64926. }
  64927. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  64928. return "VRDeviceOrientationGamepadCamera";
  64929. };
  64930. return VRDeviceOrientationGamepadCamera;
  64931. }(VRDeviceOrientationFreeCamera));
  64932. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  64933. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  64934. __extends(VRDeviceOrientationArcRotateCamera, _super);
  64935. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  64936. if (compensateDistortion === void 0) { compensateDistortion = true; }
  64937. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  64938. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  64939. vrCameraMetrics.compensateDistortion = compensateDistortion;
  64940. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  64941. _this.inputs.addVRDeviceOrientation();
  64942. return _this;
  64943. }
  64944. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  64945. return "VRDeviceOrientationArcRotateCamera";
  64946. };
  64947. return VRDeviceOrientationArcRotateCamera;
  64948. }(BABYLON.ArcRotateCamera));
  64949. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  64950. })(BABYLON || (BABYLON = {}));
  64951. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  64952. /// <reference path="babylon.freeCamera.ts" />
  64953. /// <reference path="babylon.arcRotateCamera.ts" />
  64954. /// <reference path="babylon.gamepadCamera.ts" />
  64955. /// <reference path="babylon.universalCamera.ts" />
  64956. var BABYLON;
  64957. (function (BABYLON) {
  64958. var AnaglyphFreeCamera = (function (_super) {
  64959. __extends(AnaglyphFreeCamera, _super);
  64960. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  64961. var _this = _super.call(this, name, position, scene) || this;
  64962. _this.interaxialDistance = interaxialDistance;
  64963. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64964. return _this;
  64965. }
  64966. AnaglyphFreeCamera.prototype.getClassName = function () {
  64967. return "AnaglyphFreeCamera";
  64968. };
  64969. return AnaglyphFreeCamera;
  64970. }(BABYLON.FreeCamera));
  64971. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  64972. var AnaglyphArcRotateCamera = (function (_super) {
  64973. __extends(AnaglyphArcRotateCamera, _super);
  64974. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  64975. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  64976. _this.interaxialDistance = interaxialDistance;
  64977. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64978. return _this;
  64979. }
  64980. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  64981. return "AnaglyphArcRotateCamera";
  64982. };
  64983. return AnaglyphArcRotateCamera;
  64984. }(BABYLON.ArcRotateCamera));
  64985. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  64986. var AnaglyphGamepadCamera = (function (_super) {
  64987. __extends(AnaglyphGamepadCamera, _super);
  64988. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  64989. var _this = _super.call(this, name, position, scene) || this;
  64990. _this.interaxialDistance = interaxialDistance;
  64991. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  64992. return _this;
  64993. }
  64994. AnaglyphGamepadCamera.prototype.getClassName = function () {
  64995. return "AnaglyphGamepadCamera";
  64996. };
  64997. return AnaglyphGamepadCamera;
  64998. }(BABYLON.GamepadCamera));
  64999. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  65000. var AnaglyphUniversalCamera = (function (_super) {
  65001. __extends(AnaglyphUniversalCamera, _super);
  65002. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  65003. var _this = _super.call(this, name, position, scene) || this;
  65004. _this.interaxialDistance = interaxialDistance;
  65005. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65006. return _this;
  65007. }
  65008. AnaglyphUniversalCamera.prototype.getClassName = function () {
  65009. return "AnaglyphUniversalCamera";
  65010. };
  65011. return AnaglyphUniversalCamera;
  65012. }(BABYLON.UniversalCamera));
  65013. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  65014. var StereoscopicFreeCamera = (function (_super) {
  65015. __extends(StereoscopicFreeCamera, _super);
  65016. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65017. var _this = _super.call(this, name, position, scene) || this;
  65018. _this.interaxialDistance = interaxialDistance;
  65019. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65020. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65021. return _this;
  65022. }
  65023. StereoscopicFreeCamera.prototype.getClassName = function () {
  65024. return "StereoscopicFreeCamera";
  65025. };
  65026. return StereoscopicFreeCamera;
  65027. }(BABYLON.FreeCamera));
  65028. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  65029. var StereoscopicArcRotateCamera = (function (_super) {
  65030. __extends(StereoscopicArcRotateCamera, _super);
  65031. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  65032. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65033. _this.interaxialDistance = interaxialDistance;
  65034. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65035. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65036. return _this;
  65037. }
  65038. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  65039. return "StereoscopicArcRotateCamera";
  65040. };
  65041. return StereoscopicArcRotateCamera;
  65042. }(BABYLON.ArcRotateCamera));
  65043. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  65044. var StereoscopicGamepadCamera = (function (_super) {
  65045. __extends(StereoscopicGamepadCamera, _super);
  65046. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65047. var _this = _super.call(this, name, position, scene) || this;
  65048. _this.interaxialDistance = interaxialDistance;
  65049. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65050. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65051. return _this;
  65052. }
  65053. StereoscopicGamepadCamera.prototype.getClassName = function () {
  65054. return "StereoscopicGamepadCamera";
  65055. };
  65056. return StereoscopicGamepadCamera;
  65057. }(BABYLON.GamepadCamera));
  65058. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  65059. var StereoscopicUniversalCamera = (function (_super) {
  65060. __extends(StereoscopicUniversalCamera, _super);
  65061. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65062. var _this = _super.call(this, name, position, scene) || this;
  65063. _this.interaxialDistance = interaxialDistance;
  65064. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65065. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65066. return _this;
  65067. }
  65068. StereoscopicUniversalCamera.prototype.getClassName = function () {
  65069. return "StereoscopicUniversalCamera";
  65070. };
  65071. return StereoscopicUniversalCamera;
  65072. }(BABYLON.UniversalCamera));
  65073. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  65074. })(BABYLON || (BABYLON = {}));
  65075. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  65076. var BABYLON;
  65077. (function (BABYLON) {
  65078. var VRExperienceHelper = (function () {
  65079. function VRExperienceHelper(scene, webVROptions) {
  65080. if (webVROptions === void 0) { webVROptions = {}; }
  65081. var _this = this;
  65082. this.webVROptions = webVROptions;
  65083. this._webVRsupportedAndReady = false;
  65084. this._isInVRMode = false;
  65085. this._scene = scene;
  65086. if (!this._scene.activeCamera) {
  65087. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  65088. }
  65089. else {
  65090. var newCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  65091. if (scene.activeCamera.rotation) {
  65092. newCamera.rotation = scene.activeCamera.rotation.clone();
  65093. }
  65094. this._scene.activeCamera = newCamera;
  65095. }
  65096. this._position = this._scene.activeCamera.position;
  65097. this._canvas = scene.getEngine().getRenderingCanvas();
  65098. this._scene.activeCamera.attachControl(this._canvas);
  65099. this._btnVR = document.createElement("BUTTON");
  65100. this._btnVR.className = "babylonVRicon";
  65101. this._btnVR.id = "babylonVRiconbtn";
  65102. this._btnVR.title = "Click to switch to VR";
  65103. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  65104. var style = document.createElement('style');
  65105. style.appendChild(document.createTextNode(css));
  65106. document.getElementsByTagName('head')[0].appendChild(style);
  65107. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  65108. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  65109. window.addEventListener("resize", function () {
  65110. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  65111. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  65112. });
  65113. // Exiting VR mode using 'ESC' key on desktop
  65114. document.addEventListener("keydown", function (event) {
  65115. if (event.keyCode === 27 && _this._isInVRMode) {
  65116. _this.exitVR();
  65117. }
  65118. });
  65119. // Exiting VR mode double tapping the touch screen
  65120. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  65121. if (_this._isInVRMode) {
  65122. _this.exitVR();
  65123. }
  65124. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  65125. if (navigator.getVRDisplays) {
  65126. navigator.getVRDisplays().then(function (headsets) {
  65127. if (headsets.length > 0) {
  65128. scene.getEngine().initWebVR();
  65129. _this._webVRsupportedAndReady = true;
  65130. }
  65131. document.body.appendChild(_this._btnVR);
  65132. });
  65133. }
  65134. else {
  65135. document.body.appendChild(this._btnVR);
  65136. }
  65137. this._btnVR.addEventListener("click", function () {
  65138. _this.enterVR();
  65139. });
  65140. }
  65141. VRExperienceHelper.prototype.enterVR = function () {
  65142. this._scene.activeCamera.dispose();
  65143. // If WebVR is supported and a headset is connected
  65144. if (this._webVRsupportedAndReady) {
  65145. this._scene.activeCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  65146. }
  65147. else {
  65148. this._scene.activeCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  65149. this._scene.getEngine().switchFullscreen(true);
  65150. }
  65151. this._scene.activeCamera.attachControl(this._canvas);
  65152. this._isInVRMode = true;
  65153. this._btnVR.style.display = "none";
  65154. };
  65155. VRExperienceHelper.prototype.exitVR = function () {
  65156. if (this._webVRsupportedAndReady) {
  65157. this._scene.getEngine().disableVR();
  65158. }
  65159. this._position = this._scene.activeCamera.position;
  65160. this._scene.activeCamera.dispose();
  65161. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, this._scene);
  65162. this._scene.activeCamera.attachControl(this._canvas);
  65163. this._isInVRMode = false;
  65164. this._btnVR.style.display = "";
  65165. };
  65166. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  65167. get: function () {
  65168. return this._position;
  65169. },
  65170. set: function (value) {
  65171. this._position = value;
  65172. this._scene.activeCamera.position = value;
  65173. },
  65174. enumerable: true,
  65175. configurable: true
  65176. });
  65177. VRExperienceHelper.prototype.dispose = function () {
  65178. if (this._isInVRMode) {
  65179. this.exitVR();
  65180. }
  65181. document.body.removeChild(this._btnVR);
  65182. };
  65183. VRExperienceHelper.prototype.getClassName = function () {
  65184. return "VRExperienceHelper";
  65185. };
  65186. return VRExperienceHelper;
  65187. }());
  65188. BABYLON.VRExperienceHelper = VRExperienceHelper;
  65189. })(BABYLON || (BABYLON = {}));
  65190. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  65191. // Mainly based on these 2 articles :
  65192. // 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
  65193. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  65194. var BABYLON;
  65195. (function (BABYLON) {
  65196. var JoystickAxis;
  65197. (function (JoystickAxis) {
  65198. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  65199. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  65200. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  65201. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  65202. var VirtualJoystick = (function () {
  65203. function VirtualJoystick(leftJoystick) {
  65204. var _this = this;
  65205. if (leftJoystick) {
  65206. this._leftJoystick = true;
  65207. }
  65208. else {
  65209. this._leftJoystick = false;
  65210. }
  65211. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  65212. VirtualJoystick._globalJoystickIndex++;
  65213. // By default left & right arrow keys are moving the X
  65214. // and up & down keys are moving the Y
  65215. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  65216. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  65217. this.reverseLeftRight = false;
  65218. this.reverseUpDown = false;
  65219. // collections of pointers
  65220. this._touches = new BABYLON.StringDictionary();
  65221. this.deltaPosition = BABYLON.Vector3.Zero();
  65222. this._joystickSensibility = 25;
  65223. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  65224. this._rotationSpeed = 25;
  65225. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  65226. this._rotateOnAxisRelativeToMesh = false;
  65227. this._onResize = function (evt) {
  65228. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  65229. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  65230. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  65231. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  65232. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  65233. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  65234. };
  65235. // injecting a canvas element on top of the canvas 3D game
  65236. if (!VirtualJoystick.vjCanvas) {
  65237. window.addEventListener("resize", this._onResize, false);
  65238. VirtualJoystick.vjCanvas = document.createElement("canvas");
  65239. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  65240. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  65241. VirtualJoystick.vjCanvas.width = window.innerWidth;
  65242. VirtualJoystick.vjCanvas.height = window.innerHeight;
  65243. VirtualJoystick.vjCanvas.style.width = "100%";
  65244. VirtualJoystick.vjCanvas.style.height = "100%";
  65245. VirtualJoystick.vjCanvas.style.position = "absolute";
  65246. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  65247. VirtualJoystick.vjCanvas.style.top = "0px";
  65248. VirtualJoystick.vjCanvas.style.left = "0px";
  65249. VirtualJoystick.vjCanvas.style.zIndex = "5";
  65250. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  65251. // Support for jQuery PEP polyfill
  65252. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  65253. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  65254. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  65255. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  65256. document.body.appendChild(VirtualJoystick.vjCanvas);
  65257. }
  65258. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  65259. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  65260. this.pressed = false;
  65261. // default joystick color
  65262. this._joystickColor = "cyan";
  65263. this._joystickPointerID = -1;
  65264. // current joystick position
  65265. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  65266. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  65267. // origin joystick position
  65268. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  65269. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  65270. this._onPointerDownHandlerRef = function (evt) {
  65271. _this._onPointerDown(evt);
  65272. };
  65273. this._onPointerMoveHandlerRef = function (evt) {
  65274. _this._onPointerMove(evt);
  65275. };
  65276. this._onPointerOutHandlerRef = function (evt) {
  65277. _this._onPointerUp(evt);
  65278. };
  65279. this._onPointerUpHandlerRef = function (evt) {
  65280. _this._onPointerUp(evt);
  65281. };
  65282. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  65283. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  65284. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  65285. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  65286. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  65287. evt.preventDefault(); // Disables system menu
  65288. }, false);
  65289. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  65290. }
  65291. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  65292. this._joystickSensibility = newJoystickSensibility;
  65293. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  65294. };
  65295. VirtualJoystick.prototype._onPointerDown = function (e) {
  65296. var positionOnScreenCondition;
  65297. e.preventDefault();
  65298. if (this._leftJoystick === true) {
  65299. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  65300. }
  65301. else {
  65302. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  65303. }
  65304. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  65305. // First contact will be dedicated to the virtual joystick
  65306. this._joystickPointerID = e.pointerId;
  65307. this._joystickPointerStartPos.x = e.clientX;
  65308. this._joystickPointerStartPos.y = e.clientY;
  65309. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  65310. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  65311. this._deltaJoystickVector.x = 0;
  65312. this._deltaJoystickVector.y = 0;
  65313. this.pressed = true;
  65314. this._touches.add(e.pointerId.toString(), e);
  65315. }
  65316. else {
  65317. // You can only trigger the action buttons with a joystick declared
  65318. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  65319. this._action();
  65320. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  65321. }
  65322. }
  65323. };
  65324. VirtualJoystick.prototype._onPointerMove = function (e) {
  65325. // If the current pointer is the one associated to the joystick (first touch contact)
  65326. if (this._joystickPointerID == e.pointerId) {
  65327. this._joystickPointerPos.x = e.clientX;
  65328. this._joystickPointerPos.y = e.clientY;
  65329. this._deltaJoystickVector = this._joystickPointerPos.clone();
  65330. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  65331. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  65332. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  65333. switch (this._axisTargetedByLeftAndRight) {
  65334. case JoystickAxis.X:
  65335. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  65336. break;
  65337. case JoystickAxis.Y:
  65338. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  65339. break;
  65340. case JoystickAxis.Z:
  65341. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  65342. break;
  65343. }
  65344. var directionUpDown = this.reverseUpDown ? 1 : -1;
  65345. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  65346. switch (this._axisTargetedByUpAndDown) {
  65347. case JoystickAxis.X:
  65348. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  65349. break;
  65350. case JoystickAxis.Y:
  65351. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  65352. break;
  65353. case JoystickAxis.Z:
  65354. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  65355. break;
  65356. }
  65357. }
  65358. else {
  65359. var data = this._touches.get(e.pointerId.toString());
  65360. if (data) {
  65361. data.x = e.clientX;
  65362. data.y = e.clientY;
  65363. }
  65364. }
  65365. };
  65366. VirtualJoystick.prototype._onPointerUp = function (e) {
  65367. if (this._joystickPointerID == e.pointerId) {
  65368. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  65369. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  65370. this._joystickPointerID = -1;
  65371. this.pressed = false;
  65372. }
  65373. else {
  65374. var touch = this._touches.get(e.pointerId.toString());
  65375. if (touch) {
  65376. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  65377. }
  65378. }
  65379. this._deltaJoystickVector.x = 0;
  65380. this._deltaJoystickVector.y = 0;
  65381. this._touches.remove(e.pointerId.toString());
  65382. };
  65383. /**
  65384. * Change the color of the virtual joystick
  65385. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  65386. */
  65387. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  65388. this._joystickColor = newColor;
  65389. };
  65390. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  65391. this._action = action;
  65392. };
  65393. // Define which axis you'd like to control for left & right
  65394. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  65395. switch (axis) {
  65396. case JoystickAxis.X:
  65397. case JoystickAxis.Y:
  65398. case JoystickAxis.Z:
  65399. this._axisTargetedByLeftAndRight = axis;
  65400. break;
  65401. default:
  65402. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  65403. break;
  65404. }
  65405. };
  65406. // Define which axis you'd like to control for up & down
  65407. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  65408. switch (axis) {
  65409. case JoystickAxis.X:
  65410. case JoystickAxis.Y:
  65411. case JoystickAxis.Z:
  65412. this._axisTargetedByUpAndDown = axis;
  65413. break;
  65414. default:
  65415. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  65416. break;
  65417. }
  65418. };
  65419. VirtualJoystick.prototype._clearCanvas = function () {
  65420. if (this._leftJoystick) {
  65421. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  65422. }
  65423. else {
  65424. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  65425. }
  65426. };
  65427. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  65428. var _this = this;
  65429. if (this.pressed) {
  65430. this._touches.forEach(function (key, touch) {
  65431. if (touch.pointerId === _this._joystickPointerID) {
  65432. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  65433. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  65434. VirtualJoystick.vjCanvasContext.beginPath();
  65435. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  65436. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65437. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  65438. VirtualJoystick.vjCanvasContext.stroke();
  65439. VirtualJoystick.vjCanvasContext.closePath();
  65440. VirtualJoystick.vjCanvasContext.beginPath();
  65441. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65442. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  65443. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  65444. VirtualJoystick.vjCanvasContext.stroke();
  65445. VirtualJoystick.vjCanvasContext.closePath();
  65446. VirtualJoystick.vjCanvasContext.beginPath();
  65447. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65448. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  65449. VirtualJoystick.vjCanvasContext.stroke();
  65450. VirtualJoystick.vjCanvasContext.closePath();
  65451. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  65452. }
  65453. else {
  65454. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  65455. VirtualJoystick.vjCanvasContext.beginPath();
  65456. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  65457. VirtualJoystick.vjCanvasContext.beginPath();
  65458. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  65459. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  65460. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  65461. VirtualJoystick.vjCanvasContext.stroke();
  65462. VirtualJoystick.vjCanvasContext.closePath();
  65463. touch.prevX = touch.x;
  65464. touch.prevY = touch.y;
  65465. }
  65466. ;
  65467. });
  65468. }
  65469. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  65470. };
  65471. VirtualJoystick.prototype.releaseCanvas = function () {
  65472. if (VirtualJoystick.vjCanvas) {
  65473. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  65474. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  65475. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  65476. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  65477. window.removeEventListener("resize", this._onResize);
  65478. document.body.removeChild(VirtualJoystick.vjCanvas);
  65479. VirtualJoystick.vjCanvas = null;
  65480. }
  65481. };
  65482. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  65483. VirtualJoystick._globalJoystickIndex = 0;
  65484. return VirtualJoystick;
  65485. }());
  65486. BABYLON.VirtualJoystick = VirtualJoystick;
  65487. })(BABYLON || (BABYLON = {}));
  65488. //# sourceMappingURL=babylon.virtualJoystick.js.map
  65489. var BABYLON;
  65490. (function (BABYLON) {
  65491. // We're mainly based on the logic defined into the FreeCamera code
  65492. var VirtualJoysticksCamera = (function (_super) {
  65493. __extends(VirtualJoysticksCamera, _super);
  65494. function VirtualJoysticksCamera(name, position, scene) {
  65495. var _this = _super.call(this, name, position, scene) || this;
  65496. _this.inputs.addVirtualJoystick();
  65497. return _this;
  65498. }
  65499. VirtualJoysticksCamera.prototype.getClassName = function () {
  65500. return "VirtualJoysticksCamera";
  65501. };
  65502. return VirtualJoysticksCamera;
  65503. }(BABYLON.FreeCamera));
  65504. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  65505. })(BABYLON || (BABYLON = {}));
  65506. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  65507. var BABYLON;
  65508. (function (BABYLON) {
  65509. var FreeCameraVirtualJoystickInput = (function () {
  65510. function FreeCameraVirtualJoystickInput() {
  65511. }
  65512. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  65513. return this._leftjoystick;
  65514. };
  65515. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  65516. return this._rightjoystick;
  65517. };
  65518. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  65519. if (this._leftjoystick) {
  65520. var camera = this.camera;
  65521. var speed = camera._computeLocalCameraSpeed() * 50;
  65522. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  65523. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  65524. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  65525. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  65526. if (!this._leftjoystick.pressed) {
  65527. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  65528. }
  65529. if (!this._rightjoystick.pressed) {
  65530. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  65531. }
  65532. }
  65533. };
  65534. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  65535. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  65536. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  65537. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  65538. this._leftjoystick.setJoystickSensibility(0.15);
  65539. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  65540. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  65541. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  65542. this._rightjoystick.reverseUpDown = true;
  65543. this._rightjoystick.setJoystickSensibility(0.05);
  65544. this._rightjoystick.setJoystickColor("yellow");
  65545. };
  65546. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  65547. this._leftjoystick.releaseCanvas();
  65548. this._rightjoystick.releaseCanvas();
  65549. };
  65550. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  65551. return "FreeCameraVirtualJoystickInput";
  65552. };
  65553. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  65554. return "virtualJoystick";
  65555. };
  65556. return FreeCameraVirtualJoystickInput;
  65557. }());
  65558. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  65559. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  65560. })(BABYLON || (BABYLON = {}));
  65561. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  65562. var BABYLON;
  65563. (function (BABYLON) {
  65564. var SimplificationSettings = (function () {
  65565. function SimplificationSettings(quality, distance, optimizeMesh) {
  65566. this.quality = quality;
  65567. this.distance = distance;
  65568. this.optimizeMesh = optimizeMesh;
  65569. }
  65570. return SimplificationSettings;
  65571. }());
  65572. BABYLON.SimplificationSettings = SimplificationSettings;
  65573. var SimplificationQueue = (function () {
  65574. function SimplificationQueue() {
  65575. this.running = false;
  65576. this._simplificationArray = [];
  65577. }
  65578. SimplificationQueue.prototype.addTask = function (task) {
  65579. this._simplificationArray.push(task);
  65580. };
  65581. SimplificationQueue.prototype.executeNext = function () {
  65582. var task = this._simplificationArray.pop();
  65583. if (task) {
  65584. this.running = true;
  65585. this.runSimplification(task);
  65586. }
  65587. else {
  65588. this.running = false;
  65589. }
  65590. };
  65591. SimplificationQueue.prototype.runSimplification = function (task) {
  65592. var _this = this;
  65593. if (task.parallelProcessing) {
  65594. //parallel simplifier
  65595. task.settings.forEach(function (setting) {
  65596. var simplifier = _this.getSimplifier(task);
  65597. simplifier.simplify(setting, function (newMesh) {
  65598. task.mesh.addLODLevel(setting.distance, newMesh);
  65599. newMesh.isVisible = true;
  65600. //check if it is the last
  65601. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  65602. //all done, run the success callback.
  65603. task.successCallback();
  65604. }
  65605. _this.executeNext();
  65606. });
  65607. });
  65608. }
  65609. else {
  65610. //single simplifier.
  65611. var simplifier = this.getSimplifier(task);
  65612. var runDecimation = function (setting, callback) {
  65613. simplifier.simplify(setting, function (newMesh) {
  65614. task.mesh.addLODLevel(setting.distance, newMesh);
  65615. newMesh.isVisible = true;
  65616. //run the next quality level
  65617. callback();
  65618. });
  65619. };
  65620. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  65621. runDecimation(task.settings[loop.index], function () {
  65622. loop.executeNext();
  65623. });
  65624. }, function () {
  65625. //execution ended, run the success callback.
  65626. if (task.successCallback) {
  65627. task.successCallback();
  65628. }
  65629. _this.executeNext();
  65630. });
  65631. }
  65632. };
  65633. SimplificationQueue.prototype.getSimplifier = function (task) {
  65634. switch (task.simplificationType) {
  65635. case SimplificationType.QUADRATIC:
  65636. default:
  65637. return new QuadraticErrorSimplification(task.mesh);
  65638. }
  65639. };
  65640. return SimplificationQueue;
  65641. }());
  65642. BABYLON.SimplificationQueue = SimplificationQueue;
  65643. /**
  65644. * The implemented types of simplification.
  65645. * At the moment only Quadratic Error Decimation is implemented.
  65646. */
  65647. var SimplificationType;
  65648. (function (SimplificationType) {
  65649. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  65650. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  65651. var DecimationTriangle = (function () {
  65652. function DecimationTriangle(vertices) {
  65653. this.vertices = vertices;
  65654. this.error = new Array(4);
  65655. this.deleted = false;
  65656. this.isDirty = false;
  65657. this.deletePending = false;
  65658. this.borderFactor = 0;
  65659. }
  65660. return DecimationTriangle;
  65661. }());
  65662. BABYLON.DecimationTriangle = DecimationTriangle;
  65663. var DecimationVertex = (function () {
  65664. function DecimationVertex(position, id) {
  65665. this.position = position;
  65666. this.id = id;
  65667. this.isBorder = true;
  65668. this.q = new QuadraticMatrix();
  65669. this.triangleCount = 0;
  65670. this.triangleStart = 0;
  65671. this.originalOffsets = [];
  65672. }
  65673. DecimationVertex.prototype.updatePosition = function (newPosition) {
  65674. this.position.copyFrom(newPosition);
  65675. };
  65676. return DecimationVertex;
  65677. }());
  65678. BABYLON.DecimationVertex = DecimationVertex;
  65679. var QuadraticMatrix = (function () {
  65680. function QuadraticMatrix(data) {
  65681. this.data = new Array(10);
  65682. for (var i = 0; i < 10; ++i) {
  65683. if (data && data[i]) {
  65684. this.data[i] = data[i];
  65685. }
  65686. else {
  65687. this.data[i] = 0;
  65688. }
  65689. }
  65690. }
  65691. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  65692. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  65693. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  65694. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  65695. return det;
  65696. };
  65697. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  65698. for (var i = 0; i < 10; ++i) {
  65699. this.data[i] += matrix.data[i];
  65700. }
  65701. };
  65702. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  65703. for (var i = 0; i < 10; ++i) {
  65704. this.data[i] += data[i];
  65705. }
  65706. };
  65707. QuadraticMatrix.prototype.add = function (matrix) {
  65708. var m = new QuadraticMatrix();
  65709. for (var i = 0; i < 10; ++i) {
  65710. m.data[i] = this.data[i] + matrix.data[i];
  65711. }
  65712. return m;
  65713. };
  65714. QuadraticMatrix.FromData = function (a, b, c, d) {
  65715. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  65716. };
  65717. //returning an array to avoid garbage collection
  65718. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  65719. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  65720. };
  65721. return QuadraticMatrix;
  65722. }());
  65723. BABYLON.QuadraticMatrix = QuadraticMatrix;
  65724. var Reference = (function () {
  65725. function Reference(vertexId, triangleId) {
  65726. this.vertexId = vertexId;
  65727. this.triangleId = triangleId;
  65728. }
  65729. return Reference;
  65730. }());
  65731. BABYLON.Reference = Reference;
  65732. /**
  65733. * An implementation of the Quadratic Error simplification algorithm.
  65734. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  65735. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  65736. * @author RaananW
  65737. */
  65738. var QuadraticErrorSimplification = (function () {
  65739. function QuadraticErrorSimplification(_mesh) {
  65740. this._mesh = _mesh;
  65741. this.initialized = false;
  65742. this.syncIterations = 5000;
  65743. this.aggressiveness = 7;
  65744. this.decimationIterations = 100;
  65745. this.boundingBoxEpsilon = BABYLON.Epsilon;
  65746. }
  65747. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  65748. var _this = this;
  65749. this.initDecimatedMesh();
  65750. //iterating through the submeshes array, one after the other.
  65751. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  65752. _this.initWithMesh(loop.index, function () {
  65753. _this.runDecimation(settings, loop.index, function () {
  65754. loop.executeNext();
  65755. });
  65756. }, settings.optimizeMesh);
  65757. }, function () {
  65758. setTimeout(function () {
  65759. successCallback(_this._reconstructedMesh);
  65760. }, 0);
  65761. });
  65762. };
  65763. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  65764. var _this = this;
  65765. var gCount = 0;
  65766. triangle.vertices.forEach(function (vertex) {
  65767. var count = 0;
  65768. var vPos = vertex.position;
  65769. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  65770. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  65771. ++count;
  65772. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  65773. ++count;
  65774. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  65775. ++count;
  65776. if (count > 1) {
  65777. ++gCount;
  65778. }
  65779. ;
  65780. });
  65781. if (gCount > 1) {
  65782. console.log(triangle, gCount);
  65783. }
  65784. return gCount > 1;
  65785. };
  65786. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  65787. var _this = this;
  65788. var targetCount = ~~(this.triangles.length * settings.quality);
  65789. var deletedTriangles = 0;
  65790. var triangleCount = this.triangles.length;
  65791. var iterationFunction = function (iteration, callback) {
  65792. setTimeout(function () {
  65793. if (iteration % 5 === 0) {
  65794. _this.updateMesh(iteration === 0);
  65795. }
  65796. for (var i = 0; i < _this.triangles.length; ++i) {
  65797. _this.triangles[i].isDirty = false;
  65798. }
  65799. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  65800. var trianglesIterator = function (i) {
  65801. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  65802. var t = _this.triangles[tIdx];
  65803. if (!t)
  65804. return;
  65805. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  65806. return;
  65807. }
  65808. for (var j = 0; j < 3; ++j) {
  65809. if (t.error[j] < threshold) {
  65810. var deleted0 = [];
  65811. var deleted1 = [];
  65812. var v0 = t.vertices[j];
  65813. var v1 = t.vertices[(j + 1) % 3];
  65814. if (v0.isBorder || v1.isBorder)
  65815. continue;
  65816. var p = BABYLON.Vector3.Zero();
  65817. var n = BABYLON.Vector3.Zero();
  65818. var uv = BABYLON.Vector2.Zero();
  65819. var color = new BABYLON.Color4(0, 0, 0, 1);
  65820. _this.calculateError(v0, v1, p, n, uv, color);
  65821. var delTr = [];
  65822. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  65823. continue;
  65824. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  65825. continue;
  65826. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  65827. continue;
  65828. var uniqueArray = [];
  65829. delTr.forEach(function (deletedT) {
  65830. if (uniqueArray.indexOf(deletedT) === -1) {
  65831. deletedT.deletePending = true;
  65832. uniqueArray.push(deletedT);
  65833. }
  65834. });
  65835. if (uniqueArray.length % 2 !== 0) {
  65836. continue;
  65837. }
  65838. v0.q = v1.q.add(v0.q);
  65839. v0.updatePosition(p);
  65840. var tStart = _this.references.length;
  65841. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  65842. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  65843. var tCount = _this.references.length - tStart;
  65844. if (tCount <= v0.triangleCount) {
  65845. if (tCount) {
  65846. for (var c = 0; c < tCount; c++) {
  65847. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  65848. }
  65849. }
  65850. }
  65851. else {
  65852. v0.triangleStart = tStart;
  65853. }
  65854. v0.triangleCount = tCount;
  65855. break;
  65856. }
  65857. }
  65858. };
  65859. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  65860. }, 0);
  65861. };
  65862. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  65863. if (triangleCount - deletedTriangles <= targetCount)
  65864. loop.breakLoop();
  65865. else {
  65866. iterationFunction(loop.index, function () {
  65867. loop.executeNext();
  65868. });
  65869. }
  65870. }, function () {
  65871. setTimeout(function () {
  65872. //reconstruct this part of the mesh
  65873. _this.reconstructMesh(submeshIndex);
  65874. successCallback();
  65875. }, 0);
  65876. });
  65877. };
  65878. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  65879. var _this = this;
  65880. this.vertices = [];
  65881. this.triangles = [];
  65882. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65883. var indices = this._mesh.getIndices();
  65884. var submesh = this._mesh.subMeshes[submeshIndex];
  65885. var findInVertices = function (positionToSearch) {
  65886. if (optimizeMesh) {
  65887. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  65888. if (_this.vertices[ii].position.equals(positionToSearch)) {
  65889. return _this.vertices[ii];
  65890. }
  65891. }
  65892. }
  65893. return null;
  65894. };
  65895. var vertexReferences = [];
  65896. var vertexInit = function (i) {
  65897. var offset = i + submesh.verticesStart;
  65898. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  65899. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  65900. vertex.originalOffsets.push(offset);
  65901. if (vertex.id === _this.vertices.length) {
  65902. _this.vertices.push(vertex);
  65903. }
  65904. vertexReferences.push(vertex.id);
  65905. };
  65906. //var totalVertices = mesh.getTotalVertices();
  65907. var totalVertices = submesh.verticesCount;
  65908. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  65909. var indicesInit = function (i) {
  65910. var offset = (submesh.indexStart / 3) + i;
  65911. var pos = (offset * 3);
  65912. var i0 = indices[pos + 0];
  65913. var i1 = indices[pos + 1];
  65914. var i2 = indices[pos + 2];
  65915. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  65916. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  65917. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  65918. var triangle = new DecimationTriangle([v0, v1, v2]);
  65919. triangle.originalOffset = pos;
  65920. _this.triangles.push(triangle);
  65921. };
  65922. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  65923. _this.init(callback);
  65924. });
  65925. });
  65926. };
  65927. QuadraticErrorSimplification.prototype.init = function (callback) {
  65928. var _this = this;
  65929. var triangleInit1 = function (i) {
  65930. var t = _this.triangles[i];
  65931. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  65932. for (var j = 0; j < 3; j++) {
  65933. 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))));
  65934. }
  65935. };
  65936. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  65937. var triangleInit2 = function (i) {
  65938. var t = _this.triangles[i];
  65939. for (var j = 0; j < 3; ++j) {
  65940. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  65941. }
  65942. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  65943. };
  65944. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  65945. _this.initialized = true;
  65946. callback();
  65947. });
  65948. });
  65949. };
  65950. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  65951. var newTriangles = [];
  65952. var i;
  65953. for (i = 0; i < this.vertices.length; ++i) {
  65954. this.vertices[i].triangleCount = 0;
  65955. }
  65956. var t;
  65957. var j;
  65958. for (i = 0; i < this.triangles.length; ++i) {
  65959. if (!this.triangles[i].deleted) {
  65960. t = this.triangles[i];
  65961. for (j = 0; j < 3; ++j) {
  65962. t.vertices[j].triangleCount = 1;
  65963. }
  65964. newTriangles.push(t);
  65965. }
  65966. }
  65967. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  65968. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  65969. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  65970. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  65971. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65972. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65973. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65974. var vertexCount = 0;
  65975. for (i = 0; i < this.vertices.length; ++i) {
  65976. var vertex = this.vertices[i];
  65977. vertex.id = vertexCount;
  65978. if (vertex.triangleCount) {
  65979. vertex.originalOffsets.forEach(function (originalOffset) {
  65980. newPositionData.push(vertex.position.x);
  65981. newPositionData.push(vertex.position.y);
  65982. newPositionData.push(vertex.position.z);
  65983. newNormalData.push(normalData[originalOffset * 3]);
  65984. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  65985. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  65986. if (uvs && uvs.length) {
  65987. newUVsData.push(uvs[(originalOffset * 2)]);
  65988. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  65989. }
  65990. else if (colorsData && colorsData.length) {
  65991. newColorsData.push(colorsData[(originalOffset * 4)]);
  65992. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  65993. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  65994. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  65995. }
  65996. ++vertexCount;
  65997. });
  65998. }
  65999. }
  66000. var startingIndex = this._reconstructedMesh.getTotalIndices();
  66001. var startingVertex = this._reconstructedMesh.getTotalVertices();
  66002. var submeshesArray = this._reconstructedMesh.subMeshes;
  66003. this._reconstructedMesh.subMeshes = [];
  66004. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  66005. var originalIndices = this._mesh.getIndices();
  66006. for (i = 0; i < newTriangles.length; ++i) {
  66007. t = newTriangles[i]; //now get the new referencing point for each vertex
  66008. [0, 1, 2].forEach(function (idx) {
  66009. var id = originalIndices[t.originalOffset + idx];
  66010. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  66011. if (offset < 0)
  66012. offset = 0;
  66013. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  66014. });
  66015. }
  66016. //overwriting the old vertex buffers and indices.
  66017. this._reconstructedMesh.setIndices(newIndicesArray);
  66018. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  66019. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  66020. if (newUVsData.length > 0)
  66021. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  66022. if (newColorsData.length > 0)
  66023. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  66024. //create submesh
  66025. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  66026. if (submeshIndex > 0) {
  66027. this._reconstructedMesh.subMeshes = [];
  66028. submeshesArray.forEach(function (submesh) {
  66029. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  66030. });
  66031. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  66032. }
  66033. };
  66034. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  66035. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  66036. this._reconstructedMesh.material = this._mesh.material;
  66037. this._reconstructedMesh.parent = this._mesh.parent;
  66038. this._reconstructedMesh.isVisible = false;
  66039. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  66040. };
  66041. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  66042. for (var i = 0; i < vertex1.triangleCount; ++i) {
  66043. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  66044. if (t.deleted)
  66045. continue;
  66046. var s = this.references[vertex1.triangleStart + i].vertexId;
  66047. var v1 = t.vertices[(s + 1) % 3];
  66048. var v2 = t.vertices[(s + 2) % 3];
  66049. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  66050. deletedArray[i] = true;
  66051. delTr.push(t);
  66052. continue;
  66053. }
  66054. var d1 = v1.position.subtract(point);
  66055. d1 = d1.normalize();
  66056. var d2 = v2.position.subtract(point);
  66057. d2 = d2.normalize();
  66058. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  66059. return true;
  66060. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  66061. deletedArray[i] = false;
  66062. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  66063. return true;
  66064. }
  66065. return false;
  66066. };
  66067. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  66068. var newDeleted = deletedTriangles;
  66069. for (var i = 0; i < vertex.triangleCount; ++i) {
  66070. var ref = this.references[vertex.triangleStart + i];
  66071. var t = this.triangles[ref.triangleId];
  66072. if (t.deleted)
  66073. continue;
  66074. if (deletedArray[i] && t.deletePending) {
  66075. t.deleted = true;
  66076. newDeleted++;
  66077. continue;
  66078. }
  66079. t.vertices[ref.vertexId] = origVertex;
  66080. t.isDirty = true;
  66081. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  66082. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  66083. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  66084. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  66085. this.references.push(ref);
  66086. }
  66087. return newDeleted;
  66088. };
  66089. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  66090. for (var i = 0; i < this.vertices.length; ++i) {
  66091. var vCount = [];
  66092. var vId = [];
  66093. var v = this.vertices[i];
  66094. var j;
  66095. for (j = 0; j < v.triangleCount; ++j) {
  66096. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  66097. for (var ii = 0; ii < 3; ii++) {
  66098. var ofs = 0;
  66099. var vv = triangle.vertices[ii];
  66100. while (ofs < vCount.length) {
  66101. if (vId[ofs] === vv.id)
  66102. break;
  66103. ++ofs;
  66104. }
  66105. if (ofs === vCount.length) {
  66106. vCount.push(1);
  66107. vId.push(vv.id);
  66108. }
  66109. else {
  66110. vCount[ofs]++;
  66111. }
  66112. }
  66113. }
  66114. for (j = 0; j < vCount.length; ++j) {
  66115. if (vCount[j] === 1) {
  66116. this.vertices[vId[j]].isBorder = true;
  66117. }
  66118. else {
  66119. this.vertices[vId[j]].isBorder = false;
  66120. }
  66121. }
  66122. }
  66123. };
  66124. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  66125. if (identifyBorders === void 0) { identifyBorders = false; }
  66126. var i;
  66127. if (!identifyBorders) {
  66128. var newTrianglesVector = [];
  66129. for (i = 0; i < this.triangles.length; ++i) {
  66130. if (!this.triangles[i].deleted) {
  66131. newTrianglesVector.push(this.triangles[i]);
  66132. }
  66133. }
  66134. this.triangles = newTrianglesVector;
  66135. }
  66136. for (i = 0; i < this.vertices.length; ++i) {
  66137. this.vertices[i].triangleCount = 0;
  66138. this.vertices[i].triangleStart = 0;
  66139. }
  66140. var t;
  66141. var j;
  66142. var v;
  66143. for (i = 0; i < this.triangles.length; ++i) {
  66144. t = this.triangles[i];
  66145. for (j = 0; j < 3; ++j) {
  66146. v = t.vertices[j];
  66147. v.triangleCount++;
  66148. }
  66149. }
  66150. var tStart = 0;
  66151. for (i = 0; i < this.vertices.length; ++i) {
  66152. this.vertices[i].triangleStart = tStart;
  66153. tStart += this.vertices[i].triangleCount;
  66154. this.vertices[i].triangleCount = 0;
  66155. }
  66156. var newReferences = new Array(this.triangles.length * 3);
  66157. for (i = 0; i < this.triangles.length; ++i) {
  66158. t = this.triangles[i];
  66159. for (j = 0; j < 3; ++j) {
  66160. v = t.vertices[j];
  66161. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  66162. v.triangleCount++;
  66163. }
  66164. }
  66165. this.references = newReferences;
  66166. if (identifyBorders) {
  66167. this.identifyBorder();
  66168. }
  66169. };
  66170. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  66171. var x = point.x;
  66172. var y = point.y;
  66173. var z = point.z;
  66174. 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
  66175. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  66176. };
  66177. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  66178. var q = vertex1.q.add(vertex2.q);
  66179. var border = vertex1.isBorder && vertex2.isBorder;
  66180. var error = 0;
  66181. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  66182. if (qDet !== 0 && !border) {
  66183. if (!pointResult) {
  66184. pointResult = BABYLON.Vector3.Zero();
  66185. }
  66186. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  66187. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  66188. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  66189. error = this.vertexError(q, pointResult);
  66190. }
  66191. else {
  66192. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  66193. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  66194. var error1 = this.vertexError(q, vertex1.position);
  66195. var error2 = this.vertexError(q, vertex2.position);
  66196. var error3 = this.vertexError(q, p3);
  66197. error = Math.min(error1, error2, error3);
  66198. if (error === error1) {
  66199. if (pointResult) {
  66200. pointResult.copyFrom(vertex1.position);
  66201. }
  66202. }
  66203. else if (error === error2) {
  66204. if (pointResult) {
  66205. pointResult.copyFrom(vertex2.position);
  66206. }
  66207. }
  66208. else {
  66209. if (pointResult) {
  66210. pointResult.copyFrom(p3);
  66211. }
  66212. }
  66213. }
  66214. return error;
  66215. };
  66216. return QuadraticErrorSimplification;
  66217. }());
  66218. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  66219. })(BABYLON || (BABYLON = {}));
  66220. //# sourceMappingURL=babylon.meshSimplification.js.map
  66221. var BABYLON;
  66222. (function (BABYLON) {
  66223. var Internals;
  66224. (function (Internals) {
  66225. var MeshLODLevel = (function () {
  66226. function MeshLODLevel(distance, mesh) {
  66227. this.distance = distance;
  66228. this.mesh = mesh;
  66229. }
  66230. return MeshLODLevel;
  66231. }());
  66232. Internals.MeshLODLevel = MeshLODLevel;
  66233. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66234. })(BABYLON || (BABYLON = {}));
  66235. //# sourceMappingURL=babylon.meshLODLevel.js.map
  66236. var BABYLON;
  66237. (function (BABYLON) {
  66238. // Standard optimizations
  66239. var SceneOptimization = (function () {
  66240. function SceneOptimization(priority) {
  66241. if (priority === void 0) { priority = 0; }
  66242. this.priority = priority;
  66243. this.apply = function (scene) {
  66244. return true; // Return true if everything that can be done was applied
  66245. };
  66246. }
  66247. return SceneOptimization;
  66248. }());
  66249. BABYLON.SceneOptimization = SceneOptimization;
  66250. var TextureOptimization = (function (_super) {
  66251. __extends(TextureOptimization, _super);
  66252. function TextureOptimization(priority, maximumSize) {
  66253. if (priority === void 0) { priority = 0; }
  66254. if (maximumSize === void 0) { maximumSize = 1024; }
  66255. var _this = _super.call(this, priority) || this;
  66256. _this.priority = priority;
  66257. _this.maximumSize = maximumSize;
  66258. _this.apply = function (scene) {
  66259. var allDone = true;
  66260. for (var index = 0; index < scene.textures.length; index++) {
  66261. var texture = scene.textures[index];
  66262. if (!texture.canRescale || texture.getContext) {
  66263. continue;
  66264. }
  66265. var currentSize = texture.getSize();
  66266. var maxDimension = Math.max(currentSize.width, currentSize.height);
  66267. if (maxDimension > _this.maximumSize) {
  66268. texture.scale(0.5);
  66269. allDone = false;
  66270. }
  66271. }
  66272. return allDone;
  66273. };
  66274. return _this;
  66275. }
  66276. return TextureOptimization;
  66277. }(SceneOptimization));
  66278. BABYLON.TextureOptimization = TextureOptimization;
  66279. var HardwareScalingOptimization = (function (_super) {
  66280. __extends(HardwareScalingOptimization, _super);
  66281. function HardwareScalingOptimization(priority, maximumScale) {
  66282. if (priority === void 0) { priority = 0; }
  66283. if (maximumScale === void 0) { maximumScale = 2; }
  66284. var _this = _super.call(this, priority) || this;
  66285. _this.priority = priority;
  66286. _this.maximumScale = maximumScale;
  66287. _this._currentScale = 1;
  66288. _this.apply = function (scene) {
  66289. _this._currentScale++;
  66290. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  66291. return _this._currentScale >= _this.maximumScale;
  66292. };
  66293. return _this;
  66294. }
  66295. return HardwareScalingOptimization;
  66296. }(SceneOptimization));
  66297. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  66298. var ShadowsOptimization = (function (_super) {
  66299. __extends(ShadowsOptimization, _super);
  66300. function ShadowsOptimization() {
  66301. var _this = _super !== null && _super.apply(this, arguments) || this;
  66302. _this.apply = function (scene) {
  66303. scene.shadowsEnabled = false;
  66304. return true;
  66305. };
  66306. return _this;
  66307. }
  66308. return ShadowsOptimization;
  66309. }(SceneOptimization));
  66310. BABYLON.ShadowsOptimization = ShadowsOptimization;
  66311. var PostProcessesOptimization = (function (_super) {
  66312. __extends(PostProcessesOptimization, _super);
  66313. function PostProcessesOptimization() {
  66314. var _this = _super !== null && _super.apply(this, arguments) || this;
  66315. _this.apply = function (scene) {
  66316. scene.postProcessesEnabled = false;
  66317. return true;
  66318. };
  66319. return _this;
  66320. }
  66321. return PostProcessesOptimization;
  66322. }(SceneOptimization));
  66323. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  66324. var LensFlaresOptimization = (function (_super) {
  66325. __extends(LensFlaresOptimization, _super);
  66326. function LensFlaresOptimization() {
  66327. var _this = _super !== null && _super.apply(this, arguments) || this;
  66328. _this.apply = function (scene) {
  66329. scene.lensFlaresEnabled = false;
  66330. return true;
  66331. };
  66332. return _this;
  66333. }
  66334. return LensFlaresOptimization;
  66335. }(SceneOptimization));
  66336. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  66337. var ParticlesOptimization = (function (_super) {
  66338. __extends(ParticlesOptimization, _super);
  66339. function ParticlesOptimization() {
  66340. var _this = _super !== null && _super.apply(this, arguments) || this;
  66341. _this.apply = function (scene) {
  66342. scene.particlesEnabled = false;
  66343. return true;
  66344. };
  66345. return _this;
  66346. }
  66347. return ParticlesOptimization;
  66348. }(SceneOptimization));
  66349. BABYLON.ParticlesOptimization = ParticlesOptimization;
  66350. var RenderTargetsOptimization = (function (_super) {
  66351. __extends(RenderTargetsOptimization, _super);
  66352. function RenderTargetsOptimization() {
  66353. var _this = _super !== null && _super.apply(this, arguments) || this;
  66354. _this.apply = function (scene) {
  66355. scene.renderTargetsEnabled = false;
  66356. return true;
  66357. };
  66358. return _this;
  66359. }
  66360. return RenderTargetsOptimization;
  66361. }(SceneOptimization));
  66362. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  66363. var MergeMeshesOptimization = (function (_super) {
  66364. __extends(MergeMeshesOptimization, _super);
  66365. function MergeMeshesOptimization() {
  66366. var _this = _super !== null && _super.apply(this, arguments) || this;
  66367. _this._canBeMerged = function (abstractMesh) {
  66368. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  66369. return false;
  66370. }
  66371. var mesh = abstractMesh;
  66372. if (!mesh.isVisible || !mesh.isEnabled()) {
  66373. return false;
  66374. }
  66375. if (mesh.instances.length > 0) {
  66376. return false;
  66377. }
  66378. if (mesh.skeleton || mesh.hasLODLevels) {
  66379. return false;
  66380. }
  66381. if (mesh.parent) {
  66382. return false;
  66383. }
  66384. return true;
  66385. };
  66386. _this.apply = function (scene, updateSelectionTree) {
  66387. var globalPool = scene.meshes.slice(0);
  66388. var globalLength = globalPool.length;
  66389. for (var index = 0; index < globalLength; index++) {
  66390. var currentPool = new Array();
  66391. var current = globalPool[index];
  66392. // Checks
  66393. if (!_this._canBeMerged(current)) {
  66394. continue;
  66395. }
  66396. currentPool.push(current);
  66397. // Find compatible meshes
  66398. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  66399. var otherMesh = globalPool[subIndex];
  66400. if (!_this._canBeMerged(otherMesh)) {
  66401. continue;
  66402. }
  66403. if (otherMesh.material !== current.material) {
  66404. continue;
  66405. }
  66406. if (otherMesh.checkCollisions !== current.checkCollisions) {
  66407. continue;
  66408. }
  66409. currentPool.push(otherMesh);
  66410. globalLength--;
  66411. globalPool.splice(subIndex, 1);
  66412. subIndex--;
  66413. }
  66414. if (currentPool.length < 2) {
  66415. continue;
  66416. }
  66417. // Merge meshes
  66418. BABYLON.Mesh.MergeMeshes(currentPool);
  66419. }
  66420. if (updateSelectionTree != undefined) {
  66421. if (updateSelectionTree) {
  66422. scene.createOrUpdateSelectionOctree();
  66423. }
  66424. }
  66425. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  66426. scene.createOrUpdateSelectionOctree();
  66427. }
  66428. return true;
  66429. };
  66430. return _this;
  66431. }
  66432. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  66433. get: function () {
  66434. return MergeMeshesOptimization._UpdateSelectionTree;
  66435. },
  66436. set: function (value) {
  66437. MergeMeshesOptimization._UpdateSelectionTree = value;
  66438. },
  66439. enumerable: true,
  66440. configurable: true
  66441. });
  66442. MergeMeshesOptimization._UpdateSelectionTree = false;
  66443. return MergeMeshesOptimization;
  66444. }(SceneOptimization));
  66445. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  66446. // Options
  66447. var SceneOptimizerOptions = (function () {
  66448. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  66449. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  66450. if (trackerDuration === void 0) { trackerDuration = 2000; }
  66451. this.targetFrameRate = targetFrameRate;
  66452. this.trackerDuration = trackerDuration;
  66453. this.optimizations = new Array();
  66454. }
  66455. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  66456. var result = new SceneOptimizerOptions(targetFrameRate);
  66457. var priority = 0;
  66458. result.optimizations.push(new MergeMeshesOptimization(priority));
  66459. result.optimizations.push(new ShadowsOptimization(priority));
  66460. result.optimizations.push(new LensFlaresOptimization(priority));
  66461. // Next priority
  66462. priority++;
  66463. result.optimizations.push(new PostProcessesOptimization(priority));
  66464. result.optimizations.push(new ParticlesOptimization(priority));
  66465. // Next priority
  66466. priority++;
  66467. result.optimizations.push(new TextureOptimization(priority, 1024));
  66468. return result;
  66469. };
  66470. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  66471. var result = new SceneOptimizerOptions(targetFrameRate);
  66472. var priority = 0;
  66473. result.optimizations.push(new MergeMeshesOptimization(priority));
  66474. result.optimizations.push(new ShadowsOptimization(priority));
  66475. result.optimizations.push(new LensFlaresOptimization(priority));
  66476. // Next priority
  66477. priority++;
  66478. result.optimizations.push(new PostProcessesOptimization(priority));
  66479. result.optimizations.push(new ParticlesOptimization(priority));
  66480. // Next priority
  66481. priority++;
  66482. result.optimizations.push(new TextureOptimization(priority, 512));
  66483. // Next priority
  66484. priority++;
  66485. result.optimizations.push(new RenderTargetsOptimization(priority));
  66486. // Next priority
  66487. priority++;
  66488. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  66489. return result;
  66490. };
  66491. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  66492. var result = new SceneOptimizerOptions(targetFrameRate);
  66493. var priority = 0;
  66494. result.optimizations.push(new MergeMeshesOptimization(priority));
  66495. result.optimizations.push(new ShadowsOptimization(priority));
  66496. result.optimizations.push(new LensFlaresOptimization(priority));
  66497. // Next priority
  66498. priority++;
  66499. result.optimizations.push(new PostProcessesOptimization(priority));
  66500. result.optimizations.push(new ParticlesOptimization(priority));
  66501. // Next priority
  66502. priority++;
  66503. result.optimizations.push(new TextureOptimization(priority, 256));
  66504. // Next priority
  66505. priority++;
  66506. result.optimizations.push(new RenderTargetsOptimization(priority));
  66507. // Next priority
  66508. priority++;
  66509. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  66510. return result;
  66511. };
  66512. return SceneOptimizerOptions;
  66513. }());
  66514. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  66515. // Scene optimizer tool
  66516. var SceneOptimizer = (function () {
  66517. function SceneOptimizer() {
  66518. }
  66519. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  66520. // TODO: add an epsilon
  66521. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  66522. if (onSuccess) {
  66523. onSuccess();
  66524. }
  66525. return;
  66526. }
  66527. // Apply current level of optimizations
  66528. var allDone = true;
  66529. var noOptimizationApplied = true;
  66530. for (var index = 0; index < options.optimizations.length; index++) {
  66531. var optimization = options.optimizations[index];
  66532. if (optimization.priority === currentPriorityLevel) {
  66533. noOptimizationApplied = false;
  66534. allDone = allDone && optimization.apply(scene);
  66535. }
  66536. }
  66537. // If no optimization was applied, this is a failure :(
  66538. if (noOptimizationApplied) {
  66539. if (onFailure) {
  66540. onFailure();
  66541. }
  66542. return;
  66543. }
  66544. // If all optimizations were done, move to next level
  66545. if (allDone) {
  66546. currentPriorityLevel++;
  66547. }
  66548. // Let's the system running for a specific amount of time before checking FPS
  66549. scene.executeWhenReady(function () {
  66550. setTimeout(function () {
  66551. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  66552. }, options.trackerDuration);
  66553. });
  66554. };
  66555. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  66556. if (!options) {
  66557. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  66558. }
  66559. // Let's the system running for a specific amount of time before checking FPS
  66560. scene.executeWhenReady(function () {
  66561. setTimeout(function () {
  66562. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  66563. }, options.trackerDuration);
  66564. });
  66565. };
  66566. return SceneOptimizer;
  66567. }());
  66568. BABYLON.SceneOptimizer = SceneOptimizer;
  66569. })(BABYLON || (BABYLON = {}));
  66570. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  66571. var BABYLON;
  66572. (function (BABYLON) {
  66573. var OutlineRenderer = (function () {
  66574. function OutlineRenderer(scene) {
  66575. this.zOffset = 1;
  66576. this._scene = scene;
  66577. }
  66578. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  66579. var _this = this;
  66580. if (useOverlay === void 0) { useOverlay = false; }
  66581. var scene = this._scene;
  66582. var engine = this._scene.getEngine();
  66583. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66584. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  66585. return;
  66586. }
  66587. var mesh = subMesh.getRenderingMesh();
  66588. var material = subMesh.getMaterial();
  66589. engine.enableEffect(this._effect);
  66590. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  66591. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  66592. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66593. // Bones
  66594. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66595. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66596. }
  66597. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66598. // Alpha test
  66599. if (material && material.needAlphaTesting()) {
  66600. var alphaTexture = material.getAlphaTestTexture();
  66601. if (alphaTexture) {
  66602. this._effect.setTexture("diffuseSampler", alphaTexture);
  66603. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66604. }
  66605. }
  66606. engine.setZOffset(-this.zOffset);
  66607. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  66608. engine.setZOffset(0);
  66609. };
  66610. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  66611. var defines = [];
  66612. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  66613. var mesh = subMesh.getMesh();
  66614. var material = subMesh.getMaterial();
  66615. // Alpha test
  66616. if (material && material.needAlphaTesting()) {
  66617. defines.push("#define ALPHATEST");
  66618. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66619. attribs.push(BABYLON.VertexBuffer.UVKind);
  66620. defines.push("#define UV1");
  66621. }
  66622. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66623. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66624. defines.push("#define UV2");
  66625. }
  66626. }
  66627. // Bones
  66628. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66629. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66630. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66631. if (mesh.numBoneInfluencers > 4) {
  66632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66634. }
  66635. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66636. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66637. }
  66638. else {
  66639. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66640. }
  66641. // Instances
  66642. if (useInstances) {
  66643. defines.push("#define INSTANCES");
  66644. attribs.push("world0");
  66645. attribs.push("world1");
  66646. attribs.push("world2");
  66647. attribs.push("world3");
  66648. }
  66649. // Get correct effect
  66650. var join = defines.join("\n");
  66651. if (this._cachedDefines !== join) {
  66652. this._cachedDefines = join;
  66653. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  66654. }
  66655. return this._effect.isReady();
  66656. };
  66657. return OutlineRenderer;
  66658. }());
  66659. BABYLON.OutlineRenderer = OutlineRenderer;
  66660. })(BABYLON || (BABYLON = {}));
  66661. //# sourceMappingURL=babylon.outlineRenderer.js.map
  66662. var BABYLON;
  66663. (function (BABYLON) {
  66664. var FaceAdjacencies = (function () {
  66665. function FaceAdjacencies() {
  66666. this.edges = new Array();
  66667. this.edgesConnectedCount = 0;
  66668. }
  66669. return FaceAdjacencies;
  66670. }());
  66671. var EdgesRenderer = (function () {
  66672. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  66673. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  66674. if (epsilon === void 0) { epsilon = 0.95; }
  66675. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  66676. this.edgesWidthScalerForOrthographic = 1000.0;
  66677. this.edgesWidthScalerForPerspective = 50.0;
  66678. this._linesPositions = new Array();
  66679. this._linesNormals = new Array();
  66680. this._linesIndices = new Array();
  66681. this._buffers = {};
  66682. this._checkVerticesInsteadOfIndices = false;
  66683. this._source = source;
  66684. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  66685. this._epsilon = epsilon;
  66686. this._prepareRessources();
  66687. this._generateEdgesLines();
  66688. }
  66689. EdgesRenderer.prototype._prepareRessources = function () {
  66690. if (this._lineShader) {
  66691. return;
  66692. }
  66693. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  66694. attributes: ["position", "normal"],
  66695. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  66696. });
  66697. this._lineShader.disableDepthWrite = true;
  66698. this._lineShader.backFaceCulling = false;
  66699. };
  66700. EdgesRenderer.prototype.dispose = function () {
  66701. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  66702. if (buffer) {
  66703. buffer.dispose();
  66704. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  66705. }
  66706. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  66707. if (buffer) {
  66708. buffer.dispose();
  66709. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  66710. }
  66711. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  66712. this._lineShader.dispose();
  66713. };
  66714. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  66715. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  66716. return 0;
  66717. }
  66718. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  66719. return 1;
  66720. }
  66721. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  66722. return 2;
  66723. }
  66724. return -1;
  66725. };
  66726. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  66727. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  66728. return 0;
  66729. }
  66730. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  66731. return 1;
  66732. }
  66733. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  66734. return 2;
  66735. }
  66736. return -1;
  66737. };
  66738. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  66739. var needToCreateLine;
  66740. if (edge === undefined) {
  66741. needToCreateLine = true;
  66742. }
  66743. else {
  66744. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  66745. needToCreateLine = dotProduct < this._epsilon;
  66746. }
  66747. if (needToCreateLine) {
  66748. var offset = this._linesPositions.length / 3;
  66749. var normal = p0.subtract(p1);
  66750. normal.normalize();
  66751. // Positions
  66752. this._linesPositions.push(p0.x);
  66753. this._linesPositions.push(p0.y);
  66754. this._linesPositions.push(p0.z);
  66755. this._linesPositions.push(p0.x);
  66756. this._linesPositions.push(p0.y);
  66757. this._linesPositions.push(p0.z);
  66758. this._linesPositions.push(p1.x);
  66759. this._linesPositions.push(p1.y);
  66760. this._linesPositions.push(p1.z);
  66761. this._linesPositions.push(p1.x);
  66762. this._linesPositions.push(p1.y);
  66763. this._linesPositions.push(p1.z);
  66764. // Normals
  66765. this._linesNormals.push(p1.x);
  66766. this._linesNormals.push(p1.y);
  66767. this._linesNormals.push(p1.z);
  66768. this._linesNormals.push(-1);
  66769. this._linesNormals.push(p1.x);
  66770. this._linesNormals.push(p1.y);
  66771. this._linesNormals.push(p1.z);
  66772. this._linesNormals.push(1);
  66773. this._linesNormals.push(p0.x);
  66774. this._linesNormals.push(p0.y);
  66775. this._linesNormals.push(p0.z);
  66776. this._linesNormals.push(-1);
  66777. this._linesNormals.push(p0.x);
  66778. this._linesNormals.push(p0.y);
  66779. this._linesNormals.push(p0.z);
  66780. this._linesNormals.push(1);
  66781. // Indices
  66782. this._linesIndices.push(offset);
  66783. this._linesIndices.push(offset + 1);
  66784. this._linesIndices.push(offset + 2);
  66785. this._linesIndices.push(offset);
  66786. this._linesIndices.push(offset + 2);
  66787. this._linesIndices.push(offset + 3);
  66788. }
  66789. };
  66790. EdgesRenderer.prototype._generateEdgesLines = function () {
  66791. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66792. var indices = this._source.getIndices();
  66793. // First let's find adjacencies
  66794. var adjacencies = new Array();
  66795. var faceNormals = new Array();
  66796. var index;
  66797. var faceAdjacencies;
  66798. // Prepare faces
  66799. for (index = 0; index < indices.length; index += 3) {
  66800. faceAdjacencies = new FaceAdjacencies();
  66801. var p0Index = indices[index];
  66802. var p1Index = indices[index + 1];
  66803. var p2Index = indices[index + 2];
  66804. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  66805. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  66806. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  66807. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  66808. faceNormal.normalize();
  66809. faceNormals.push(faceNormal);
  66810. adjacencies.push(faceAdjacencies);
  66811. }
  66812. // Scan
  66813. for (index = 0; index < adjacencies.length; index++) {
  66814. faceAdjacencies = adjacencies[index];
  66815. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  66816. var otherFaceAdjacencies = adjacencies[otherIndex];
  66817. if (faceAdjacencies.edgesConnectedCount === 3) {
  66818. break;
  66819. }
  66820. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  66821. continue;
  66822. }
  66823. var otherP0 = indices[otherIndex * 3];
  66824. var otherP1 = indices[otherIndex * 3 + 1];
  66825. var otherP2 = indices[otherIndex * 3 + 2];
  66826. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  66827. var otherEdgeIndex;
  66828. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  66829. continue;
  66830. }
  66831. switch (edgeIndex) {
  66832. case 0:
  66833. if (this._checkVerticesInsteadOfIndices) {
  66834. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66835. }
  66836. else {
  66837. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  66838. }
  66839. break;
  66840. case 1:
  66841. if (this._checkVerticesInsteadOfIndices) {
  66842. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66843. }
  66844. else {
  66845. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  66846. }
  66847. break;
  66848. case 2:
  66849. if (this._checkVerticesInsteadOfIndices) {
  66850. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  66851. }
  66852. else {
  66853. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  66854. }
  66855. break;
  66856. }
  66857. if (otherEdgeIndex === -1) {
  66858. continue;
  66859. }
  66860. faceAdjacencies.edges[edgeIndex] = otherIndex;
  66861. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  66862. faceAdjacencies.edgesConnectedCount++;
  66863. otherFaceAdjacencies.edgesConnectedCount++;
  66864. if (faceAdjacencies.edgesConnectedCount === 3) {
  66865. break;
  66866. }
  66867. }
  66868. }
  66869. }
  66870. // Create lines
  66871. for (index = 0; index < adjacencies.length; index++) {
  66872. // 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
  66873. var current = adjacencies[index];
  66874. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  66875. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  66876. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  66877. }
  66878. // Merge into a single mesh
  66879. var engine = this._source.getScene().getEngine();
  66880. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  66881. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  66882. this._ib = engine.createIndexBuffer(this._linesIndices);
  66883. this._indicesCount = this._linesIndices.length;
  66884. };
  66885. EdgesRenderer.prototype.render = function () {
  66886. if (!this._lineShader.isReady()) {
  66887. return;
  66888. }
  66889. var scene = this._source.getScene();
  66890. var engine = scene.getEngine();
  66891. this._lineShader._preBind();
  66892. // VBOs
  66893. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  66894. scene.resetCachedMaterial();
  66895. this._lineShader.setColor4("color", this._source.edgesColor);
  66896. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  66897. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  66898. }
  66899. else {
  66900. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  66901. }
  66902. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  66903. this._lineShader.bind(this._source.getWorldMatrix());
  66904. // Draw order
  66905. engine.draw(true, 0, this._indicesCount);
  66906. this._lineShader.unbind();
  66907. engine.setDepthWrite(true);
  66908. };
  66909. return EdgesRenderer;
  66910. }());
  66911. BABYLON.EdgesRenderer = EdgesRenderer;
  66912. })(BABYLON || (BABYLON = {}));
  66913. //# sourceMappingURL=babylon.edgesRenderer.js.map
  66914. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  66915. /// <reference path="..\Math\babylon.math.ts" />
  66916. var BABYLON;
  66917. (function (BABYLON) {
  66918. /**
  66919. * Special Glow Blur post process only blurring the alpha channel
  66920. * It enforces keeping the most luminous color in the color channel.
  66921. */
  66922. var GlowBlurPostProcess = (function (_super) {
  66923. __extends(GlowBlurPostProcess, _super);
  66924. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  66925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66926. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  66927. _this.direction = direction;
  66928. _this.kernel = kernel;
  66929. _this.onApplyObservable.add(function (effect) {
  66930. effect.setFloat2("screenSize", _this.width, _this.height);
  66931. effect.setVector2("direction", _this.direction);
  66932. effect.setFloat("blurWidth", _this.kernel);
  66933. });
  66934. return _this;
  66935. }
  66936. return GlowBlurPostProcess;
  66937. }(BABYLON.PostProcess));
  66938. /**
  66939. * The highlight layer Helps adding a glow effect around a mesh.
  66940. *
  66941. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  66942. * glowy meshes to your scene.
  66943. *
  66944. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  66945. */
  66946. var HighlightLayer = (function () {
  66947. /**
  66948. * Instantiates a new highlight Layer and references it to the scene..
  66949. * @param name The name of the layer
  66950. * @param scene The scene to use the layer in
  66951. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  66952. */
  66953. function HighlightLayer(name, scene, options) {
  66954. this.name = name;
  66955. this._vertexBuffers = {};
  66956. this._mainTextureDesiredSize = { width: 0, height: 0 };
  66957. this._meshes = {};
  66958. this._maxSize = 0;
  66959. this._shouldRender = false;
  66960. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  66961. this._excludedMeshes = {};
  66962. /**
  66963. * Specifies whether or not the inner glow is ACTIVE in the layer.
  66964. */
  66965. this.innerGlow = true;
  66966. /**
  66967. * Specifies whether or not the outer glow is ACTIVE in the layer.
  66968. */
  66969. this.outerGlow = true;
  66970. /**
  66971. * Specifies wether the highlight layer is enabled or not.
  66972. */
  66973. this.isEnabled = true;
  66974. /**
  66975. * An event triggered when the highlight layer has been disposed.
  66976. * @type {BABYLON.Observable}
  66977. */
  66978. this.onDisposeObservable = new BABYLON.Observable();
  66979. /**
  66980. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  66981. * @type {BABYLON.Observable}
  66982. */
  66983. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  66984. /**
  66985. * An event triggered when the highlight layer is being blurred.
  66986. * @type {BABYLON.Observable}
  66987. */
  66988. this.onBeforeBlurObservable = new BABYLON.Observable();
  66989. /**
  66990. * An event triggered when the highlight layer has been blurred.
  66991. * @type {BABYLON.Observable}
  66992. */
  66993. this.onAfterBlurObservable = new BABYLON.Observable();
  66994. /**
  66995. * An event triggered when the glowing blurred texture is being merged in the scene.
  66996. * @type {BABYLON.Observable}
  66997. */
  66998. this.onBeforeComposeObservable = new BABYLON.Observable();
  66999. /**
  67000. * An event triggered when the glowing blurred texture has been merged in the scene.
  67001. * @type {BABYLON.Observable}
  67002. */
  67003. this.onAfterComposeObservable = new BABYLON.Observable();
  67004. /**
  67005. * An event triggered when the highlight layer changes its size.
  67006. * @type {BABYLON.Observable}
  67007. */
  67008. this.onSizeChangedObservable = new BABYLON.Observable();
  67009. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67010. var engine = scene.getEngine();
  67011. this._engine = engine;
  67012. this._maxSize = this._engine.getCaps().maxTextureSize;
  67013. this._scene.highlightLayers.push(this);
  67014. // Warn on stencil.
  67015. if (!this._engine.isStencilEnable) {
  67016. 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 }");
  67017. }
  67018. // Adapt options
  67019. this._options = options || {
  67020. mainTextureRatio: 0.5,
  67021. blurTextureSizeRatio: 0.5,
  67022. blurHorizontalSize: 1.0,
  67023. blurVerticalSize: 1.0,
  67024. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  67025. };
  67026. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  67027. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  67028. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  67029. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  67030. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  67031. // VBO
  67032. var vertices = [];
  67033. vertices.push(1, 1);
  67034. vertices.push(-1, 1);
  67035. vertices.push(-1, -1);
  67036. vertices.push(1, -1);
  67037. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67038. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  67039. // Indices
  67040. var indices = [];
  67041. indices.push(0);
  67042. indices.push(1);
  67043. indices.push(2);
  67044. indices.push(0);
  67045. indices.push(2);
  67046. indices.push(3);
  67047. this._indexBuffer = engine.createIndexBuffer(indices);
  67048. // Effect
  67049. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  67050. // Render target
  67051. this.setMainTextureSize();
  67052. // Create Textures and post processes
  67053. this.createTextureAndPostProcesses();
  67054. }
  67055. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  67056. /**
  67057. * Gets the horizontal size of the blur.
  67058. */
  67059. get: function () {
  67060. return this._horizontalBlurPostprocess.kernel;
  67061. },
  67062. /**
  67063. * Specifies the horizontal size of the blur.
  67064. */
  67065. set: function (value) {
  67066. this._horizontalBlurPostprocess.kernel = value;
  67067. },
  67068. enumerable: true,
  67069. configurable: true
  67070. });
  67071. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  67072. /**
  67073. * Gets the vertical size of the blur.
  67074. */
  67075. get: function () {
  67076. return this._verticalBlurPostprocess.kernel;
  67077. },
  67078. /**
  67079. * Specifies the vertical size of the blur.
  67080. */
  67081. set: function (value) {
  67082. this._verticalBlurPostprocess.kernel = value;
  67083. },
  67084. enumerable: true,
  67085. configurable: true
  67086. });
  67087. Object.defineProperty(HighlightLayer.prototype, "camera", {
  67088. /**
  67089. * Gets the camera attached to the layer.
  67090. */
  67091. get: function () {
  67092. return this._options.camera;
  67093. },
  67094. enumerable: true,
  67095. configurable: true
  67096. });
  67097. /**
  67098. * Creates the render target textures and post processes used in the highlight layer.
  67099. */
  67100. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  67101. var _this = this;
  67102. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  67103. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  67104. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  67105. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  67106. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  67107. width: this._mainTextureDesiredSize.width,
  67108. height: this._mainTextureDesiredSize.height
  67109. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67110. this._mainTexture.activeCamera = this._options.camera;
  67111. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67112. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67113. this._mainTexture.anisotropicFilteringLevel = 1;
  67114. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67115. this._mainTexture.renderParticles = false;
  67116. this._mainTexture.renderList = null;
  67117. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  67118. width: blurTextureWidth,
  67119. height: blurTextureHeight
  67120. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67121. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67122. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67123. this._blurTexture.anisotropicFilteringLevel = 16;
  67124. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67125. this._blurTexture.renderParticles = false;
  67126. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67127. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  67128. effect.setTexture("textureSampler", _this._mainTexture);
  67129. });
  67130. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  67131. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67132. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  67133. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67134. });
  67135. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67136. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  67137. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67138. });
  67139. }
  67140. else {
  67141. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67142. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  67143. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67144. });
  67145. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67146. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  67147. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67148. });
  67149. }
  67150. this._mainTexture.onAfterUnbindObservable.add(function () {
  67151. _this.onBeforeBlurObservable.notifyObservers(_this);
  67152. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  67153. _this.onAfterBlurObservable.notifyObservers(_this);
  67154. });
  67155. // Custom render function
  67156. var renderSubMesh = function (subMesh) {
  67157. var mesh = subMesh.getRenderingMesh();
  67158. var scene = _this._scene;
  67159. var engine = scene.getEngine();
  67160. // Culling
  67161. engine.setState(subMesh.getMaterial().backFaceCulling);
  67162. // Managing instances
  67163. var batch = mesh._getInstancesRenderList(subMesh._id);
  67164. if (batch.mustReturn) {
  67165. return;
  67166. }
  67167. // Excluded Mesh
  67168. if (_this._excludedMeshes[mesh.uniqueId]) {
  67169. return;
  67170. }
  67171. ;
  67172. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67173. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  67174. var material = subMesh.getMaterial();
  67175. var emissiveTexture = null;
  67176. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  67177. emissiveTexture = material.emissiveTexture;
  67178. }
  67179. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  67180. engine.enableEffect(_this._glowMapGenerationEffect);
  67181. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  67182. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  67183. if (highlightLayerMesh) {
  67184. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  67185. }
  67186. else {
  67187. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  67188. }
  67189. // Alpha test
  67190. if (material && material.needAlphaTesting()) {
  67191. var alphaTexture = material.getAlphaTestTexture();
  67192. if (alphaTexture) {
  67193. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  67194. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67195. }
  67196. }
  67197. // Glow emissive only
  67198. if (emissiveTexture) {
  67199. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  67200. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  67201. }
  67202. // Bones
  67203. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67204. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67205. }
  67206. // Draw
  67207. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  67208. }
  67209. else {
  67210. // Need to reset refresh rate of the shadowMap
  67211. _this._mainTexture.resetRefreshCounter();
  67212. }
  67213. };
  67214. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  67215. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  67216. var index;
  67217. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67218. renderSubMesh(opaqueSubMeshes.data[index]);
  67219. }
  67220. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67221. renderSubMesh(alphaTestSubMeshes.data[index]);
  67222. }
  67223. for (index = 0; index < transparentSubMeshes.length; index++) {
  67224. renderSubMesh(transparentSubMeshes.data[index]);
  67225. }
  67226. };
  67227. this._mainTexture.onClearObservable.add(function (engine) {
  67228. engine.clear(HighlightLayer.neutralColor, true, true, true);
  67229. });
  67230. };
  67231. /**
  67232. * Checks for the readiness of the element composing the layer.
  67233. * @param subMesh the mesh to check for
  67234. * @param useInstances specify wether or not to use instances to render the mesh
  67235. * @param emissiveTexture the associated emissive texture used to generate the glow
  67236. * @return true if ready otherwise, false
  67237. */
  67238. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  67239. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  67240. return false;
  67241. }
  67242. var defines = [];
  67243. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67244. var mesh = subMesh.getMesh();
  67245. var material = subMesh.getMaterial();
  67246. var uv1 = false;
  67247. var uv2 = false;
  67248. // Alpha test
  67249. if (material && material.needAlphaTesting()) {
  67250. var alphaTexture = material.getAlphaTestTexture();
  67251. if (alphaTexture) {
  67252. defines.push("#define ALPHATEST");
  67253. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  67254. alphaTexture.coordinatesIndex === 1) {
  67255. defines.push("#define DIFFUSEUV2");
  67256. uv2 = true;
  67257. }
  67258. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67259. defines.push("#define DIFFUSEUV1");
  67260. uv1 = true;
  67261. }
  67262. }
  67263. }
  67264. // Emissive
  67265. if (emissiveTexture) {
  67266. defines.push("#define EMISSIVE");
  67267. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  67268. emissiveTexture.coordinatesIndex === 1) {
  67269. defines.push("#define EMISSIVEUV2");
  67270. uv2 = true;
  67271. }
  67272. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67273. defines.push("#define EMISSIVEUV1");
  67274. uv1 = true;
  67275. }
  67276. }
  67277. if (uv1) {
  67278. attribs.push(BABYLON.VertexBuffer.UVKind);
  67279. defines.push("#define UV1");
  67280. }
  67281. if (uv2) {
  67282. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67283. defines.push("#define UV2");
  67284. }
  67285. // Bones
  67286. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67287. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67288. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67289. if (mesh.numBoneInfluencers > 4) {
  67290. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67291. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67292. }
  67293. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67294. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67295. }
  67296. else {
  67297. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67298. }
  67299. // Instances
  67300. if (useInstances) {
  67301. defines.push("#define INSTANCES");
  67302. attribs.push("world0");
  67303. attribs.push("world1");
  67304. attribs.push("world2");
  67305. attribs.push("world3");
  67306. }
  67307. // Get correct effect
  67308. var join = defines.join("\n");
  67309. if (this._cachedDefines !== join) {
  67310. this._cachedDefines = join;
  67311. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  67312. }
  67313. return this._glowMapGenerationEffect.isReady();
  67314. };
  67315. /**
  67316. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  67317. */
  67318. HighlightLayer.prototype.render = function () {
  67319. var currentEffect = this._glowMapMergeEffect;
  67320. // Check
  67321. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  67322. return;
  67323. var engine = this._scene.getEngine();
  67324. this.onBeforeComposeObservable.notifyObservers(this);
  67325. // Render
  67326. engine.enableEffect(currentEffect);
  67327. engine.setState(false);
  67328. // Cache
  67329. var previousStencilBuffer = engine.getStencilBuffer();
  67330. var previousStencilFunction = engine.getStencilFunction();
  67331. var previousStencilMask = engine.getStencilMask();
  67332. var previousStencilOperationPass = engine.getStencilOperationPass();
  67333. var previousStencilOperationFail = engine.getStencilOperationFail();
  67334. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  67335. var previousAlphaMode = engine.getAlphaMode();
  67336. // Texture
  67337. currentEffect.setTexture("textureSampler", this._blurTexture);
  67338. // VBOs
  67339. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  67340. // Stencil operations
  67341. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  67342. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  67343. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  67344. // Draw order
  67345. engine.setAlphaMode(this._options.alphaBlendingMode);
  67346. engine.setStencilMask(0x00);
  67347. engine.setStencilBuffer(true);
  67348. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  67349. if (this.outerGlow) {
  67350. currentEffect.setFloat("offset", 0);
  67351. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  67352. engine.draw(true, 0, 6);
  67353. }
  67354. if (this.innerGlow) {
  67355. currentEffect.setFloat("offset", 1);
  67356. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  67357. engine.draw(true, 0, 6);
  67358. }
  67359. // Restore Cache
  67360. engine.setStencilFunction(previousStencilFunction);
  67361. engine.setStencilMask(previousStencilMask);
  67362. engine.setAlphaMode(previousAlphaMode);
  67363. engine.setStencilBuffer(previousStencilBuffer);
  67364. engine.setStencilOperationPass(previousStencilOperationPass);
  67365. engine.setStencilOperationFail(previousStencilOperationFail);
  67366. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  67367. engine._stencilState.reset();
  67368. this.onAfterComposeObservable.notifyObservers(this);
  67369. // Handle size changes.
  67370. var size = this._mainTexture.getSize();
  67371. this.setMainTextureSize();
  67372. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  67373. // Recreate RTT and post processes on size change.
  67374. this.onSizeChangedObservable.notifyObservers(this);
  67375. this.disposeTextureAndPostProcesses();
  67376. this.createTextureAndPostProcesses();
  67377. }
  67378. };
  67379. /**
  67380. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  67381. * @param mesh The mesh to exclude from the highlight layer
  67382. */
  67383. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  67384. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  67385. if (!meshExcluded) {
  67386. this._excludedMeshes[mesh.uniqueId] = {
  67387. mesh: mesh,
  67388. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  67389. mesh.getEngine().setStencilBuffer(false);
  67390. }),
  67391. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  67392. mesh.getEngine().setStencilBuffer(true);
  67393. }),
  67394. };
  67395. }
  67396. };
  67397. /**
  67398. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  67399. * @param mesh The mesh to highlight
  67400. */
  67401. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  67402. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  67403. if (meshExcluded) {
  67404. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  67405. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  67406. }
  67407. this._excludedMeshes[mesh.uniqueId] = undefined;
  67408. };
  67409. /**
  67410. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  67411. * @param mesh The mesh to highlight
  67412. * @param color The color of the highlight
  67413. * @param glowEmissiveOnly Extract the glow from the emissive texture
  67414. */
  67415. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  67416. var _this = this;
  67417. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  67418. var meshHighlight = this._meshes[mesh.uniqueId];
  67419. if (meshHighlight) {
  67420. meshHighlight.color = color;
  67421. }
  67422. else {
  67423. this._meshes[mesh.uniqueId] = {
  67424. mesh: mesh,
  67425. color: color,
  67426. // Lambda required for capture due to Observable this context
  67427. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  67428. if (_this._excludedMeshes[mesh.uniqueId]) {
  67429. _this.defaultStencilReference(mesh);
  67430. }
  67431. else {
  67432. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  67433. }
  67434. }),
  67435. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  67436. glowEmissiveOnly: glowEmissiveOnly
  67437. };
  67438. }
  67439. this._shouldRender = true;
  67440. };
  67441. /**
  67442. * Remove a mesh from the highlight layer in order to make it stop glowing.
  67443. * @param mesh The mesh to highlight
  67444. */
  67445. HighlightLayer.prototype.removeMesh = function (mesh) {
  67446. var meshHighlight = this._meshes[mesh.uniqueId];
  67447. if (meshHighlight) {
  67448. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  67449. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  67450. }
  67451. this._meshes[mesh.uniqueId] = undefined;
  67452. this._shouldRender = false;
  67453. for (var meshHighlightToCheck in this._meshes) {
  67454. if (meshHighlightToCheck) {
  67455. this._shouldRender = true;
  67456. break;
  67457. }
  67458. }
  67459. };
  67460. /**
  67461. * Returns true if the layer contains information to display, otherwise false.
  67462. */
  67463. HighlightLayer.prototype.shouldRender = function () {
  67464. return this.isEnabled && this._shouldRender;
  67465. };
  67466. /**
  67467. * Sets the main texture desired size which is the closest power of two
  67468. * of the engine canvas size.
  67469. */
  67470. HighlightLayer.prototype.setMainTextureSize = function () {
  67471. if (this._options.mainTextureFixedSize) {
  67472. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  67473. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  67474. }
  67475. else {
  67476. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  67477. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  67478. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  67479. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  67480. }
  67481. };
  67482. /**
  67483. * Force the stencil to the normal expected value for none glowing parts
  67484. */
  67485. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  67486. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  67487. };
  67488. /**
  67489. * Dispose only the render target textures and post process.
  67490. */
  67491. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  67492. this._blurTexture.dispose();
  67493. this._mainTexture.dispose();
  67494. this._downSamplePostprocess.dispose();
  67495. this._horizontalBlurPostprocess.dispose();
  67496. this._verticalBlurPostprocess.dispose();
  67497. };
  67498. /**
  67499. * Dispose the highlight layer and free resources.
  67500. */
  67501. HighlightLayer.prototype.dispose = function () {
  67502. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67503. if (vertexBuffer) {
  67504. vertexBuffer.dispose();
  67505. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67506. }
  67507. if (this._indexBuffer) {
  67508. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67509. this._indexBuffer = null;
  67510. }
  67511. // Clean textures and post processes
  67512. this.disposeTextureAndPostProcesses();
  67513. // Clean mesh references
  67514. for (var id in this._meshes) {
  67515. var meshHighlight = this._meshes[id];
  67516. if (meshHighlight && meshHighlight.mesh) {
  67517. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  67518. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  67519. }
  67520. }
  67521. this._meshes = null;
  67522. for (var id in this._excludedMeshes) {
  67523. var meshHighlight = this._excludedMeshes[id];
  67524. if (meshHighlight) {
  67525. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  67526. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  67527. }
  67528. }
  67529. this._excludedMeshes = null;
  67530. // Remove from scene
  67531. var index = this._scene.highlightLayers.indexOf(this, 0);
  67532. if (index > -1) {
  67533. this._scene.highlightLayers.splice(index, 1);
  67534. }
  67535. // Callback
  67536. this.onDisposeObservable.notifyObservers(this);
  67537. this.onDisposeObservable.clear();
  67538. this.onBeforeRenderMainTextureObservable.clear();
  67539. this.onBeforeBlurObservable.clear();
  67540. this.onBeforeComposeObservable.clear();
  67541. this.onAfterComposeObservable.clear();
  67542. this.onSizeChangedObservable.clear();
  67543. };
  67544. /**
  67545. * The neutral color used during the preparation of the glow effect.
  67546. * This is black by default as the blend operation is a blend operation.
  67547. */
  67548. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  67549. /**
  67550. * Stencil value used for glowing meshes.
  67551. */
  67552. HighlightLayer.glowingMeshStencilReference = 0x02;
  67553. /**
  67554. * Stencil value used for the other meshes in the scene.
  67555. */
  67556. HighlightLayer.normalMeshStencilReference = 0x01;
  67557. return HighlightLayer;
  67558. }());
  67559. BABYLON.HighlightLayer = HighlightLayer;
  67560. })(BABYLON || (BABYLON = {}));
  67561. //# sourceMappingURL=babylon.highlightlayer.js.map
  67562. var BABYLON;
  67563. (function (BABYLON) {
  67564. var MeshAssetTask = (function () {
  67565. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  67566. this.name = name;
  67567. this.meshesNames = meshesNames;
  67568. this.rootUrl = rootUrl;
  67569. this.sceneFilename = sceneFilename;
  67570. this.isCompleted = false;
  67571. }
  67572. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67573. var _this = this;
  67574. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  67575. _this.loadedMeshes = meshes;
  67576. _this.loadedParticleSystems = particleSystems;
  67577. _this.loadedSkeletons = skeletons;
  67578. _this.isCompleted = true;
  67579. if (_this.onSuccess) {
  67580. _this.onSuccess(_this);
  67581. }
  67582. onSuccess();
  67583. }, null, function () {
  67584. if (_this.onError) {
  67585. _this.onError(_this);
  67586. }
  67587. onError();
  67588. });
  67589. };
  67590. return MeshAssetTask;
  67591. }());
  67592. BABYLON.MeshAssetTask = MeshAssetTask;
  67593. var TextFileAssetTask = (function () {
  67594. function TextFileAssetTask(name, url) {
  67595. this.name = name;
  67596. this.url = url;
  67597. this.isCompleted = false;
  67598. }
  67599. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67600. var _this = this;
  67601. BABYLON.Tools.LoadFile(this.url, function (data) {
  67602. _this.text = data;
  67603. _this.isCompleted = true;
  67604. if (_this.onSuccess) {
  67605. _this.onSuccess(_this);
  67606. }
  67607. onSuccess();
  67608. }, null, scene.database, false, function () {
  67609. if (_this.onError) {
  67610. _this.onError(_this);
  67611. }
  67612. onError();
  67613. });
  67614. };
  67615. return TextFileAssetTask;
  67616. }());
  67617. BABYLON.TextFileAssetTask = TextFileAssetTask;
  67618. var BinaryFileAssetTask = (function () {
  67619. function BinaryFileAssetTask(name, url) {
  67620. this.name = name;
  67621. this.url = url;
  67622. this.isCompleted = false;
  67623. }
  67624. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67625. var _this = this;
  67626. BABYLON.Tools.LoadFile(this.url, function (data) {
  67627. _this.data = data;
  67628. _this.isCompleted = true;
  67629. if (_this.onSuccess) {
  67630. _this.onSuccess(_this);
  67631. }
  67632. onSuccess();
  67633. }, null, scene.database, true, function () {
  67634. if (_this.onError) {
  67635. _this.onError(_this);
  67636. }
  67637. onError();
  67638. });
  67639. };
  67640. return BinaryFileAssetTask;
  67641. }());
  67642. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  67643. var ImageAssetTask = (function () {
  67644. function ImageAssetTask(name, url) {
  67645. this.name = name;
  67646. this.url = url;
  67647. this.isCompleted = false;
  67648. }
  67649. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67650. var _this = this;
  67651. var img = new Image();
  67652. BABYLON.Tools.SetCorsBehavior(this.url, img);
  67653. img.onload = function () {
  67654. _this.image = img;
  67655. _this.isCompleted = true;
  67656. if (_this.onSuccess) {
  67657. _this.onSuccess(_this);
  67658. }
  67659. onSuccess();
  67660. };
  67661. img.onerror = function () {
  67662. if (_this.onError) {
  67663. _this.onError(_this);
  67664. }
  67665. onError();
  67666. };
  67667. img.src = this.url;
  67668. };
  67669. return ImageAssetTask;
  67670. }());
  67671. BABYLON.ImageAssetTask = ImageAssetTask;
  67672. var TextureAssetTask = (function () {
  67673. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  67674. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67675. this.name = name;
  67676. this.url = url;
  67677. this.noMipmap = noMipmap;
  67678. this.invertY = invertY;
  67679. this.samplingMode = samplingMode;
  67680. this.isCompleted = false;
  67681. }
  67682. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67683. var _this = this;
  67684. var onload = function () {
  67685. _this.isCompleted = true;
  67686. if (_this.onSuccess) {
  67687. _this.onSuccess(_this);
  67688. }
  67689. onSuccess();
  67690. };
  67691. var onerror = function () {
  67692. if (_this.onError) {
  67693. _this.onError(_this);
  67694. }
  67695. onError();
  67696. };
  67697. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  67698. };
  67699. return TextureAssetTask;
  67700. }());
  67701. BABYLON.TextureAssetTask = TextureAssetTask;
  67702. var CubeTextureAssetTask = (function () {
  67703. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  67704. this.name = name;
  67705. this.url = url;
  67706. this.extensions = extensions;
  67707. this.noMipmap = noMipmap;
  67708. this.files = files;
  67709. this.isCompleted = false;
  67710. }
  67711. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67712. var _this = this;
  67713. var onload = function () {
  67714. _this.isCompleted = true;
  67715. if (_this.onSuccess) {
  67716. _this.onSuccess(_this);
  67717. }
  67718. onSuccess();
  67719. };
  67720. var onerror = function () {
  67721. if (_this.onError) {
  67722. _this.onError(_this);
  67723. }
  67724. onError();
  67725. };
  67726. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  67727. };
  67728. return CubeTextureAssetTask;
  67729. }());
  67730. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  67731. var HDRCubeTextureAssetTask = (function () {
  67732. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  67733. if (noMipmap === void 0) { noMipmap = false; }
  67734. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67735. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67736. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67737. this.name = name;
  67738. this.url = url;
  67739. this.size = size;
  67740. this.noMipmap = noMipmap;
  67741. this.generateHarmonics = generateHarmonics;
  67742. this.useInGammaSpace = useInGammaSpace;
  67743. this.usePMREMGenerator = usePMREMGenerator;
  67744. this.isCompleted = false;
  67745. }
  67746. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  67747. var _this = this;
  67748. var onload = function () {
  67749. _this.isCompleted = true;
  67750. if (_this.onSuccess) {
  67751. _this.onSuccess(_this);
  67752. }
  67753. onSuccess();
  67754. };
  67755. var onerror = function () {
  67756. if (_this.onError) {
  67757. _this.onError(_this);
  67758. }
  67759. onError();
  67760. };
  67761. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  67762. };
  67763. return HDRCubeTextureAssetTask;
  67764. }());
  67765. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  67766. var AssetsManager = (function () {
  67767. function AssetsManager(scene) {
  67768. this.tasks = new Array();
  67769. this.waitingTasksCount = 0;
  67770. this.useDefaultLoadingScreen = true;
  67771. this._scene = scene;
  67772. }
  67773. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  67774. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  67775. this.tasks.push(task);
  67776. return task;
  67777. };
  67778. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  67779. var task = new TextFileAssetTask(taskName, url);
  67780. this.tasks.push(task);
  67781. return task;
  67782. };
  67783. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  67784. var task = new BinaryFileAssetTask(taskName, url);
  67785. this.tasks.push(task);
  67786. return task;
  67787. };
  67788. AssetsManager.prototype.addImageTask = function (taskName, url) {
  67789. var task = new ImageAssetTask(taskName, url);
  67790. this.tasks.push(task);
  67791. return task;
  67792. };
  67793. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  67794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67795. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  67796. this.tasks.push(task);
  67797. return task;
  67798. };
  67799. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  67800. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  67801. this.tasks.push(task);
  67802. return task;
  67803. };
  67804. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  67805. if (noMipmap === void 0) { noMipmap = false; }
  67806. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67807. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67808. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67809. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  67810. this.tasks.push(task);
  67811. return task;
  67812. };
  67813. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  67814. this.waitingTasksCount--;
  67815. if (this.waitingTasksCount === 0) {
  67816. if (this.onFinish) {
  67817. this.onFinish(this.tasks);
  67818. }
  67819. this._scene.getEngine().hideLoadingUI();
  67820. }
  67821. };
  67822. AssetsManager.prototype._runTask = function (task) {
  67823. var _this = this;
  67824. task.run(this._scene, function () {
  67825. if (_this.onTaskSuccess) {
  67826. _this.onTaskSuccess(task);
  67827. }
  67828. _this._decreaseWaitingTasksCount();
  67829. }, function () {
  67830. if (_this.onTaskError) {
  67831. _this.onTaskError(task);
  67832. }
  67833. _this._decreaseWaitingTasksCount();
  67834. });
  67835. };
  67836. AssetsManager.prototype.reset = function () {
  67837. this.tasks = new Array();
  67838. return this;
  67839. };
  67840. AssetsManager.prototype.load = function () {
  67841. this.waitingTasksCount = this.tasks.length;
  67842. if (this.waitingTasksCount === 0) {
  67843. if (this.onFinish) {
  67844. this.onFinish(this.tasks);
  67845. }
  67846. return this;
  67847. }
  67848. if (this.useDefaultLoadingScreen) {
  67849. this._scene.getEngine().displayLoadingUI();
  67850. }
  67851. for (var index = 0; index < this.tasks.length; index++) {
  67852. var task = this.tasks[index];
  67853. this._runTask(task);
  67854. }
  67855. return this;
  67856. };
  67857. return AssetsManager;
  67858. }());
  67859. BABYLON.AssetsManager = AssetsManager;
  67860. })(BABYLON || (BABYLON = {}));
  67861. //# sourceMappingURL=babylon.assetsManager.js.map
  67862. var BABYLON;
  67863. (function (BABYLON) {
  67864. var MapTexture = (function (_super) {
  67865. __extends(MapTexture, _super);
  67866. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  67867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67868. if (useMipMap === void 0) { useMipMap = false; }
  67869. if (margin === void 0) { margin = 0; }
  67870. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  67871. _this.name = name;
  67872. _this._size = size;
  67873. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67874. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67875. // Create the rectPackMap that will allocate portion of the texture
  67876. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  67877. // Create the texture that will store the content
  67878. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  67879. return _this;
  67880. }
  67881. /**
  67882. * Allocate a rectangle of a given size in the texture map
  67883. * @param size the size of the rectangle to allocation
  67884. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  67885. */
  67886. MapTexture.prototype.allocateRect = function (size) {
  67887. return this._rectPackingMap.addRect(size);
  67888. };
  67889. /**
  67890. * Free a given rectangle from the texture map
  67891. * @param rectInfo the instance corresponding to the rect to free.
  67892. */
  67893. MapTexture.prototype.freeRect = function (rectInfo) {
  67894. if (rectInfo) {
  67895. rectInfo.freeContent();
  67896. }
  67897. };
  67898. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  67899. /**
  67900. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  67901. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  67902. * @returns {}
  67903. */
  67904. get: function () {
  67905. return this._rectPackingMap.freeSpace;
  67906. },
  67907. enumerable: true,
  67908. configurable: true
  67909. });
  67910. /**
  67911. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  67912. * 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.
  67913. * Don't forget to call unbindTexture when you're done rendering
  67914. * @param rect the zone to render to
  67915. * @param clear true to clear the portion's color/depth data
  67916. */
  67917. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  67918. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  67919. };
  67920. /**
  67921. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  67922. * 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.
  67923. * Don't forget to call unbindTexture when you're done rendering
  67924. * @param pos the position into the texture
  67925. * @param size the portion to fit the clip space to
  67926. * @param clear true to clear the portion's color/depth data
  67927. */
  67928. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  67929. var engine = this.getScene().getEngine();
  67930. engine.bindFramebuffer(this._texture);
  67931. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  67932. if (clear) {
  67933. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  67934. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  67935. }
  67936. };
  67937. /**
  67938. * Unbind the texture map from the rendering engine.
  67939. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  67940. * @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.
  67941. */
  67942. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  67943. // Dump ?
  67944. if (dumpForDebug) {
  67945. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  67946. }
  67947. var engine = this.getScene().getEngine();
  67948. if (this._replacedViewport) {
  67949. engine.setViewport(this._replacedViewport);
  67950. this._replacedViewport = null;
  67951. }
  67952. engine.unBindFramebuffer(this._texture);
  67953. };
  67954. Object.defineProperty(MapTexture.prototype, "canRescale", {
  67955. get: function () {
  67956. return false;
  67957. },
  67958. enumerable: true,
  67959. configurable: true
  67960. });
  67961. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  67962. // Anyway, there's not much point to use this method for this kind of texture I guess
  67963. MapTexture.prototype.clone = function () {
  67964. return null;
  67965. };
  67966. return MapTexture;
  67967. }(BABYLON.Texture));
  67968. BABYLON.MapTexture = MapTexture;
  67969. })(BABYLON || (BABYLON = {}));
  67970. //# sourceMappingURL=babylon.mapTexture.js.map
  67971. var BABYLON;
  67972. (function (BABYLON) {
  67973. /**
  67974. * This class describe a rectangle that were added to the map.
  67975. * You have access to its coordinates either in pixel or normalized (UV)
  67976. */
  67977. var PackedRect = (function () {
  67978. function PackedRect(root, parent, pos, size) {
  67979. this._pos = pos;
  67980. this._size = size;
  67981. this._root = root;
  67982. this._parent = parent;
  67983. this._contentSize = null;
  67984. this._bottomNode = null;
  67985. this._leftNode = null;
  67986. this._initialSize = null;
  67987. this._rightNode = null;
  67988. }
  67989. Object.defineProperty(PackedRect.prototype, "pos", {
  67990. /**
  67991. * @returns the position of this node into the map
  67992. */
  67993. get: function () {
  67994. return this._pos;
  67995. },
  67996. enumerable: true,
  67997. configurable: true
  67998. });
  67999. Object.defineProperty(PackedRect.prototype, "contentSize", {
  68000. /**
  68001. * @returns the size of the rectangle this node handles
  68002. */
  68003. get: function () {
  68004. return this._contentSize;
  68005. },
  68006. enumerable: true,
  68007. configurable: true
  68008. });
  68009. /**
  68010. * Retrieve the inner position (considering the margin) and stores it into the res object
  68011. * @param res must be a valid Vector2 that will contain the inner position after this call
  68012. */
  68013. PackedRect.prototype.getInnerPosToRef = function (res) {
  68014. var m = this._root._margin;
  68015. res.x = this._pos.x + m;
  68016. res.y = this._pos.y + m;
  68017. };
  68018. /**
  68019. * Retrieve the inner size (considering the margin) and stores it into the res object
  68020. * @param res must be a valid Size that will contain the inner size after this call
  68021. */
  68022. PackedRect.prototype.getInnerSizeToRef = function (res) {
  68023. var m = this._root._margin;
  68024. res.width = this._contentSize.width - (m * 2);
  68025. res.height = this._contentSize.height - (m * 2);
  68026. };
  68027. Object.defineProperty(PackedRect.prototype, "UVs", {
  68028. /**
  68029. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  68030. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  68031. */
  68032. get: function () {
  68033. if (!this._contentSize) {
  68034. throw new Error("Can't compute UVs for this object because it's nor allocated");
  68035. }
  68036. return this.getUVsForCustomSize(this._contentSize);
  68037. },
  68038. enumerable: true,
  68039. configurable: true
  68040. });
  68041. /**
  68042. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  68043. * and then using only a part of the PackRect.
  68044. * This method will return the UVs for this part by given the custom size of what you really use
  68045. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  68046. */
  68047. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  68048. var mainWidth = this._root._size.width;
  68049. var mainHeight = this._root._size.height;
  68050. var margin = this._root._margin;
  68051. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  68052. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  68053. var uvs = new Array();
  68054. uvs.push(topLeft);
  68055. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  68056. uvs.push(rightBottom);
  68057. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  68058. return uvs;
  68059. };
  68060. /**
  68061. * Free this rectangle from the map.
  68062. * Call this method when you no longer need the rectangle to be in the map.
  68063. */
  68064. PackedRect.prototype.freeContent = function () {
  68065. if (!this.contentSize) {
  68066. return;
  68067. }
  68068. this._contentSize = null;
  68069. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  68070. this.attemptDefrag();
  68071. };
  68072. Object.defineProperty(PackedRect.prototype, "isUsed", {
  68073. get: function () {
  68074. return this._contentSize != null || this._leftNode != null;
  68075. },
  68076. enumerable: true,
  68077. configurable: true
  68078. });
  68079. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  68080. var node = this.findNode(contentSize);
  68081. // Not enough space...
  68082. if (!node) {
  68083. return null;
  68084. }
  68085. node.splitNode(contentSize);
  68086. return node;
  68087. };
  68088. PackedRect.prototype.findNode = function (size) {
  68089. var resNode = null;
  68090. var margin = this._root._margin * 2;
  68091. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  68092. if (this.isUsed) {
  68093. if (this._leftNode) {
  68094. resNode = this._leftNode.findNode(size);
  68095. }
  68096. if (!resNode && this._rightNode) {
  68097. resNode = this._rightNode.findNode(size);
  68098. }
  68099. if (!resNode && this._bottomNode) {
  68100. resNode = this._bottomNode.findNode(size);
  68101. }
  68102. }
  68103. else if (this._initialSize) {
  68104. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  68105. resNode = this;
  68106. }
  68107. else {
  68108. return null;
  68109. }
  68110. }
  68111. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  68112. resNode = this;
  68113. }
  68114. return resNode;
  68115. };
  68116. PackedRect.prototype.splitNode = function (contentSize) {
  68117. var cs = PackedRect.TpsSize;
  68118. var margin = this._root._margin * 2;
  68119. cs.copyFrom(contentSize);
  68120. cs.width += margin;
  68121. cs.height += margin;
  68122. // 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)
  68123. if (!this._contentSize && this._initialSize) {
  68124. this._contentSize = cs.clone();
  68125. 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));
  68126. return this._leftNode.splitNode(contentSize);
  68127. }
  68128. else {
  68129. this._contentSize = cs.clone();
  68130. this._initialSize = cs.clone();
  68131. if (cs.width !== this._size.width) {
  68132. 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));
  68133. }
  68134. if (cs.height !== this._size.height) {
  68135. 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));
  68136. }
  68137. return this;
  68138. }
  68139. };
  68140. PackedRect.prototype.attemptDefrag = function () {
  68141. if (!this.isUsed && this.isRecursiveFree) {
  68142. this.clearNode();
  68143. if (this._parent) {
  68144. this._parent.attemptDefrag();
  68145. }
  68146. }
  68147. };
  68148. PackedRect.prototype.clearNode = function () {
  68149. this._initialSize = null;
  68150. this._rightNode = null;
  68151. this._bottomNode = null;
  68152. };
  68153. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  68154. get: function () {
  68155. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  68156. },
  68157. enumerable: true,
  68158. configurable: true
  68159. });
  68160. PackedRect.prototype.evalFreeSize = function (size) {
  68161. var levelSize = 0;
  68162. if (!this.isUsed) {
  68163. var margin = this._root._margin;
  68164. var is = this._initialSize;
  68165. if (is) {
  68166. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  68167. }
  68168. else {
  68169. var size_1 = this._size;
  68170. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  68171. }
  68172. }
  68173. if (this._rightNode) {
  68174. levelSize += this._rightNode.evalFreeSize(0);
  68175. }
  68176. if (this._bottomNode) {
  68177. levelSize += this._bottomNode.evalFreeSize(0);
  68178. }
  68179. return levelSize + size;
  68180. };
  68181. PackedRect.TpsSize = BABYLON.Size.Zero();
  68182. return PackedRect;
  68183. }());
  68184. BABYLON.PackedRect = PackedRect;
  68185. /**
  68186. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  68187. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  68188. * 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.
  68189. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  68190. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  68191. */
  68192. var RectPackingMap = (function (_super) {
  68193. __extends(RectPackingMap, _super);
  68194. /**
  68195. * Create an instance of the object with a dimension using the given size
  68196. * @param size The dimension of the rectangle that will contain all the sub ones.
  68197. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  68198. */
  68199. function RectPackingMap(size, margin) {
  68200. if (margin === void 0) { margin = 0; }
  68201. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  68202. _this._margin = margin;
  68203. _this._root = _this;
  68204. return _this;
  68205. }
  68206. /**
  68207. * Add a rectangle, finding the best location to store it into the map
  68208. * @param size the dimension of the rectangle to store
  68209. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  68210. */
  68211. RectPackingMap.prototype.addRect = function (size) {
  68212. var node = this.findAndSplitNode(size);
  68213. return node;
  68214. };
  68215. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  68216. /**
  68217. * Return the current space free normalized between [0;1]
  68218. * @returns {}
  68219. */
  68220. get: function () {
  68221. var freeSize = 0;
  68222. freeSize = this.evalFreeSize(freeSize);
  68223. return freeSize / (this._size.width * this._size.height);
  68224. },
  68225. enumerable: true,
  68226. configurable: true
  68227. });
  68228. return RectPackingMap;
  68229. }(PackedRect));
  68230. BABYLON.RectPackingMap = RectPackingMap;
  68231. })(BABYLON || (BABYLON = {}));
  68232. //# sourceMappingURL=babylon.rectPackingMap.js.map
  68233. var BABYLON;
  68234. (function (BABYLON) {
  68235. /**
  68236. * This groups together the common properties used for image processing either in direct forward pass
  68237. * or through post processing effect depending on the use of the image processing pipeline in your scene
  68238. * or not.
  68239. */
  68240. var ImageProcessingConfiguration = (function () {
  68241. function ImageProcessingConfiguration() {
  68242. /**
  68243. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  68244. */
  68245. this.colorCurves = new BABYLON.ColorCurves();
  68246. this._colorCurvesEnabled = false;
  68247. this._colorGradingEnabled = false;
  68248. this._colorGradingWithGreenDepth = false;
  68249. this._colorGradingBGR = false;
  68250. this._exposure = 1.0;
  68251. this._toneMappingEnabled = false;
  68252. this._contrast = 1.0;
  68253. /**
  68254. * Vignette stretch size.
  68255. */
  68256. this.vignetteStretch = 0;
  68257. /**
  68258. * Vignette centre X Offset.
  68259. */
  68260. this.vignetteCentreX = 0;
  68261. /**
  68262. * Vignette centre Y Offset.
  68263. */
  68264. this.vignetteCentreY = 0;
  68265. /**
  68266. * Vignette weight or intensity of the vignette effect.
  68267. */
  68268. this.vignetteWeight = 1.5;
  68269. /**
  68270. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68271. * if vignetteEnabled is set to true.
  68272. */
  68273. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  68274. /**
  68275. * Camera field of view used by the Vignette effect.
  68276. */
  68277. this.vignetteCameraFov = 0.5;
  68278. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  68279. this._vignetteEnabled = false;
  68280. this._applyByPostProcess = false;
  68281. /**
  68282. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  68283. * @type {BABYLON.Observable}
  68284. */
  68285. this.onUpdateParameters = new BABYLON.Observable();
  68286. }
  68287. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  68288. /**
  68289. * Gets wether the color curves effect is enabled.
  68290. */
  68291. get: function () {
  68292. return this._colorCurvesEnabled;
  68293. },
  68294. /**
  68295. * Sets wether the color curves effect is enabled.
  68296. */
  68297. set: function (value) {
  68298. if (this._colorCurvesEnabled === value) {
  68299. return;
  68300. }
  68301. this._colorCurvesEnabled = value;
  68302. this._updateParameters();
  68303. },
  68304. enumerable: true,
  68305. configurable: true
  68306. });
  68307. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  68308. /**
  68309. * Gets wether the color grading effect is enabled.
  68310. */
  68311. get: function () {
  68312. return this._colorGradingEnabled;
  68313. },
  68314. /**
  68315. * Sets wether the color grading effect is enabled.
  68316. */
  68317. set: function (value) {
  68318. if (this._colorGradingEnabled === value) {
  68319. return;
  68320. }
  68321. this._colorGradingEnabled = value;
  68322. this._updateParameters();
  68323. },
  68324. enumerable: true,
  68325. configurable: true
  68326. });
  68327. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  68328. /**
  68329. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  68330. */
  68331. get: function () {
  68332. return this._colorGradingWithGreenDepth;
  68333. },
  68334. /**
  68335. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  68336. */
  68337. set: function (value) {
  68338. if (this._colorGradingWithGreenDepth === value) {
  68339. return;
  68340. }
  68341. this._colorGradingWithGreenDepth = value;
  68342. this._updateParameters();
  68343. },
  68344. enumerable: true,
  68345. configurable: true
  68346. });
  68347. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  68348. /**
  68349. * Gets wether the color grading texture contains BGR values.
  68350. */
  68351. get: function () {
  68352. return this._colorGradingBGR;
  68353. },
  68354. /**
  68355. * Sets wether the color grading texture contains BGR values.
  68356. */
  68357. set: function (value) {
  68358. if (this._colorGradingBGR === value) {
  68359. return;
  68360. }
  68361. this._colorGradingBGR = value;
  68362. this._updateParameters();
  68363. },
  68364. enumerable: true,
  68365. configurable: true
  68366. });
  68367. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  68368. /**
  68369. * Gets the Exposure used in the effect.
  68370. */
  68371. get: function () {
  68372. return this._exposure;
  68373. },
  68374. /**
  68375. * Sets the Exposure used in the effect.
  68376. */
  68377. set: function (value) {
  68378. if (this._exposure === value) {
  68379. return;
  68380. }
  68381. this._exposure = value;
  68382. this._updateParameters();
  68383. },
  68384. enumerable: true,
  68385. configurable: true
  68386. });
  68387. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  68388. /**
  68389. * Gets wether the tone mapping effect is enabled.
  68390. */
  68391. get: function () {
  68392. return this._toneMappingEnabled;
  68393. },
  68394. /**
  68395. * Sets wether the tone mapping effect is enabled.
  68396. */
  68397. set: function (value) {
  68398. if (this._toneMappingEnabled === value) {
  68399. return;
  68400. }
  68401. this._toneMappingEnabled = value;
  68402. this._updateParameters();
  68403. },
  68404. enumerable: true,
  68405. configurable: true
  68406. });
  68407. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  68408. /**
  68409. * Gets the contrast used in the effect.
  68410. */
  68411. get: function () {
  68412. return this._contrast;
  68413. },
  68414. /**
  68415. * Sets the contrast used in the effect.
  68416. */
  68417. set: function (value) {
  68418. if (this._contrast === value) {
  68419. return;
  68420. }
  68421. this._contrast = value;
  68422. this._updateParameters();
  68423. },
  68424. enumerable: true,
  68425. configurable: true
  68426. });
  68427. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  68428. /**
  68429. * Gets the vignette blend mode allowing different kind of effect.
  68430. */
  68431. get: function () {
  68432. return this._vignetteBlendMode;
  68433. },
  68434. /**
  68435. * Sets the vignette blend mode allowing different kind of effect.
  68436. */
  68437. set: function (value) {
  68438. if (this._vignetteBlendMode === value) {
  68439. return;
  68440. }
  68441. this._vignetteBlendMode = value;
  68442. this._updateParameters();
  68443. },
  68444. enumerable: true,
  68445. configurable: true
  68446. });
  68447. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  68448. /**
  68449. * Gets wether the vignette effect is enabled.
  68450. */
  68451. get: function () {
  68452. return this._vignetteEnabled;
  68453. },
  68454. /**
  68455. * Sets wether the vignette effect is enabled.
  68456. */
  68457. set: function (value) {
  68458. if (this._vignetteEnabled === value) {
  68459. return;
  68460. }
  68461. this._vignetteEnabled = value;
  68462. this._updateParameters();
  68463. },
  68464. enumerable: true,
  68465. configurable: true
  68466. });
  68467. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  68468. /**
  68469. * Gets wether the image processing is applied through a post process or not.
  68470. */
  68471. get: function () {
  68472. return this._applyByPostProcess;
  68473. },
  68474. /**
  68475. * Sets wether the image processing is applied through a post process or not.
  68476. */
  68477. set: function (value) {
  68478. if (this._applyByPostProcess === value) {
  68479. return;
  68480. }
  68481. this._applyByPostProcess = value;
  68482. this._updateParameters();
  68483. },
  68484. enumerable: true,
  68485. configurable: true
  68486. });
  68487. /**
  68488. * Method called each time the image processing information changes requires to recompile the effect.
  68489. */
  68490. ImageProcessingConfiguration.prototype._updateParameters = function () {
  68491. this.onUpdateParameters.notifyObservers(this);
  68492. };
  68493. ImageProcessingConfiguration.prototype.getClassName = function () {
  68494. return "ImageProcessingConfiguration";
  68495. };
  68496. /**
  68497. * Prepare the list of uniforms associated with the Image Processing effects.
  68498. * @param uniformsList The list of uniforms used in the effect
  68499. * @param defines the list of defines currently in use
  68500. */
  68501. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  68502. if (defines.EXPOSURE) {
  68503. uniforms.push("exposureLinear");
  68504. }
  68505. if (defines.CONTRAST) {
  68506. uniforms.push("contrast");
  68507. }
  68508. if (defines.COLORGRADING) {
  68509. uniforms.push("colorTransformSettings");
  68510. }
  68511. if (defines.VIGNETTE) {
  68512. uniforms.push("vInverseScreenSize");
  68513. uniforms.push("vignetteSettings1");
  68514. uniforms.push("vignetteSettings2");
  68515. }
  68516. if (defines.COLORCURVES) {
  68517. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  68518. }
  68519. };
  68520. /**
  68521. * Prepare the list of samplers associated with the Image Processing effects.
  68522. * @param uniformsList The list of uniforms used in the effect
  68523. * @param defines the list of defines currently in use
  68524. */
  68525. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  68526. if (defines.COLORGRADING) {
  68527. samplersList.push("txColorTransform");
  68528. }
  68529. };
  68530. /**
  68531. * Prepare the list of defines associated to the shader.
  68532. * @param defines the list of defines to complete
  68533. */
  68534. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  68535. defines.VIGNETTE = this.vignetteEnabled;
  68536. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  68537. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  68538. defines.TONEMAPPING = this.toneMappingEnabled;
  68539. defines.CONTRAST = (this.contrast !== 1.0);
  68540. defines.EXPOSURE = (this.exposure !== 1.0);
  68541. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  68542. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  68543. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  68544. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  68545. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  68546. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  68547. };
  68548. /**
  68549. * Returns true if all the image processing information are ready.
  68550. */
  68551. ImageProcessingConfiguration.prototype.isReady = function () {
  68552. // Color Grading texure can not be none blocking.
  68553. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  68554. };
  68555. /**
  68556. * Binds the image processing to the shader.
  68557. * @param effect The effect to bind to
  68558. */
  68559. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  68560. if (aspectRatio === void 0) { aspectRatio = 1; }
  68561. // Color Curves
  68562. if (this._colorCurvesEnabled) {
  68563. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  68564. }
  68565. // Vignette
  68566. if (this._vignetteEnabled) {
  68567. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  68568. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  68569. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  68570. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  68571. var vignetteScaleX = vignetteScaleY * aspectRatio;
  68572. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  68573. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  68574. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  68575. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  68576. var vignettePower = -2.0 * this.vignetteWeight;
  68577. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  68578. }
  68579. // Exposure
  68580. effect.setFloat("exposureLinear", this.exposure);
  68581. // Contrast
  68582. effect.setFloat("contrast", this.contrast);
  68583. // Color transform settings
  68584. if (this.colorGradingTexture) {
  68585. effect.setTexture("txColorTransform", this.colorGradingTexture);
  68586. var textureSize = this.colorGradingTexture.getSize().height;
  68587. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  68588. 0.5 / textureSize, // textureOffset
  68589. textureSize, // textureSize
  68590. this.colorGradingTexture.level // weight
  68591. );
  68592. }
  68593. };
  68594. /**
  68595. * Clones the current image processing instance.
  68596. * @return The cloned image processing
  68597. */
  68598. ImageProcessingConfiguration.prototype.clone = function () {
  68599. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  68600. };
  68601. /**
  68602. * Serializes the current image processing instance to a json representation.
  68603. * @return a JSON representation
  68604. */
  68605. ImageProcessingConfiguration.prototype.serialize = function () {
  68606. return BABYLON.SerializationHelper.Serialize(this);
  68607. };
  68608. /**
  68609. * Parses the image processing from a json representation.
  68610. * @param source the JSON source to parse
  68611. * @return The parsed image processing
  68612. */
  68613. ImageProcessingConfiguration.Parse = function (source) {
  68614. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  68615. };
  68616. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  68617. /**
  68618. * Used to apply the vignette as a mix with the pixel color.
  68619. */
  68620. get: function () {
  68621. return this._VIGNETTEMODE_MULTIPLY;
  68622. },
  68623. enumerable: true,
  68624. configurable: true
  68625. });
  68626. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  68627. /**
  68628. * Used to apply the vignette as a replacement of the pixel color.
  68629. */
  68630. get: function () {
  68631. return this._VIGNETTEMODE_OPAQUE;
  68632. },
  68633. enumerable: true,
  68634. configurable: true
  68635. });
  68636. // Static constants associated to the image processing.
  68637. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  68638. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  68639. __decorate([
  68640. BABYLON.serializeAsColorCurves()
  68641. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  68642. __decorate([
  68643. BABYLON.serialize()
  68644. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  68645. __decorate([
  68646. BABYLON.serializeAsTexture()
  68647. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  68648. __decorate([
  68649. BABYLON.serialize()
  68650. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  68651. __decorate([
  68652. BABYLON.serialize()
  68653. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  68654. __decorate([
  68655. BABYLON.serialize()
  68656. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  68657. __decorate([
  68658. BABYLON.serialize()
  68659. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  68660. __decorate([
  68661. BABYLON.serialize()
  68662. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  68663. __decorate([
  68664. BABYLON.serialize()
  68665. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  68666. __decorate([
  68667. BABYLON.serialize()
  68668. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  68669. __decorate([
  68670. BABYLON.serialize()
  68671. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  68672. __decorate([
  68673. BABYLON.serialize()
  68674. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  68675. __decorate([
  68676. BABYLON.serialize()
  68677. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  68678. __decorate([
  68679. BABYLON.serializeAsColor4()
  68680. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  68681. __decorate([
  68682. BABYLON.serialize()
  68683. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  68684. __decorate([
  68685. BABYLON.serialize()
  68686. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  68687. __decorate([
  68688. BABYLON.serialize()
  68689. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  68690. __decorate([
  68691. BABYLON.serialize()
  68692. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  68693. return ImageProcessingConfiguration;
  68694. }());
  68695. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  68696. })(BABYLON || (BABYLON = {}));
  68697. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  68698. var BABYLON;
  68699. (function (BABYLON) {
  68700. var serializedGeometries = [];
  68701. var serializeGeometry = function (geometry, serializationGeometries) {
  68702. if (serializedGeometries[geometry.id]) {
  68703. return;
  68704. }
  68705. if (geometry.doNotSerialize) {
  68706. return;
  68707. }
  68708. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  68709. serializationGeometries.boxes.push(geometry.serialize());
  68710. }
  68711. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  68712. serializationGeometries.spheres.push(geometry.serialize());
  68713. }
  68714. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  68715. serializationGeometries.cylinders.push(geometry.serialize());
  68716. }
  68717. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  68718. serializationGeometries.toruses.push(geometry.serialize());
  68719. }
  68720. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  68721. serializationGeometries.grounds.push(geometry.serialize());
  68722. }
  68723. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  68724. serializationGeometries.planes.push(geometry.serialize());
  68725. }
  68726. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  68727. serializationGeometries.torusKnots.push(geometry.serialize());
  68728. }
  68729. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  68730. throw new Error("Unknown primitive type");
  68731. }
  68732. else {
  68733. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  68734. }
  68735. serializedGeometries[geometry.id] = true;
  68736. };
  68737. var serializeMesh = function (mesh, serializationScene) {
  68738. var serializationObject = {};
  68739. // Geometry
  68740. var geometry = mesh._geometry;
  68741. if (geometry) {
  68742. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  68743. // 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
  68744. serializeGeometry(geometry, serializationScene.geometries);
  68745. }
  68746. }
  68747. // Custom
  68748. if (mesh.serialize) {
  68749. mesh.serialize(serializationObject);
  68750. }
  68751. return serializationObject;
  68752. };
  68753. var finalizeSingleMesh = function (mesh, serializationObject) {
  68754. //only works if the mesh is already loaded
  68755. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  68756. //serialize material
  68757. if (mesh.material) {
  68758. if (mesh.material instanceof BABYLON.StandardMaterial) {
  68759. serializationObject.materials = serializationObject.materials || [];
  68760. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  68761. serializationObject.materials.push(mesh.material.serialize());
  68762. }
  68763. }
  68764. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  68765. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  68766. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  68767. serializationObject.multiMaterials.push(mesh.material.serialize());
  68768. }
  68769. }
  68770. }
  68771. //serialize geometry
  68772. var geometry = mesh._geometry;
  68773. if (geometry) {
  68774. if (!serializationObject.geometries) {
  68775. serializationObject.geometries = {};
  68776. serializationObject.geometries.boxes = [];
  68777. serializationObject.geometries.spheres = [];
  68778. serializationObject.geometries.cylinders = [];
  68779. serializationObject.geometries.toruses = [];
  68780. serializationObject.geometries.grounds = [];
  68781. serializationObject.geometries.planes = [];
  68782. serializationObject.geometries.torusKnots = [];
  68783. serializationObject.geometries.vertexData = [];
  68784. }
  68785. serializeGeometry(geometry, serializationObject.geometries);
  68786. }
  68787. // Skeletons
  68788. if (mesh.skeleton) {
  68789. serializationObject.skeletons = serializationObject.skeletons || [];
  68790. serializationObject.skeletons.push(mesh.skeleton.serialize());
  68791. }
  68792. //serialize the actual mesh
  68793. serializationObject.meshes = serializationObject.meshes || [];
  68794. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  68795. }
  68796. };
  68797. var SceneSerializer = (function () {
  68798. function SceneSerializer() {
  68799. }
  68800. SceneSerializer.ClearCache = function () {
  68801. serializedGeometries = [];
  68802. };
  68803. SceneSerializer.Serialize = function (scene) {
  68804. var serializationObject = {};
  68805. SceneSerializer.ClearCache();
  68806. // Scene
  68807. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  68808. serializationObject.autoClear = scene.autoClear;
  68809. serializationObject.clearColor = scene.clearColor.asArray();
  68810. serializationObject.ambientColor = scene.ambientColor.asArray();
  68811. serializationObject.gravity = scene.gravity.asArray();
  68812. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  68813. serializationObject.workerCollisions = scene.workerCollisions;
  68814. // Fog
  68815. if (scene.fogMode && scene.fogMode !== 0) {
  68816. serializationObject.fogMode = scene.fogMode;
  68817. serializationObject.fogColor = scene.fogColor.asArray();
  68818. serializationObject.fogStart = scene.fogStart;
  68819. serializationObject.fogEnd = scene.fogEnd;
  68820. serializationObject.fogDensity = scene.fogDensity;
  68821. }
  68822. //Physics
  68823. if (scene.isPhysicsEnabled()) {
  68824. serializationObject.physicsEnabled = true;
  68825. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  68826. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  68827. }
  68828. // Metadata
  68829. if (scene.metadata) {
  68830. serializationObject.metadata = scene.metadata;
  68831. }
  68832. // Morph targets
  68833. serializationObject.morphTargetManagers = [];
  68834. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  68835. var abstractMesh = _a[_i];
  68836. var manager = abstractMesh.morphTargetManager;
  68837. if (manager) {
  68838. serializationObject.morphTargetManagers.push(manager.serialize());
  68839. }
  68840. }
  68841. // Lights
  68842. serializationObject.lights = [];
  68843. var index;
  68844. var light;
  68845. for (index = 0; index < scene.lights.length; index++) {
  68846. light = scene.lights[index];
  68847. if (!light.doNotSerialize) {
  68848. serializationObject.lights.push(light.serialize());
  68849. }
  68850. }
  68851. // Cameras
  68852. serializationObject.cameras = [];
  68853. for (index = 0; index < scene.cameras.length; index++) {
  68854. var camera = scene.cameras[index];
  68855. if (!camera.doNotSerialize) {
  68856. serializationObject.cameras.push(camera.serialize());
  68857. }
  68858. }
  68859. if (scene.activeCamera) {
  68860. serializationObject.activeCameraID = scene.activeCamera.id;
  68861. }
  68862. // Animations
  68863. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  68864. // Materials
  68865. serializationObject.materials = [];
  68866. serializationObject.multiMaterials = [];
  68867. var material;
  68868. for (index = 0; index < scene.materials.length; index++) {
  68869. material = scene.materials[index];
  68870. if (!material.doNotSerialize) {
  68871. serializationObject.materials.push(material.serialize());
  68872. }
  68873. }
  68874. // MultiMaterials
  68875. serializationObject.multiMaterials = [];
  68876. for (index = 0; index < scene.multiMaterials.length; index++) {
  68877. var multiMaterial = scene.multiMaterials[index];
  68878. serializationObject.multiMaterials.push(multiMaterial.serialize());
  68879. }
  68880. // Skeletons
  68881. serializationObject.skeletons = [];
  68882. for (index = 0; index < scene.skeletons.length; index++) {
  68883. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  68884. }
  68885. // Geometries
  68886. serializationObject.geometries = {};
  68887. serializationObject.geometries.boxes = [];
  68888. serializationObject.geometries.spheres = [];
  68889. serializationObject.geometries.cylinders = [];
  68890. serializationObject.geometries.toruses = [];
  68891. serializationObject.geometries.grounds = [];
  68892. serializationObject.geometries.planes = [];
  68893. serializationObject.geometries.torusKnots = [];
  68894. serializationObject.geometries.vertexData = [];
  68895. serializedGeometries = [];
  68896. var geometries = scene.getGeometries();
  68897. for (index = 0; index < geometries.length; index++) {
  68898. var geometry = geometries[index];
  68899. if (geometry.isReady()) {
  68900. serializeGeometry(geometry, serializationObject.geometries);
  68901. }
  68902. }
  68903. // Meshes
  68904. serializationObject.meshes = [];
  68905. for (index = 0; index < scene.meshes.length; index++) {
  68906. var abstractMesh = scene.meshes[index];
  68907. if (abstractMesh instanceof BABYLON.Mesh) {
  68908. var mesh = abstractMesh;
  68909. if (!mesh.doNotSerialize) {
  68910. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  68911. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  68912. }
  68913. }
  68914. }
  68915. }
  68916. // Particles Systems
  68917. serializationObject.particleSystems = [];
  68918. for (index = 0; index < scene.particleSystems.length; index++) {
  68919. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  68920. }
  68921. // Lens flares
  68922. serializationObject.lensFlareSystems = [];
  68923. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  68924. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  68925. }
  68926. // Shadows
  68927. serializationObject.shadowGenerators = [];
  68928. for (index = 0; index < scene.lights.length; index++) {
  68929. light = scene.lights[index];
  68930. var shadowGenerator = light.getShadowGenerator();
  68931. if (shadowGenerator) {
  68932. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  68933. }
  68934. }
  68935. // Action Manager
  68936. if (scene.actionManager) {
  68937. serializationObject.actions = scene.actionManager.serialize("scene");
  68938. }
  68939. // Audio
  68940. serializationObject.sounds = [];
  68941. for (index = 0; index < scene.soundTracks.length; index++) {
  68942. var soundtrack = scene.soundTracks[index];
  68943. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  68944. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  68945. }
  68946. }
  68947. return serializationObject;
  68948. };
  68949. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  68950. if (withParents === void 0) { withParents = false; }
  68951. if (withChildren === void 0) { withChildren = false; }
  68952. var serializationObject = {};
  68953. SceneSerializer.ClearCache();
  68954. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  68955. if (withParents || withChildren) {
  68956. //deliberate for loop! not for each, appended should be processed as well.
  68957. for (var i = 0; i < toSerialize.length; ++i) {
  68958. if (withChildren) {
  68959. toSerialize[i].getDescendants().forEach(function (node) {
  68960. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  68961. toSerialize.push(node);
  68962. }
  68963. });
  68964. }
  68965. //make sure the array doesn't contain the object already
  68966. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  68967. toSerialize.push(toSerialize[i].parent);
  68968. }
  68969. }
  68970. }
  68971. toSerialize.forEach(function (mesh) {
  68972. finalizeSingleMesh(mesh, serializationObject);
  68973. });
  68974. return serializationObject;
  68975. };
  68976. return SceneSerializer;
  68977. }());
  68978. BABYLON.SceneSerializer = SceneSerializer;
  68979. })(BABYLON || (BABYLON = {}));
  68980. //# sourceMappingURL=babylon.sceneSerializer.js.map
  68981. var BABYLON;
  68982. (function (BABYLON) {
  68983. var ReflectionProbe = (function () {
  68984. function ReflectionProbe(name, size, scene, generateMipMaps) {
  68985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68986. var _this = this;
  68987. this.name = name;
  68988. this._viewMatrix = BABYLON.Matrix.Identity();
  68989. this._target = BABYLON.Vector3.Zero();
  68990. this._add = BABYLON.Vector3.Zero();
  68991. this.invertYAxis = false;
  68992. this.position = BABYLON.Vector3.Zero();
  68993. this._scene = scene;
  68994. this._scene.reflectionProbes.push(this);
  68995. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  68996. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  68997. switch (faceIndex) {
  68998. case 0:
  68999. _this._add.copyFromFloats(1, 0, 0);
  69000. break;
  69001. case 1:
  69002. _this._add.copyFromFloats(-1, 0, 0);
  69003. break;
  69004. case 2:
  69005. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  69006. break;
  69007. case 3:
  69008. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  69009. break;
  69010. case 4:
  69011. _this._add.copyFromFloats(0, 0, 1);
  69012. break;
  69013. case 5:
  69014. _this._add.copyFromFloats(0, 0, -1);
  69015. break;
  69016. }
  69017. if (_this._attachedMesh) {
  69018. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  69019. }
  69020. _this.position.addToRef(_this._add, _this._target);
  69021. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  69022. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  69023. });
  69024. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  69025. scene.updateTransformMatrix(true);
  69026. });
  69027. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69028. }
  69029. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  69030. get: function () {
  69031. return this._renderTargetTexture.samples;
  69032. },
  69033. set: function (value) {
  69034. this._renderTargetTexture.samples = value;
  69035. },
  69036. enumerable: true,
  69037. configurable: true
  69038. });
  69039. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  69040. get: function () {
  69041. return this._renderTargetTexture.refreshRate;
  69042. },
  69043. set: function (value) {
  69044. this._renderTargetTexture.refreshRate = value;
  69045. },
  69046. enumerable: true,
  69047. configurable: true
  69048. });
  69049. ReflectionProbe.prototype.getScene = function () {
  69050. return this._scene;
  69051. };
  69052. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  69053. get: function () {
  69054. return this._renderTargetTexture;
  69055. },
  69056. enumerable: true,
  69057. configurable: true
  69058. });
  69059. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  69060. get: function () {
  69061. return this._renderTargetTexture.renderList;
  69062. },
  69063. enumerable: true,
  69064. configurable: true
  69065. });
  69066. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  69067. this._attachedMesh = mesh;
  69068. };
  69069. /**
  69070. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  69071. *
  69072. * @param renderingGroupId The rendering group id corresponding to its index
  69073. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  69074. */
  69075. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  69076. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  69077. };
  69078. ReflectionProbe.prototype.dispose = function () {
  69079. var index = this._scene.reflectionProbes.indexOf(this);
  69080. if (index !== -1) {
  69081. // Remove from the scene if found
  69082. this._scene.reflectionProbes.splice(index, 1);
  69083. }
  69084. if (this._renderTargetTexture) {
  69085. this._renderTargetTexture.dispose();
  69086. this._renderTargetTexture = null;
  69087. }
  69088. };
  69089. return ReflectionProbe;
  69090. }());
  69091. BABYLON.ReflectionProbe = ReflectionProbe;
  69092. })(BABYLON || (BABYLON = {}));
  69093. //# sourceMappingURL=babylon.reflectionProbe.js.map
  69094. var BABYLON;
  69095. (function (BABYLON) {
  69096. var Layer = (function () {
  69097. function Layer(name, imgUrl, scene, isBackground, color) {
  69098. this.name = name;
  69099. this.scale = new BABYLON.Vector2(1, 1);
  69100. this.offset = new BABYLON.Vector2(0, 0);
  69101. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  69102. this.layerMask = 0x0FFFFFFF;
  69103. this._vertexBuffers = {};
  69104. // Events
  69105. /**
  69106. * An event triggered when the layer is disposed.
  69107. * @type {BABYLON.Observable}
  69108. */
  69109. this.onDisposeObservable = new BABYLON.Observable();
  69110. /**
  69111. * An event triggered before rendering the scene
  69112. * @type {BABYLON.Observable}
  69113. */
  69114. this.onBeforeRenderObservable = new BABYLON.Observable();
  69115. /**
  69116. * An event triggered after rendering the scene
  69117. * @type {BABYLON.Observable}
  69118. */
  69119. this.onAfterRenderObservable = new BABYLON.Observable();
  69120. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  69121. this.isBackground = isBackground === undefined ? true : isBackground;
  69122. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  69123. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69124. this._scene.layers.push(this);
  69125. var engine = this._scene.getEngine();
  69126. // VBO
  69127. var vertices = [];
  69128. vertices.push(1, 1);
  69129. vertices.push(-1, 1);
  69130. vertices.push(-1, -1);
  69131. vertices.push(1, -1);
  69132. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69133. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  69134. // Indices
  69135. var indices = [];
  69136. indices.push(0);
  69137. indices.push(1);
  69138. indices.push(2);
  69139. indices.push(0);
  69140. indices.push(2);
  69141. indices.push(3);
  69142. this._indexBuffer = engine.createIndexBuffer(indices);
  69143. // Effects
  69144. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  69145. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  69146. }
  69147. Object.defineProperty(Layer.prototype, "onDispose", {
  69148. set: function (callback) {
  69149. if (this._onDisposeObserver) {
  69150. this.onDisposeObservable.remove(this._onDisposeObserver);
  69151. }
  69152. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  69153. },
  69154. enumerable: true,
  69155. configurable: true
  69156. });
  69157. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  69158. set: function (callback) {
  69159. if (this._onBeforeRenderObserver) {
  69160. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69161. }
  69162. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69163. },
  69164. enumerable: true,
  69165. configurable: true
  69166. });
  69167. Object.defineProperty(Layer.prototype, "onAfterRender", {
  69168. set: function (callback) {
  69169. if (this._onAfterRenderObserver) {
  69170. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69171. }
  69172. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69173. },
  69174. enumerable: true,
  69175. configurable: true
  69176. });
  69177. Layer.prototype.render = function () {
  69178. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  69179. // Check
  69180. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  69181. return;
  69182. var engine = this._scene.getEngine();
  69183. this.onBeforeRenderObservable.notifyObservers(this);
  69184. // Render
  69185. engine.enableEffect(currentEffect);
  69186. engine.setState(false);
  69187. // Texture
  69188. currentEffect.setTexture("textureSampler", this.texture);
  69189. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  69190. // Color
  69191. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  69192. // Scale / offset
  69193. currentEffect.setVector2("offset", this.offset);
  69194. currentEffect.setVector2("scale", this.scale);
  69195. // VBOs
  69196. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69197. // Draw order
  69198. if (!this.alphaTest) {
  69199. engine.setAlphaMode(this.alphaBlendingMode);
  69200. engine.draw(true, 0, 6);
  69201. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69202. }
  69203. else {
  69204. engine.draw(true, 0, 6);
  69205. }
  69206. this.onAfterRenderObservable.notifyObservers(this);
  69207. };
  69208. Layer.prototype.dispose = function () {
  69209. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69210. if (vertexBuffer) {
  69211. vertexBuffer.dispose();
  69212. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69213. }
  69214. if (this._indexBuffer) {
  69215. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69216. this._indexBuffer = null;
  69217. }
  69218. if (this.texture) {
  69219. this.texture.dispose();
  69220. this.texture = null;
  69221. }
  69222. // Remove from scene
  69223. var index = this._scene.layers.indexOf(this);
  69224. this._scene.layers.splice(index, 1);
  69225. // Callback
  69226. this.onDisposeObservable.notifyObservers(this);
  69227. this.onDisposeObservable.clear();
  69228. this.onAfterRenderObservable.clear();
  69229. this.onBeforeRenderObservable.clear();
  69230. };
  69231. return Layer;
  69232. }());
  69233. BABYLON.Layer = Layer;
  69234. })(BABYLON || (BABYLON = {}));
  69235. //# sourceMappingURL=babylon.layer.js.map
  69236. var BABYLON;
  69237. (function (BABYLON) {
  69238. var TextureTools = (function () {
  69239. function TextureTools() {
  69240. }
  69241. /**
  69242. * Uses the GPU to create a copy texture rescaled at a given size
  69243. * @param texture Texture to copy from
  69244. * @param width Desired width
  69245. * @param height Desired height
  69246. * @return Generated texture
  69247. */
  69248. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  69249. if (useBilinearMode === void 0) { useBilinearMode = true; }
  69250. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  69251. var scene = texture.getScene();
  69252. var engine = scene.getEngine();
  69253. rtt.wrapU = texture.wrapU;
  69254. rtt.wrapV = texture.wrapV;
  69255. rtt.uOffset = texture.uOffset;
  69256. rtt.vOffset = texture.vOffset;
  69257. rtt.uScale = texture.uScale;
  69258. rtt.vScale = texture.vScale;
  69259. rtt.uAng = texture.uAng;
  69260. rtt.vAng = texture.vAng;
  69261. rtt.wAng = texture.wAng;
  69262. rtt.coordinatesIndex = texture.coordinatesIndex;
  69263. rtt.level = texture.level;
  69264. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  69265. rtt._texture.isReady = false;
  69266. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69267. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69268. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69269. passPostProcess.getEffect().executeWhenCompiled(function () {
  69270. passPostProcess.onApply = function (effect) {
  69271. effect.setTexture("textureSampler", texture);
  69272. };
  69273. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  69274. engine.unBindFramebuffer(rtt.getInternalTexture());
  69275. rtt.disposeFramebufferObjects();
  69276. passPostProcess.dispose();
  69277. rtt._texture.isReady = true;
  69278. });
  69279. return rtt;
  69280. };
  69281. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  69282. if (!scene._environmentBRDFTexture) {
  69283. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69284. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69285. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69286. scene._environmentBRDFTexture = texture;
  69287. }
  69288. return scene._environmentBRDFTexture;
  69289. };
  69290. 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=";
  69291. return TextureTools;
  69292. }());
  69293. BABYLON.TextureTools = TextureTools;
  69294. })(BABYLON || (BABYLON = {}));
  69295. //# sourceMappingURL=babylon.textureTools.js.map
  69296. var BABYLON;
  69297. (function (BABYLON) {
  69298. var FramingBehavior = (function () {
  69299. function FramingBehavior() {
  69300. this._mode = FramingBehavior.FitFrustumSidesMode;
  69301. this._radiusScale = 1.0;
  69302. this._positionScale = 0.5;
  69303. this._defaultElevation = 0.3;
  69304. this._elevationReturnTime = 1500;
  69305. this._elevationReturnWaitTime = 1000;
  69306. this._zoomStopsAnimation = false;
  69307. this._framingTime = 1500;
  69308. this._isPointerDown = false;
  69309. this._lastFrameTime = null;
  69310. this._lastInteractionTime = -Infinity;
  69311. // Framing control
  69312. this._animatables = new Array();
  69313. this._betaIsAnimating = false;
  69314. this._lastFrameRadius = 0;
  69315. }
  69316. Object.defineProperty(FramingBehavior.prototype, "name", {
  69317. get: function () {
  69318. return "Framing";
  69319. },
  69320. enumerable: true,
  69321. configurable: true
  69322. });
  69323. Object.defineProperty(FramingBehavior.prototype, "mode", {
  69324. /**
  69325. * Gets current mode used by the behavior.
  69326. */
  69327. get: function () {
  69328. return this._mode;
  69329. },
  69330. /**
  69331. * Sets the current mode used by the behavior
  69332. */
  69333. set: function (mode) {
  69334. this._mode = mode;
  69335. },
  69336. enumerable: true,
  69337. configurable: true
  69338. });
  69339. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  69340. /**
  69341. * Gets the scale applied to the radius
  69342. */
  69343. get: function () {
  69344. return this._radiusScale;
  69345. },
  69346. /**
  69347. * Sets the scale applied to the radius (1 by default)
  69348. */
  69349. set: function (radius) {
  69350. this._radiusScale = radius;
  69351. },
  69352. enumerable: true,
  69353. configurable: true
  69354. });
  69355. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  69356. /**
  69357. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  69358. */
  69359. get: function () {
  69360. return this._positionScale;
  69361. },
  69362. /**
  69363. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  69364. */
  69365. set: function (scale) {
  69366. this._positionScale = scale;
  69367. },
  69368. enumerable: true,
  69369. configurable: true
  69370. });
  69371. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  69372. /**
  69373. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  69374. * behaviour is triggered, in radians.
  69375. */
  69376. get: function () {
  69377. return this._defaultElevation;
  69378. },
  69379. /**
  69380. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  69381. * behaviour is triggered, in radians.
  69382. */
  69383. set: function (elevation) {
  69384. this._defaultElevation = elevation;
  69385. },
  69386. enumerable: true,
  69387. configurable: true
  69388. });
  69389. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  69390. /**
  69391. * Gets the time (in milliseconds) taken to return to the default beta position.
  69392. * Negative value indicates camera should not return to default.
  69393. */
  69394. get: function () {
  69395. return this._elevationReturnTime;
  69396. },
  69397. /**
  69398. * Sets the time (in milliseconds) taken to return to the default beta position.
  69399. * Negative value indicates camera should not return to default.
  69400. */
  69401. set: function (speed) {
  69402. this._elevationReturnTime = speed;
  69403. },
  69404. enumerable: true,
  69405. configurable: true
  69406. });
  69407. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  69408. /**
  69409. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  69410. */
  69411. get: function () {
  69412. return this._elevationReturnWaitTime;
  69413. },
  69414. /**
  69415. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  69416. */
  69417. set: function (time) {
  69418. this._elevationReturnWaitTime = time;
  69419. },
  69420. enumerable: true,
  69421. configurable: true
  69422. });
  69423. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  69424. /**
  69425. * Gets the flag that indicates if user zooming should stop animation.
  69426. */
  69427. get: function () {
  69428. return this._zoomStopsAnimation;
  69429. },
  69430. /**
  69431. * Sets the flag that indicates if user zooming should stop animation.
  69432. */
  69433. set: function (flag) {
  69434. this._zoomStopsAnimation = flag;
  69435. },
  69436. enumerable: true,
  69437. configurable: true
  69438. });
  69439. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  69440. /**
  69441. * Gets the transition time when framing the mesh, in milliseconds
  69442. */
  69443. get: function () {
  69444. return this._framingTime;
  69445. },
  69446. /**
  69447. * Sets the transition time when framing the mesh, in milliseconds
  69448. */
  69449. set: function (time) {
  69450. this._framingTime = time;
  69451. },
  69452. enumerable: true,
  69453. configurable: true
  69454. });
  69455. FramingBehavior.prototype.attach = function (camera) {
  69456. var _this = this;
  69457. this._attachedCamera = camera;
  69458. var scene = this._attachedCamera.getScene();
  69459. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  69460. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  69461. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69462. _this._isPointerDown = true;
  69463. return;
  69464. }
  69465. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  69466. _this._isPointerDown = false;
  69467. }
  69468. });
  69469. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  69470. if (mesh) {
  69471. _this.zoomOnMesh(mesh);
  69472. }
  69473. });
  69474. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  69475. // Stop the animation if there is user interaction and the animation should stop for this interaction
  69476. _this._applyUserInteraction();
  69477. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  69478. // back to the default position after a given timeout
  69479. _this._maintainCameraAboveGround();
  69480. });
  69481. };
  69482. FramingBehavior.prototype.detach = function (camera) {
  69483. var scene = this._attachedCamera.getScene();
  69484. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  69485. camera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  69486. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  69487. };
  69488. /**
  69489. * Targets the given mesh and updates zoom level accordingly.
  69490. * @param mesh The mesh to target.
  69491. * @param radius Optional. If a cached radius position already exists, overrides default.
  69492. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  69493. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  69494. */
  69495. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  69496. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  69497. mesh.computeWorldMatrix(true);
  69498. var boundingBox = mesh.getBoundingInfo().boundingBox;
  69499. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  69500. };
  69501. /**
  69502. * Targets the given mesh and updates zoom level accordingly.
  69503. * @param mesh The mesh to target.
  69504. * @param radius Optional. If a cached radius position already exists, overrides default.
  69505. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  69506. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  69507. */
  69508. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  69509. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  69510. var zoomTarget;
  69511. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  69512. var bottom = minimumWorld.y;
  69513. var top = maximumWorld.y;
  69514. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  69515. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  69516. if (focusOnOriginXZ) {
  69517. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  69518. }
  69519. else {
  69520. var centerWorld = minimumWorld.add(radiusWorld);
  69521. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  69522. }
  69523. if (!this._vectorTransition) {
  69524. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  69525. }
  69526. this._betaIsAnimating = true;
  69527. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  69528. // sets the radius and lower radius bounds
  69529. // Small delta ensures camera is not always at lower zoom limit.
  69530. var delta = 0.1;
  69531. var radius = 0;
  69532. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  69533. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  69534. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  69535. radius = position;
  69536. }
  69537. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  69538. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  69539. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  69540. }
  69541. // transition to new radius
  69542. if (!this._radiusTransition) {
  69543. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  69544. }
  69545. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  69546. };
  69547. /**
  69548. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  69549. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  69550. * frustum width.
  69551. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  69552. * to fully enclose the mesh in the viewing frustum.
  69553. */
  69554. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  69555. var size = maximumWorld.subtract(minimumWorld);
  69556. var boxVectorGlobalDiagonal = size.length();
  69557. var frustumSlope = this._getFrustumSlope();
  69558. // Formula for setting distance
  69559. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  69560. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  69561. // Horizon distance
  69562. var radius = radiusWithoutFraming * this._radiusScale;
  69563. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  69564. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  69565. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  69566. var camera = this._attachedCamera;
  69567. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  69568. // Don't exceed the requested limit
  69569. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  69570. }
  69571. // Don't exceed the upper radius limit
  69572. if (camera.upperRadiusLimit) {
  69573. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  69574. }
  69575. return distance;
  69576. };
  69577. /**
  69578. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  69579. * is automatically returned to its default position (expected to be above ground plane).
  69580. */
  69581. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  69582. var _this = this;
  69583. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  69584. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  69585. var limitBeta = Math.PI * 0.5;
  69586. // Bring the camera back up if below the ground plane
  69587. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  69588. this._betaIsAnimating = true;
  69589. //Transition to new position
  69590. this.stopAllAnimations();
  69591. if (!this._betaTransition) {
  69592. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  69593. }
  69594. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  69595. _this._clearAnimationLocks();
  69596. _this.stopAllAnimations();
  69597. }));
  69598. }
  69599. };
  69600. /**
  69601. * Returns the frustum slope based on the canvas ratio and camera FOV
  69602. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  69603. */
  69604. FramingBehavior.prototype._getFrustumSlope = function () {
  69605. // Calculate the viewport ratio
  69606. // Aspect Ratio is Height/Width.
  69607. var camera = this._attachedCamera;
  69608. var engine = camera.getScene().getEngine();
  69609. var aspectRatio = engine.getAspectRatio(camera);
  69610. // Camera FOV is the vertical field of view (top-bottom) in radians.
  69611. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  69612. var frustumSlopeY = Math.tan(camera.fov / 2);
  69613. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  69614. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  69615. // along the forward vector.
  69616. var frustumSlopeX = frustumSlopeY * aspectRatio;
  69617. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  69618. };
  69619. /**
  69620. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  69621. */
  69622. FramingBehavior.prototype._clearAnimationLocks = function () {
  69623. this._betaIsAnimating = false;
  69624. };
  69625. /**
  69626. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  69627. */
  69628. FramingBehavior.prototype._applyUserInteraction = function () {
  69629. if (this.isUserIsMoving) {
  69630. this._lastInteractionTime = BABYLON.Tools.Now;
  69631. this.stopAllAnimations();
  69632. this._clearAnimationLocks();
  69633. }
  69634. };
  69635. /**
  69636. * Stops and removes all animations that have been applied to the camera
  69637. */
  69638. FramingBehavior.prototype.stopAllAnimations = function () {
  69639. this._attachedCamera.animations = [];
  69640. while (this._animatables.length) {
  69641. if (this._animatables[0]) {
  69642. this._animatables[0].onAnimationEnd = null;
  69643. this._animatables[0].stop();
  69644. }
  69645. this._animatables.shift();
  69646. }
  69647. };
  69648. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  69649. /**
  69650. * Gets a value indicating if the user is moving the camera
  69651. */
  69652. get: function () {
  69653. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  69654. this._attachedCamera.inertialBetaOffset !== 0 ||
  69655. this._attachedCamera.inertialRadiusOffset !== 0 ||
  69656. this._attachedCamera.inertialPanningX !== 0 ||
  69657. this._attachedCamera.inertialPanningY !== 0 ||
  69658. this._isPointerDown;
  69659. },
  69660. enumerable: true,
  69661. configurable: true
  69662. });
  69663. /**
  69664. * The easing function used by animations
  69665. */
  69666. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  69667. /**
  69668. * The easing mode used by animations
  69669. */
  69670. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  69671. // Statics
  69672. /**
  69673. * The camera can move all the way towards the mesh.
  69674. */
  69675. FramingBehavior.IgnoreBoundsSizeMode = 0;
  69676. /**
  69677. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  69678. */
  69679. FramingBehavior.FitFrustumSidesMode = 1;
  69680. return FramingBehavior;
  69681. }());
  69682. BABYLON.FramingBehavior = FramingBehavior;
  69683. })(BABYLON || (BABYLON = {}));
  69684. //# sourceMappingURL=babylon.framingBehavior.js.map
  69685. var BABYLON;
  69686. (function (BABYLON) {
  69687. /**
  69688. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  69689. */
  69690. var BouncingBehavior = (function () {
  69691. function BouncingBehavior() {
  69692. /**
  69693. * The duration of the animation, in milliseconds
  69694. */
  69695. this.transitionDuration = 450;
  69696. /**
  69697. * Length of the distance animated by the transition when lower radius is reached
  69698. */
  69699. this.lowerRadiusTransitionRange = 2;
  69700. /**
  69701. * Length of the distance animated by the transition when upper radius is reached
  69702. */
  69703. this.upperRadiusTransitionRange = -2;
  69704. this._autoTransitionRange = false;
  69705. // Animations
  69706. this._radiusIsAnimating = false;
  69707. this._radiusBounceTransition = null;
  69708. this._animatables = new Array();
  69709. }
  69710. Object.defineProperty(BouncingBehavior.prototype, "name", {
  69711. get: function () {
  69712. return "Bouncing";
  69713. },
  69714. enumerable: true,
  69715. configurable: true
  69716. });
  69717. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  69718. /**
  69719. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  69720. */
  69721. get: function () {
  69722. return this._autoTransitionRange;
  69723. },
  69724. /**
  69725. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  69726. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  69727. */
  69728. set: function (value) {
  69729. var _this = this;
  69730. if (this._autoTransitionRange === value) {
  69731. return;
  69732. }
  69733. this._autoTransitionRange = value;
  69734. var camera = this._attachedCamera;
  69735. if (value) {
  69736. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  69737. if (!mesh) {
  69738. return;
  69739. }
  69740. mesh.computeWorldMatrix(true);
  69741. var diagonal = mesh.getBoundingInfo().diagonalLength;
  69742. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  69743. _this.upperRadiusTransitionRange = diagonal * 0.05;
  69744. });
  69745. }
  69746. else if (this._onMeshTargetChangedObserver) {
  69747. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  69748. }
  69749. },
  69750. enumerable: true,
  69751. configurable: true
  69752. });
  69753. BouncingBehavior.prototype.attach = function (camera) {
  69754. var _this = this;
  69755. this._attachedCamera = camera;
  69756. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  69757. // Add the bounce animation to the lower radius limit
  69758. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  69759. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  69760. }
  69761. // Add the bounce animation to the upper radius limit
  69762. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  69763. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  69764. }
  69765. });
  69766. };
  69767. BouncingBehavior.prototype.detach = function (camera) {
  69768. camera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  69769. if (this._onMeshTargetChangedObserver) {
  69770. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  69771. }
  69772. };
  69773. /**
  69774. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  69775. * @param radiusLimit The limit to check against.
  69776. * @return Bool to indicate if at limit.
  69777. */
  69778. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  69779. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  69780. return true;
  69781. }
  69782. return false;
  69783. };
  69784. /**
  69785. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  69786. * @param radiusDelta The delta by which to animate to. Can be negative.
  69787. */
  69788. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  69789. var _this = this;
  69790. if (!this._radiusBounceTransition) {
  69791. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  69792. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  69793. }
  69794. // Prevent zoom until bounce has completed
  69795. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  69796. this._attachedCamera.wheelPrecision = Infinity;
  69797. this._attachedCamera.inertialRadiusOffset = 0;
  69798. // Animate to the radius limit
  69799. this.stopAllAnimations();
  69800. this._radiusIsAnimating = true;
  69801. this._animatables.push(BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }));
  69802. };
  69803. /**
  69804. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  69805. */
  69806. BouncingBehavior.prototype._clearAnimationLocks = function () {
  69807. this._radiusIsAnimating = false;
  69808. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  69809. };
  69810. /**
  69811. * Stops and removes all animations that have been applied to the camera
  69812. */
  69813. BouncingBehavior.prototype.stopAllAnimations = function () {
  69814. this._attachedCamera.animations = [];
  69815. while (this._animatables.length) {
  69816. this._animatables[0].onAnimationEnd = null;
  69817. this._animatables[0].stop();
  69818. this._animatables.shift();
  69819. }
  69820. };
  69821. /**
  69822. * The easing function used by animations
  69823. */
  69824. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  69825. /**
  69826. * The easing mode used by animations
  69827. */
  69828. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  69829. return BouncingBehavior;
  69830. }());
  69831. BABYLON.BouncingBehavior = BouncingBehavior;
  69832. })(BABYLON || (BABYLON = {}));
  69833. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  69834. var BABYLON;
  69835. (function (BABYLON) {
  69836. var AutoRotationBehavior = (function () {
  69837. function AutoRotationBehavior() {
  69838. this._zoomStopsAnimation = false;
  69839. this._idleRotationSpeed = 0.05;
  69840. this._idleRotationWaitTime = 2000;
  69841. this._idleRotationSpinupTime = 2000;
  69842. this._isPointerDown = false;
  69843. this._lastFrameTime = null;
  69844. this._lastInteractionTime = -Infinity;
  69845. this._cameraRotationSpeed = 0;
  69846. this._lastFrameRadius = 0;
  69847. }
  69848. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  69849. get: function () {
  69850. return "AutoRotation";
  69851. },
  69852. enumerable: true,
  69853. configurable: true
  69854. });
  69855. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  69856. /**
  69857. * Gets the flag that indicates if user zooming should stop animation.
  69858. */
  69859. get: function () {
  69860. return this._zoomStopsAnimation;
  69861. },
  69862. /**
  69863. * Sets the flag that indicates if user zooming should stop animation.
  69864. */
  69865. set: function (flag) {
  69866. this._zoomStopsAnimation = flag;
  69867. },
  69868. enumerable: true,
  69869. configurable: true
  69870. });
  69871. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  69872. /**
  69873. * Gets the default speed at which the camera rotates around the model.
  69874. */
  69875. get: function () {
  69876. return this._idleRotationSpeed;
  69877. },
  69878. /**
  69879. * Sets the default speed at which the camera rotates around the model.
  69880. */
  69881. set: function (speed) {
  69882. this._idleRotationSpeed = speed;
  69883. },
  69884. enumerable: true,
  69885. configurable: true
  69886. });
  69887. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  69888. /**
  69889. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  69890. */
  69891. get: function () {
  69892. return this._idleRotationWaitTime;
  69893. },
  69894. /**
  69895. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  69896. */
  69897. set: function (time) {
  69898. this._idleRotationWaitTime = time;
  69899. },
  69900. enumerable: true,
  69901. configurable: true
  69902. });
  69903. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  69904. /**
  69905. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  69906. */
  69907. get: function () {
  69908. return this._idleRotationSpinupTime;
  69909. },
  69910. /**
  69911. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  69912. */
  69913. set: function (time) {
  69914. this._idleRotationSpinupTime = time;
  69915. },
  69916. enumerable: true,
  69917. configurable: true
  69918. });
  69919. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  69920. /**
  69921. * Gets a value indicating if the camera is currently rotating because of this behavior
  69922. */
  69923. get: function () {
  69924. return Math.abs(this._cameraRotationSpeed) > 0;
  69925. },
  69926. enumerable: true,
  69927. configurable: true
  69928. });
  69929. AutoRotationBehavior.prototype.attach = function (camera) {
  69930. var _this = this;
  69931. this._attachedCamera = camera;
  69932. var scene = this._attachedCamera.getScene();
  69933. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  69934. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69935. _this._isPointerDown = true;
  69936. return;
  69937. }
  69938. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  69939. _this._isPointerDown = false;
  69940. }
  69941. });
  69942. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  69943. var now = BABYLON.Tools.Now;
  69944. var dt = 16;
  69945. if (_this._lastFrameTime != null) {
  69946. dt = now - _this._lastFrameTime;
  69947. }
  69948. _this._lastFrameTime = now;
  69949. // Stop the animation if there is user interaction and the animation should stop for this interaction
  69950. _this._applyUserInteraction();
  69951. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  69952. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  69953. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  69954. // Step camera rotation by rotation speed
  69955. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  69956. });
  69957. };
  69958. AutoRotationBehavior.prototype.detach = function (camera) {
  69959. var scene = this._attachedCamera.getScene();
  69960. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  69961. camera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  69962. };
  69963. /**
  69964. * Returns true if user is scrolling.
  69965. * @return true if user is scrolling.
  69966. */
  69967. AutoRotationBehavior.prototype._userIsZooming = function () {
  69968. return this._attachedCamera.inertialRadiusOffset !== 0;
  69969. };
  69970. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  69971. var zoomHasHitLimit = false;
  69972. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  69973. zoomHasHitLimit = true;
  69974. }
  69975. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  69976. this._lastFrameRadius = this._attachedCamera.radius;
  69977. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  69978. };
  69979. /**
  69980. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  69981. */
  69982. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  69983. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  69984. this._lastInteractionTime = BABYLON.Tools.Now;
  69985. }
  69986. };
  69987. // Tools
  69988. AutoRotationBehavior.prototype._userIsMoving = function () {
  69989. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  69990. this._attachedCamera.inertialBetaOffset !== 0 ||
  69991. this._attachedCamera.inertialRadiusOffset !== 0 ||
  69992. this._attachedCamera.inertialPanningX !== 0 ||
  69993. this._attachedCamera.inertialPanningY !== 0 ||
  69994. this._isPointerDown;
  69995. };
  69996. return AutoRotationBehavior;
  69997. }());
  69998. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  69999. })(BABYLON || (BABYLON = {}));
  70000. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  70001. 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}"};
  70002. 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};"};
  70003. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  70004. module.exports = BABYLON;
  70005. };